From ba229230144f00d35d55e31a80ca2576bd831448 Mon Sep 17 00:00:00 2001 From: Tal Gitelman Date: Mon, 7 Aug 2017 17:59:54 +0300 Subject: [SDC] sync Change-Id: I150c22c816c52cc142e8d0f3c92e5df7ecea4e3c Signed-off-by: Tal Gitelman --- .../execute/artifacts/ValidateArtResponse.java | 15 +- .../config/ValidationToolConfiguration.java | 7 - asdctool/src/main/resources/config/logback.xml | 24 - .../sdc/be/components/impl/BaseBusinessLogic.java | 29 +- .../be/components/impl/GroupTypeImportManager.java | 27 +- .../components/impl/PolicyTypeImportManager.java | 24 +- .../be/components/impl/ProductBusinessLogic.java | 1 - .../be/components/impl/PropertyBusinessLogic.java | 39 +- .../components/impl/RequirementsBusinessLogic.java | 55 - .../be/components/impl/ResourceBusinessLogic.java | 49 +- .../be/components/impl/ResourceImportManager.java | 51 +- .../ServiceComponentInstanceBusinessLogic.java | 4 - .../lifecycle/CertificationRequestTransition.java | 81 +- .../components/lifecycle/LifeCycleTransition.java | 1 - .../lifecycle/StartCertificationTransition.java | 8 +- .../sdc/be/listen/BEAppContextListener.java | 23 +- .../java/org/openecomp/sdc/be/tosca/CsarUtils.java | 50 +- .../sdc/be/components/GroupBusinessLogicTest.java | 2 +- .../be/components/PropertyBusinessLogicTest.java | 23 +- .../be/components/ResourceImportManagerTest.java | 1 - .../be/components/ServiceBusinessLogicTest.java | 37 +- .../components/impl/ArtifactBusinessLogicTest.java | 34 +- .../impl/ResourceInstanceBusinessLogicTest.java | 30 +- .../lifecycle/CertificationRequestTest.java | 19 +- .../be/components/lifecycle/LifecycleTestBase.java | 1 - .../org/openecomp/sdc/be/model/cache/jobs/Job.java | 1 - .../jsontitan/operations/GroupsOperation.java | 25 +- .../model/operations/api/IArtifactOperation.java | 32 - .../model/operations/api/IAttributeOperation.java | 71 - .../api/ICapabilityInstanceOperation.java | 130 - .../model/operations/api/ICapabilityOperation.java | 32 +- .../api/IComponentInstanceOperation.java | 152 - .../model/operations/api/IComponentOperation.java | 50 - .../operations/api/IGroupInstanceOperation.java | 44 +- .../be/model/operations/api/IGroupOperation.java | 61 - .../be/model/operations/api/IInputsOperation.java | 41 +- .../api/IInterfaceLifecycleOperation.java | 20 - .../model/operations/api/ILifecycleOperation.java | 56 - .../be/model/operations/api/IProductOperation.java | 46 - .../model/operations/api/IPropertyOperation.java | 29 - .../operations/api/IRequirementOperation.java | 75 - .../model/operations/api/IResourceOperation.java | 141 - .../be/model/operations/api/IServiceOperation.java | 78 - .../model/operations/api/IUserAdminOperation.java | 7 - .../api/ToscaDefinitionPathCalculator.java | 32 - .../model/operations/impl/AllOperationsUtil.java | 56 - .../model/operations/impl/ArtifactOperation.java | 572 +- .../model/operations/impl/AttributeOperation.java | 461 -- .../impl/CapabilityInstanceOperation.java | 1170 ---- .../model/operations/impl/CapabilityOperation.java | 1038 ---- .../operations/impl/CapabilityTypeOperation.java | 3 +- .../impl/ComponentInstanceOperation.java | 6267 ++------------------ .../model/operations/impl/ComponentOperation.java | 2964 --------- .../model/operations/impl/GraphLockOperation.java | 2 +- .../operations/impl/GroupInstanceOperation.java | 848 +-- .../be/model/operations/impl/GroupOperation.java | 1963 +----- .../be/model/operations/impl/InputsOperation.java | 1199 +--- .../impl/InterfaceLifecycleOperation.java | 198 - .../model/operations/impl/LifecycleOperation.java | 1077 ---- .../be/model/operations/impl/ProductOperation.java | 957 --- .../model/operations/impl/PropertyOperation.java | 27 +- .../operations/impl/RequirementOperation.java | 1419 ----- .../model/operations/impl/ResourceOperation.java | 3040 ---------- .../be/model/operations/impl/ServiceOperation.java | 1289 ---- .../impl/ToscaDefinitionPathCalculatorImpl.java | 47 - .../model/operations/impl/UserAdminOperation.java | 107 - .../migration/MigrationMalformedDataLogger.java | 67 - .../operations/utils/ComponentValidationUtils.java | 6 +- .../impl/AdditionalInformationOperationTest.java | 102 +- .../operations/impl/ArtifactOperationTest.java | 81 +- .../impl/ComponentInstanceOperationSpringTest.java | 513 -- .../impl/ComponentInstanceOperationTest.java | 127 - .../operations/impl/ComponentOperationTest.java | 359 -- .../operations/impl/InterfaceOperationTest.java | 27 +- .../operations/impl/LifecycleOperationTest.java | 1993 ------- .../operations/impl/RequirementOperationTest.java | 218 - .../impl/ResourceInstanceOperationTest.java | 2250 ------- .../operations/impl/ResourceOperationTest.java | 953 --- .../operations/impl/ServiceOperationTest.java | 884 --- .../impl/ToscaDefinitionPathCalculatorTest.java | 81 - .../operations/impl/UserAdminOperationTest.java | 57 +- .../recipes/BE_1_cleanup_jettydir.rb | 9 - .../recipes/BE_4_setup_configuration.rb | 14 - .../recipes/FE_1_cleanup_jettydir.rb | 8 + .../recipes/FE_2_setup_configuration.rb | 14 + .../default/FE-onboarding-configuration.yaml.erb | 5 + sdc-os-chef/sdc-frontend/startup.sh | 2 +- .../sdc/ci/tests/execute/sanity/Service.java | 12 + 88 files changed, 922 insertions(+), 33322 deletions(-) delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAttributeOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ToscaDefinitionPathCalculator.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AllOperationsUtil.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorImpl.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationMalformedDataLogger.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorTest.java create mode 100644 sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-onboarding-configuration.yaml.erb diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java index abbaa3050d..d3ff8b7957 100644 --- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java @@ -20,13 +20,6 @@ package org.openecomp.sdc.ci.tests.execute.artifacts; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.junit.Rule; import org.junit.rules.TestName; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; @@ -34,7 +27,6 @@ import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.impl.AllOperationsUtil; import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; @@ -53,6 +45,13 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + public class ValidateArtResponse extends ComponentBaseTest { @Rule diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfiguration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfiguration.java index 80e80ab472..0e6b2c7d16 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfiguration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfiguration.java @@ -16,8 +16,6 @@ import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.dao.titan.TitanGraphClient; import org.openecomp.sdc.be.model.DerivedNodeTypeResolver; import org.openecomp.sdc.be.model.jsontitan.operations.*; -import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator; -import org.openecomp.sdc.be.model.operations.impl.ToscaDefinitionPathCalculatorImpl; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -114,11 +112,6 @@ public class ValidationToolConfiguration { return new CategoryOperation(); } - @Bean(name = "tosca-path-calculator") - public ToscaDefinitionPathCalculator pathCalculator() { - return new ToscaDefinitionPathCalculatorImpl(); - } - @Bean(name = "artifacts-operation") public ArtifactsOperations artifactsOperation() { return new ArtifactsOperations(); diff --git a/asdctool/src/main/resources/config/logback.xml b/asdctool/src/main/resources/config/logback.xml index dadc5254a5..603d894317 100644 --- a/asdctool/src/main/resources/config/logback.xml +++ b/asdctool/src/main/resources/config/logback.xml @@ -45,34 +45,10 @@ - - ${HOME}/asdctool/logs/${ECOMP-component-name}/${ECOMP-subcomponent-name}/malformed-data.log - - - ${HOME}/asdctool/logs/${ECOMP-component-name}/${ECOMP-subcomponent-name}/malformed-data.log.%i - - 1 - 10 - - - - 20MB - - - ${default-log-pattern} - - - - - - - diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java index 1d153e0a5d..5a4961b24f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java @@ -20,12 +20,8 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.function.Function; - +import com.google.gson.JsonElement; +import fj.data.Either; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -40,26 +36,15 @@ import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupProperty; -import org.openecomp.sdc.be.model.IComplexDefaultValue; -import org.openecomp.sdc.be.model.IPropertyInputCommon; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.operations.api.IAttributeOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; import org.openecomp.sdc.be.model.operations.api.IGroupOperation; import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; -import org.openecomp.sdc.be.model.operations.api.IPropertyOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; @@ -80,9 +65,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.google.gson.JsonElement; - -import fj.data.Either; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.function.Function; public abstract class BaseBusinessLogic { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java index 3dee3839b1..2de9eee217 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java @@ -20,15 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -import javax.annotation.Resource; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; @@ -37,16 +29,21 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.GroupTypeDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; -import org.openecomp.sdc.be.model.operations.api.IResourceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; @Component("groupTypeImportManager") public class GroupTypeImportManager { @@ -69,13 +66,11 @@ public class GroupTypeImportManager { private static Logger log = LoggerFactory.getLogger(GroupTypeImportManager.class.getName()); @Resource - private PropertyOperation propertyOperation; - @Resource private IGroupTypeOperation groupTypeOperation; @Resource private ComponentsUtils componentsUtils; @Resource - private IResourceOperation resourceOperation; + private ToscaOperationFacade toscaOperationFacade; @Resource private CommonImportManager commonImportManager; @@ -103,7 +98,7 @@ public class GroupTypeImportManager { } else { for (String member : groupType.getMembers()) { // Verify that such Resource exist - Either eitherMemberExist = resourceOperation.getLatestByToscaResourceName(member, false); + Either eitherMemberExist = toscaOperationFacade.getLatestByToscaResourceName(member); if (eitherMemberExist.isRight()) { StorageOperationStatus operationStatus = eitherMemberExist.right().value(); log.debug("Error when fetching parent resource {}, error: {}", member, operationStatus); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java index 1e0670daa2..7b55a6988e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java @@ -20,41 +20,36 @@ package org.openecomp.sdc.be.components.impl; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - -import javax.annotation.Resource; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IGroupOperation; import org.openecomp.sdc.be.model.operations.api.IPolicyTypeOperation; -import org.openecomp.sdc.be.model.operations.api.IResourceOperation; -import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; @Component("policyTypeImportManager") public class PolicyTypeImportManager { - @Resource - private PropertyOperation propertyOperation; @Resource private IPolicyTypeOperation policyTypeOperation; @Resource private ComponentsUtils componentsUtils; - @Resource - private IResourceOperation resourceOperation; @Autowired protected IGroupOperation groupOperation; + @Autowired + private ToscaOperationFacade toscaOperationFacade; @Resource private CommonImportManager commonImportManager; @@ -82,7 +77,8 @@ public class PolicyTypeImportManager { } if (result.isLeft()) { for (String targetName : policyType.getTargets()) { - boolean isValid = resourceOperation.getLatestByToscaResourceName(targetName, false).isLeft(); + + boolean isValid = toscaOperationFacade.getLatestByToscaResourceName(targetName).isLeft();; if (!isValid) { isValid = groupOperation.isGroupExist(targetName, false); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java index 96f7eec2d8..da64f3f5b7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java @@ -43,7 +43,6 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ProductOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java index 7f73dc405c..833e6c0b9e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java @@ -20,16 +20,11 @@ package org.openecomp.sdc.be.components.impl; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.function.Supplier; - -import javax.servlet.ServletContext; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.reflect.TypeToken; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -38,7 +33,6 @@ 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.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.IComplexDefaultValue; @@ -46,12 +40,8 @@ import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IElementOperation; -import org.openecomp.sdc.be.model.operations.api.IResourceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; @@ -61,20 +51,20 @@ import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator; import org.openecomp.sdc.be.resources.data.EntryData; import org.openecomp.sdc.be.resources.data.PropertyData; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.reflect.TypeToken; - -import fj.data.Either; +import javax.servlet.ServletContext; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.Supplier; @Component("propertyBusinessLogic") public class PropertyBusinessLogic extends BaseBusinessLogic { @@ -87,9 +77,6 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { private DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); - @javax.annotation.Resource - private IResourceOperation resourceOperation = null; - protected static IElementOperation getElementDao(Class class1, ServletContext context) { WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java index f8dde98010..bd7e810066 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java @@ -20,23 +20,11 @@ package org.openecomp.sdc.be.components.impl; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.operations.api.IResourceOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; -import org.openecomp.sdc.common.config.EcompErrorName; -import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; - @Component("requirementsBusinessLogic") public class RequirementsBusinessLogic { private static Logger log = LoggerFactory.getLogger(RequirementsBusinessLogic.class.getName()); @@ -47,48 +35,5 @@ public class RequirementsBusinessLogic { @javax.annotation.Resource private ResourceBusinessLogic resourceBusinessLogic; - @javax.annotation.Resource - private IResourceOperation resourceOperation; - - public Either updateRequirement(String resourceId, String requirementId, RequirementDefinition requirementDefinition, String userId) { - - // Get the resource from DB - Either status = getResource(resourceId); - if (status.isRight()) { - log.debug("Couldn't get resource {} from DB", resourceId); - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status.right().value()), "")); - } - Resource resource = status.left().value(); - if (resource == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Requirement Business Logic", resourceId); - BeEcompErrorManager.getInstance().logBeComponentMissingError("Requirement Business Logic", ComponentTypeEnum.RESOURCE.getValue(), resourceId); - log.debug("Couldn't get resource {} from DB", resourceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - // verify that resource is checked-out and the user is the last updater - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - // TODO - return null; - } - - private Either getResource(final String resourceId) { - - log.debug("Get resource with id {}", resourceId); - Either status = resourceOperation.getResource(resourceId); - if (status.isRight()) { - log.debug("Resource with id {} was not found", resourceId); - return Either.right(status.right().value()); - } - - Resource resource = status.left().value(); - if (resource == null) { - log.debug("General Error while get resource with id {}", resourceId); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - return Either.left(resource); - } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java index 51e64ca8e1..383f1eb2ec 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java @@ -957,9 +957,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents); Map nodeTypesInfo = extractNodeTypesInfo(csar.left().value(), yamlFileContents); - Map>> nodeTypesArtifactsToCreate = findNodeTypeArtifactsToCreate(csar.left().value(), resource); CsarInfo csarInfo = new CsarInfo(resource.getName(), user, csarUUID, csar.left().value(), false); - Either createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents, yamlFileName, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, true, false, null); + Either>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo.getCsar(), csarInfo.getCsarUUID(), yamlFileName, resource, csarInfo.getModifier()); + if (findNodeTypesArtifactsToHandleRes.isRight()) { + log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID()); + return Either.right(findNodeTypesArtifactsToHandleRes.right().value()); + } + Either createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents, yamlFileName, nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, null); if (createResourceFromYaml.isRight()) { log.debug("Couldn't create resource from YAML"); return Either.right(createResourceFromYaml.right().value()); @@ -1216,14 +1220,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } if(result == null){ newComplexVfc = buildCvfcRes.left().value(); - if(csarInfo.isUpdate()){ - Either oldComplexVfcRes = toscaOperationFacade.getLatestByToscaResourceName(newComplexVfc.getToscaResourceName()); - if(oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND){ - log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value()); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } else if(oldComplexVfcRes.isLeft()){ - oldComplexVfc = oldComplexVfcRes.left().value(); - } + Either oldComplexVfcRes = toscaOperationFacade.getLatestByToscaResourceName(newComplexVfc.getToscaResourceName()); + if(oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND){ + log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value()); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } else if(oldComplexVfcRes.isLeft()){ + oldComplexVfc = oldComplexVfcRes.left().value(); } } if(result == null){ @@ -1417,7 +1419,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { cvfc.setVendorName(resourceVf.getVendorName()); cvfc.setVendorRelease(resourceVf.getVendorRelease()); cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber()); - cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), csarInfo.getVfResourceName(), nodeName)); + cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName)); cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); List tags = new ArrayList<>(); @@ -1889,18 +1891,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return result; } - private Map>> findNodeTypeArtifactsToCreate(Map csar, Resource resource) { - - Map> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar); - Map>> nodeTypesArtifactsToHandle = new HashMap<>(); - for (Map.Entry> currArts : extractedVfcsArtifacts.entrySet()) { - EnumMap> artifactsToCreate = new EnumMap<>(ArtifactOperationEnum.class); - artifactsToCreate.put(ArtifactOperationEnum.Create, currArts.getValue()); - nodeTypesArtifactsToHandle.put(currArts.getKey(), artifactsToCreate); - } - return nodeTypesArtifactsToHandle; - } - private void handleAndAddExtractedVfcsArtifacts(List vfcArtifacts, List artifactsToAdd) { List vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName()).collect(Collectors.toList()); artifactsToAdd.stream().forEach(a -> { @@ -7086,6 +7076,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { private String buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) { + String actualType; + String actualVfName; + if(ResourceTypeEnum.CVFC.name().equals(nodeResourceType)){ + actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name(); + actualType = ResourceTypeEnum.VFC.name(); + } else { + actualVfName = vfResourceName; + actualType = nodeResourceType; + } StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); String nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); String[] findTypes = nameWithouNamespacePrefix.split("\\."); @@ -7093,9 +7092,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { String actualName = nameWithouNamespacePrefix.substring(resourceType.length()); if (actualName.startsWith(Constants.ABSTRACT)) { - toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(vfResourceName)); + toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)); } else { - toscaResourceName.append(nodeResourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(vfResourceName)).append('.').append(Constants.ABSTRACT); + toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT); } return toscaResourceName.append(actualName.toLowerCase()).toString(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java index ac6183db00..b21195ff42 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java @@ -20,22 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.function.Function; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.auditing.api.IAuditingManager; @@ -53,24 +38,13 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.CsarInfo; -import org.openecomp.sdc.be.model.InterfaceDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.UploadResourceInfo; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; @@ -83,7 +57,20 @@ import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; import org.yaml.snakeyaml.Yaml; -import fj.data.Either; +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.function.Function; +import java.util.regex.Pattern; +import java.util.stream.Collectors; @Component("resourceImportManager") public class ResourceImportManager { @@ -102,9 +89,6 @@ public class ResourceImportManager { @Autowired protected ComponentsUtils componentsUtils; - @Autowired - protected ResourceOperation resourceOperation; - public final static Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern .compile("[\\w\\-\\_\\d\\:]+"); @Autowired @@ -963,8 +947,5 @@ public class ResourceImportManager { this.auditingManager = auditingManager; } - public void setResourceOperation(ResourceOperation resourceOperation) { - this.resourceOperation = resourceOperation; - } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java index 11ffcd9329..d1cc93acc8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java @@ -22,12 +22,8 @@ package org.openecomp.sdc.be.components.impl; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; -import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Component; -import fj.data.Either; - @Component("serviceComponentInstanceBusinessLogic") public class ServiceComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java index b18c4d0985..d12afdbd55 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java @@ -20,18 +20,8 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; - -import org.apache.commons.codec.binary.Base64; +import fj.data.Either; import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder; -import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -42,40 +32,30 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Operation; -import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; -import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.be.tosca.ToscaError; import org.openecomp.sdc.be.tosca.ToscaExportHandler; -import org.openecomp.sdc.be.tosca.ToscaRepresentation; -import org.openecomp.sdc.be.tosca.ToscaUtils; import org.openecomp.sdc.be.user.Role; -import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; public class CertificationRequestTransition extends LifeCycleTransition { @@ -326,47 +306,6 @@ public class CertificationRequestTransition extends LifeCycleTransition { return Either.left(true); } - private Either parseRelationsForReqCapVerification(Component component, Map> reqName2Ids, Map> capName2Ids) { - log.debug("Submit for testing validation - Preparing relations for inner atomic instances validation"); - List componentInstancesRelations = component.getComponentInstancesRelations(); - if (componentInstancesRelations != null) { - for (RequirementCapabilityRelDef reqCapRelDef : componentInstancesRelations) { - List relationships = reqCapRelDef.getRelationships(); - if (relationships != null) { - for (RequirementAndRelationshipPair reqRelPair : relationships) { - String capUniqueId = reqRelPair.getCapabilityUid(); - Either capability = capabilityOperation.getCapability(capUniqueId); - if (capability.isRight()) { - log.error("Couldn't fetch capability by id {}", capUniqueId); - return Either.right(componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - String reqCapType = capability.left().value().getType(); - String capabilityOwnerId = reqRelPair.getCapabilityOwnerId(); - String requirementOwnerId = reqRelPair.getRequirementOwnerId(); - // Update req - List reqIds = reqName2Ids.get(reqCapType); - if (reqIds == null) { - reqIds = new ArrayList<>(); - reqName2Ids.put(reqCapType, reqIds); - } - reqIds.add(requirementOwnerId); - // Update cap - List capIds = capName2Ids.get(reqCapType); - if (capIds == null) { - capIds = new ArrayList<>(); - capName2Ids.put(reqCapType, capIds); - } - capIds.add(capabilityOwnerId); - } - } - } - log.debug("Parsed req for validation: {}, parsed cap for validation: {}", reqName2Ids, capName2Ids); - } else { - log.debug("There are no relations found for component {}", component.getUniqueId()); - } - return Either.left(true); - } - @Override public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java index 0d0e06fe6d..cc534bb694 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java @@ -39,7 +39,6 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.Role; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java index 8a80e0bb64..24266521c2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java @@ -20,15 +20,12 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.Arrays; - -import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; @@ -39,7 +36,6 @@ import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; -import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.Role; @@ -47,7 +43,7 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.Arrays; public class StartCertificationTransition extends LifeCycleTransition { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java index 436b2319e9..fa31989d87 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java @@ -20,19 +20,9 @@ package org.openecomp.sdc.be.listen; -import java.io.IOException; -import java.io.InputStream; -import java.util.jar.Attributes; -import java.util.jar.Manifest; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; - import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.impl.DownloadArtifactLogic; import org.openecomp.sdc.be.impl.WebAppContextWrapper; -import org.openecomp.sdc.be.model.operations.api.IResourceOperation; import org.openecomp.sdc.be.monitoring.BeMonitoringService; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.impl.ExternalConfiguration; @@ -41,6 +31,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import java.io.IOException; +import java.io.InputStream; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + public class BEAppContextListener extends AppContextListener implements ServletContextListener { private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF"; @@ -71,11 +69,6 @@ public class BEAppContextListener extends AppContextListener implements ServletC } - private IResourceOperation getResourceOperationManager(Class clazz, WebApplicationContext webContext) { - - return webContext.getBean(clazz); - } - private String getVersionFromManifest(ServletContextEvent context) { ServletContext servletContext = context.getServletContext(); InputStream inputStream = servletContext.getResourceAsStream(MANIFEST_FILE_NAME); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java index b70dae68e8..85b1927548 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java @@ -20,26 +20,8 @@ package org.openecomp.sdc.be.tosca; -import java.io.BufferedOutputStream; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; - +import com.google.gson.Gson; +import fj.data.Either; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.output.ByteArrayOutputStream; @@ -68,10 +50,10 @@ import org.openecomp.sdc.be.model.Operation; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData; import org.openecomp.sdc.be.tosca.model.ToscaTemplate; @@ -92,9 +74,25 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.google.gson.Gson; - -import fj.data.Either; +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; /** @@ -814,10 +812,10 @@ public class CsarUtils { if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) { version = component.getVersion(); } else { - String[] versionParts = component.getVersion().split(LifecycleOperation.VERSION_DELIMETER_REGEXP); + String[] versionParts = component.getVersion().split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP); Integer majorVersion = Integer.parseInt(versionParts[0]); - version = (majorVersion + 1) + LifecycleOperation.VERSION_DELIMETER + "0"; + version = (majorVersion + 1) + ToscaElementLifecycleOperation.VERSION_DELIMETER + "0"; } additionalParams.put(AdditionalParams.ServiceVersion.getName(), version); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java index 134038abb6..0dceaed4f2 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java @@ -95,7 +95,7 @@ public class GroupBusinessLogicTest { @BeforeClass public static void setupBeforeClass() { when(graphLockOperation.lockComponent(componentId, ComponentTypeEnum.RESOURCE.getNodeType())).thenReturn(StorageOperationStatus.OK); - when(groupOperation.getGroup(groupUniqueId)).thenReturn(Either.left(groupDefenition)); +// when(groupOperation.getGroup(groupUniqueId)).thenReturn(Either.left(groupDefenition)); } public enum ResponseEnum{ diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java index ae929edb31..1309af8ff7 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java @@ -41,7 +41,6 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IPropertyOperation; -import org.openecomp.sdc.be.model.operations.api.IResourceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.EntryData; import org.openecomp.sdc.be.user.Role; @@ -74,8 +73,6 @@ public class PropertyBusinessLogicTest { @Mock private IPropertyOperation propertyOperation; @Mock - private IResourceOperation resourceOperation; - @Mock private WebAppContextWrapper webAppContextWrapper; @Mock private UserBusinessLogic mockUserAdmin; @@ -115,20 +112,20 @@ public class PropertyBusinessLogicTest { when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); when(servletContext.getAttribute(Constants.PROPERTY_OPERATION_MANAGER)).thenReturn(propertyOperation); when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation); +// when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation); when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); // Resource Operation mock methods // getCount - Either eitherCount = Either.left(0); - when(resourceOperation.getNumberOfResourcesByName("MyResourceName".toLowerCase())).thenReturn(eitherCount); - Either eitherCountExist = Either.left(1); - when(resourceOperation.getNumberOfResourcesByName("alreadyExist".toLowerCase())).thenReturn(eitherCountExist); - Either eitherCountRoot = Either.left(1); - when(resourceOperation.getNumberOfResourcesByName("Root".toLowerCase())).thenReturn(eitherCountRoot); - - Either eitherGetResource = Either.left(createResourceObject(true)); - when(resourceOperation.getResource(resourceId)).thenReturn(eitherGetResource); +// Either eitherCount = Either.left(0); +// when(resourceOperation.getNumberOfResourcesByName("MyResourceName".toLowerCase())).thenReturn(eitherCount); +// Either eitherCountExist = Either.left(1); +// when(resourceOperation.getNumberOfResourcesByName("alreadyExist".toLowerCase())).thenReturn(eitherCountExist); +// Either eitherCountRoot = Either.left(1); +// when(resourceOperation.getNumberOfResourcesByName("Root".toLowerCase())).thenReturn(eitherCountRoot); +// +// Either eitherGetResource = Either.left(createResourceObject(true)); +// when(resourceOperation.getResource(resourceId)).thenReturn(eitherGetResource); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java index a453df2563..c545474f5d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java @@ -55,7 +55,6 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.UploadResourceInfo; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; import org.openecomp.sdc.be.model.tosca.constraints.GreaterOrEqualConstraint; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.UserBusinessLogic; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java index ed16ca722a..d8b82da396 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java @@ -20,26 +20,12 @@ package org.openecomp.sdc.be.components; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.openecomp.sdc.ElementOperationMock; import org.openecomp.sdc.be.auditing.api.IAuditingManager; import org.openecomp.sdc.be.auditing.impl.AuditingManager; @@ -49,20 +35,15 @@ import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; -import org.openecomp.sdc.be.dao.impl.AuditingDao; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.GroupInstance; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; @@ -72,8 +53,6 @@ import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation; import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; -import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent; import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent; import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; @@ -83,7 +62,6 @@ import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; -import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.common.util.ValidationUtils; @@ -92,10 +70,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import javax.servlet.ServletContext; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; -import fj.data.Either; +import static org.junit.Assert.*; +import static org.mockito.Mockito.when; public class ServiceBusinessLogicTest { @@ -158,7 +141,7 @@ public class ServiceBusinessLogicTest { // Servlet Context attributes when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation()); +// when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation()); when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java index 6cb90d0920..5de6762bdd 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java @@ -20,18 +20,10 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.cassandra.io.sstable.Component; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import fj.data.Either; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig.Feature; @@ -40,11 +32,8 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.InjectMocks; -import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.be.components.ArtifactsResolver; -import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -66,7 +55,6 @@ import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation; -import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.be.servlets.RepresentationUtils; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; @@ -76,11 +64,14 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.ResponseFormat; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; -import fj.data.Either; +import static org.junit.Assert.*; +import static org.mockito.Mockito.when; public class ArtifactBusinessLogicTest { @@ -95,7 +86,6 @@ public class ArtifactBusinessLogicTest { public static final IInterfaceLifecycleOperation lifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class); public static final IUserAdminOperation userOperation = Mockito.mock(IUserAdminOperation.class); public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class); - public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); public static final ArtifactCassandraDao artifactCassandraDao = Mockito.mock(ArtifactCassandraDao.class); public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); @@ -110,7 +100,7 @@ public class ArtifactBusinessLogicTest { public static void setup() { Either NotFoundResult = Either.right(StorageOperationStatus.NOT_FOUND); - when(artifactOperation.getArtifactById(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(NotFoundResult); +// when(artifactOperation.getArtifactById(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(NotFoundResult); Either, StorageOperationStatus> NotFoundResult2 = Either.right(StorageOperationStatus.NOT_FOUND); when(artifactOperation.getArtifacts(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service), Mockito.anyBoolean())).thenReturn(NotFoundResult2); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java index e1a3265c6a..a3022330a1 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java @@ -20,25 +20,12 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; -import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -55,7 +42,6 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.UserBusinessLogic; @@ -66,7 +52,13 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.*; public class ResourceInstanceBusinessLogicTest { @@ -87,7 +79,7 @@ public class ResourceInstanceBusinessLogicTest { public static final ArtifactsBusinessLogic artifactBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class); public static final UserBusinessLogic userAdminManager = Mockito.mock(UserBusinessLogic.class); - public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); +// public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); public static final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class); public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); @@ -132,7 +124,7 @@ public class ResourceInstanceBusinessLogicTest { Object lightService = new Service(); Either eitherLightService = Either.left(lightService); - Mockito.when(serviceOperation.getLightComponent(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherLightService); +// Mockito.when(serviceOperation.getLightComponent(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherLightService); Mockito.doNothing().when(componentsUtils).auditComponent(Mockito.any(ResponseFormat.class), Mockito.any(User.class), Mockito.any(Component.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(AuditingActionEnum.class), Mockito.any(ComponentTypeEnum.class), Mockito.any(EnumMap.class)); @@ -157,7 +149,7 @@ public class ResourceInstanceBusinessLogicTest { @Before public void initMocks() { MockitoAnnotations.initMocks(this); - Mockito.reset(artifactBusinessLogic, serviceOperation, componentsUtils, userAdminManager); +// Mockito.reset(artifactBusinessLogic, serviceOperation, componentsUtils, userAdminManager); setup(); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java index e26934bfaf..6bfd64be41 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java @@ -20,13 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; - +import fj.data.Either; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; @@ -36,9 +30,7 @@ import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; @@ -49,18 +41,21 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; import org.openecomp.sdc.be.tosca.ToscaError; import org.openecomp.sdc.be.tosca.ToscaExportHandler; import org.openecomp.sdc.be.tosca.ToscaRepresentation; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class CertificationRequestTest extends LifecycleTestBase { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java index 1488f13015..ff5c618138 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java @@ -55,7 +55,6 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOper import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.be.user.UserBusinessLogic; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java index c1fb2e0a7f..198325b6b5 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java @@ -26,7 +26,6 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.cache.DaoInfo; -import org.openecomp.sdc.be.model.operations.api.IComponentOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.slf4j.Logger; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java index 5f7502e7ce..f7e4245492 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java @@ -20,13 +20,7 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.apache.tinkerpop.shaded.minlog.Log; +import fj.data.Either; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; @@ -34,11 +28,9 @@ import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupInstance; @@ -48,20 +40,17 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.be.resources.data.GroupData; -import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.carrotsearch.junitbenchmarks.annotation.LabelType; -import com.thinkaurelius.titan.diskstorage.Entry; - -import fj.data.Either; -import javassist.expr.NewArray; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("groups-operation") public class GroupsOperation extends BaseOperation { @@ -242,7 +231,7 @@ public class GroupsOperation extends BaseOperation { */ private String increaseMajorVersion(String version) { - String[] versionParts = version.split(LifecycleOperation.VERSION_DELIMETER_REGEXP); + String[] versionParts = version.split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP); Integer majorVersion = Integer.parseInt(versionParts[0]); majorVersion++; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java index 5e8a2eb0d5..3d689a4f93 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java @@ -39,42 +39,10 @@ public interface IArtifactOperation { public Either updateArifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId, NodeTypeEnum type, boolean inTransaction); - public Either updateArifactDefinition(ArtifactDefinition artifactInfo, boolean inTransaction); - public Either removeArifactFromResource(String id, String artifactId, NodeTypeEnum resource, boolean deleteMandatoryArtifact, boolean inTransaction); public Either, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction); - public void setTitanGenericDao(TitanGenericDao titanGenericDao); - - public Either getArtifactById(String id, boolean inTransaction); - - public Either, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, String groupType); - - Either addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String parentId, NodeTypeEnum parentType, boolean failIfExist); - - public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion); - - public Either getParentsOfArtifact(String artifactId, NodeTypeEnum type); - - public Either getHeatArtifactByHeatEnvId(String heatEnvId, boolean inTransaction); - - public Either updateToscaArtifactNameOnGraph(ArtifactDefinition artifactInfo, String artifactId, NodeTypeEnum type, String id); - - public StorageOperationStatus addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, TitanVertex parentVertex); - public Either getLatestArtifactDataByArtifactUUID(String artifactUUID, boolean inTransaction); - - StorageOperationStatus addArifactToComponent(TitanVertex artifactInfo, TitanVertex parentVertex, String label); - - public Either removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact); - - public Either updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, boolean inTransaction); - - public Either updateHeatEnvArtifact( String id, ArtifactDefinition artifactEnvInfo, String oldArtifactId, String newArtifactId, NodeTypeEnum type, boolean inTransaction); - - public Either getHeatEnvByGeneratedFromId(String generatedFromId); - - } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAttributeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAttributeOperation.java deleted file mode 100644 index c5fc70eb38..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAttributeOperation.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.api; - -import java.util.List; -import java.util.Map; - -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.resources.data.AttributeData; -import org.openecomp.sdc.be.resources.data.AttributeValueData; - -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; - -public interface IAttributeOperation { - Either deleteAttribute(String attributeId); - - TitanOperationStatus addAttributesToGraph(TitanVertex metadataVertex, Map attributes, String resourceId, Map dataTypes); - - Either, TitanOperationStatus> getAllAttributesOfResourceInstance(ComponentInstance compInstance); - - TitanOperationStatus findAllResourceAttributesRecursively(String resourceId, List attributes); - - Either, StorageOperationStatus> deleteAllAttributeAssociatedToNode(NodeTypeEnum nodeType, String uniqueId); - - TitanOperationStatus findNodeNonInheretedAttribues(String uniqueId, NodeTypeEnum nodeType, List attributes); - - Either addAttribute(PropertyDefinition attributeDefinition, String resourceId); - - Either addAttributeToGraph(PropertyDefinition attribute, String resourceId, Map dataTypes); - - PropertyDefinition convertAttributeDataToAttributeDefinition(AttributeData attributeData, String attributeName, String resourceId); - - Either updateAttribute(String attributeId, PropertyDefinition newAttDef, Map dataTypes); - - /** - * Builds ComponentInstanceAttribute from AttributeValueData - * - * @param attributeValueData - * @param resourceInstanceAttribute - * @return - */ - ComponentInstanceProperty buildResourceInstanceAttribute(AttributeValueData attributeValueData, ComponentInstanceProperty resourceInstanceAttribute); - - TitanOperationStatus addAttributeToGraphByVertex(TitanVertex metadataVertex, PropertyDefinition attribute, String resourceId, Map dataTypes); - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java deleted file mode 100644 index f8e8c80f12..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java +++ /dev/null @@ -1,130 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.api; - -import java.util.List; -import java.util.Map; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.resources.data.CapabilityInstData; -import org.openecomp.sdc.be.resources.data.ComponentInstanceData; -import org.openecomp.sdc.be.resources.data.PropertyValueData; - -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; - -/** - * public interface ICapabilityInstanceOperation provides methods for CRUD operations for CapabilityInstance on component instance level - * - * @author ns019t - * - */ -public interface ICapabilityInstanceOperation { - /** - * create capability instance of capability with property values for resource instance - * - * @param resourceInstanceId - * @param capabilityId - * @param propertyValues - * @param validateCapabilityInstExistance - * @param capabilityName - * @return - */ - public Either>, TitanOperationStatus> createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(String resourceInstanceId, String capabilityId, String capabilityName, - List propertyValues, boolean validateCapabilityInstExistance); - - /** - * - * @param resourceInstanceVertex - * @param capabilityId - * @param capabilityName - * @param propertyValues - * @param validateCapabilityInstExistence - * @return - */ - public TitanOperationStatus createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(TitanVertex resourceInstanceVertex, String resourceInstanceId, String capabilityId, String capabilityName, - List propertyValues, boolean validateCapabilityInstExistence); - - /** - * validate capability instance uniqueness - * - * @param resourceInstanceId - * @param capabilityId - * @return - */ - public Either validateCapabilityInstExistence(String resourceInstanceId, String capabilityId); - - /** - * delete capability instance from resource instance - * - * @param resourceInstanceId - * @param capabilityInstanceId - * @return - */ - public Either deleteCapabilityInstanceFromResourceInstance(String resourceInstanceId, String capabilityInstanceId); - - /** - * get all capability instances for resource instance returns all Capability Instances related to Resource Instance as List or TitanOperationStatus if error occurs or if Resource Instance have no any related Capability - * Instance - * - * @param resourceInstanceId - * @return Either, TitanOperationStatus> - */ - public Either>, TitanOperationStatus> getAllCapabilityInstancesOfResourceInstance(String resourceInstanceId); - - /** - * get capability instance of capability for resource instance - * - * @param resourceInstanceId - * @param capabilityId - * @return - */ - public Either getCapabilityInstanceOfCapabilityOfResourceInstance(String resourceInstanceId, String capabilityId); - - /** - * update capability property values - * - * @param resourceInstanceId - * @param capabilityInstanceId - * @param propertyValues - * @param capabilityId - * @return - */ - public Either, TitanOperationStatus> updateCapabilityPropertyValues(String resourceInstanceId, String capabilityId, List propertyValues); - - /** - * clone and associate capability instance with property values - * - * @param createdComponentInstance - * @param capability - * @param capabilityInstPair - * @return - */ - public Either>, TitanOperationStatus> cloneAssociateCapabilityInstanceWithPropertyValues(ComponentInstanceData createdComponentInstance, CapabilityDefinition capability, - ImmutablePair capabilityInstPair); - - Either validateCapabilityInstExistence(TitanVertex instanceVertex, String resourceInstanceId, String capabilityId); -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java index b3be2bd6ee..b90f31f731 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java @@ -38,36 +38,8 @@ import fj.data.Either; public interface ICapabilityOperation { - public Either addCapability(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition); + Either, TitanOperationStatus> getAllCapabilityTypePropertiesFromAllDerivedFrom(String firstParentType); - public Either addCapability(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition, boolean inTransaction); - - /** - * @param uniqueId - * @return - */ - public Either getCapability(String uniqueId); - - public Either getCapability(String uniqueId, boolean inTransaction); - - public Either getCapability(String capabilityName, String resourceId); - - public Either getCapability(String capabilityName, String resourceId, boolean inTransaction); - - public Either>, TitanOperationStatus> getAllCapabilitiesPairs(String resourceId); - - public Either, StorageOperationStatus> deleteAllCapabilities(String resourceId, boolean inTransaction); - - public Either getCapabilityByCapabilityData(CapabilityData capabilityData); - - public TitanOperationStatus getCapabilitySourcesList(String resourceId, List derivedFromList); - - public Either, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId, String capabilityType, List newProperties); - - public Either, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId, String capabilityType, List newProperties, boolean inTransaction); - - StorageOperationStatus addCapability(TitanVertex metadataVertex, String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition, boolean inTransaction); - - Either getCapabilityTypeOfCapability(String uniqueId); + Either, TitanOperationStatus> validatePropertyUniqueness(Map propertiesOfCapabilityType, List properties); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java index f4cb13fa64..d1a1b6ac7b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java @@ -45,149 +45,8 @@ import fj.data.Either; public interface IComponentInstanceOperation { - /** - * add resource instance to service - * - * @param containerComponentId - * - component id - * @param instanceNumber - * - instance number of the component instance - * @param componentInstance - * @param inTransaction - * @return - */ - public Either createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, ComponentInstance componentInstance, NodeTypeEnum instNodeType, - boolean inTransaction); - - /** - * add resource instance to service with internal transaction - * - * @param containerComponentId - * @param instanceNumber - * @param componentInstance - * @return - */ - public Either createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, ComponentInstance componentInstance, NodeTypeEnum instNodeType); - - /** - * delete resource instance from component - * - * @param containerComponentId - * - containerComponent id - * @param resourceInstUid - * - resource instance uid - * @param inTransaction - * @return - */ - public Either deleteComponentInstance(NodeTypeEnum containerNodeType, String containerComponentId, String resourceInstUid, boolean inTransaction); - - public Either deleteComponentInstance(NodeTypeEnum containerNodeType, String containerComponentId, String resourceInstUid); - - /** - * associate 2 resource instances for a given requirement - * - * @param serviceId - * @param fromResInstanceUid - * @param toResInstanceUid - * @param requirement - * @param relationship - * @param inTransaction - * @return - */ - // public Either - // associateResourceInstances( - // String serviceId, NodeTypeEnum nodeType, String fromResInstanceUid, - // String toResInstanceUid, String requirement, String relationship, - // boolean inTransaction); - - // public Either - // associateResourceInstances( - // String serviceId, NodeTypeEnum nodeType, String fromResInstanceUid, - // String toResInstanceUid, String requirement, String relationship); - - public Either associateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean inTransaction, boolean isClone); - - public Either associateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation); - - /** - * - * dissociate the relation between 2 resource instances for a given requirement - * - * @param serviceId - * @param fromResInstanceUid - * @param toResInstanceUid - * @param requirement - * @param inTransaction - * @return - */ - public Either dissociateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef, boolean inTransaction); - - public Either dissociateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef); - - /** - * update the properties of a given resource instance - * - * @param serviceId - * @param resourceInstanceName - * @param resourceInstance - * @param inTransaction - * @return - */ - public Either updateResourceInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance, boolean inTransaction); - - public Either updateResourceInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance); - - /** - * get all resource instances of a given service and the relations between the resource instances - * - * @param serviceId - * @param inTransaction - * @return - */ - public Either, List>, StorageOperationStatus> getAllComponentInstances(String componentId, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, boolean inTransaction); - - public Either, StorageOperationStatus> getAllComponentInstancesNames(String componentId, NodeTypeEnum nodeType, boolean inTransaction); - - public Either, StorageOperationStatus> getAllComponentInstancesNames(String componentId, NodeTypeEnum nodeType); - - /** - * get all component instance properties and values from graph - * @param resourceInstance - * @return - */ - public Either, StorageOperationStatus> getComponentInstancesPropertiesAndValuesFromGraph( - ComponentInstance resourceInstance); - - /** - * get resource instance from id - * - * @param resourceId - * @return resource instance of given id - */ - public Either getResourceInstanceById(String resourceId); - - public Either, StorageOperationStatus> deleteAllComponentInstances(String serviceId, NodeTypeEnum nodeType, boolean inTransaction); - - public Either, StorageOperationStatus> deleteAllComponentInstances(String serviceId, NodeTypeEnum nodeType); - public Either increaseAndGetResourceInstanceSpecificCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, boolean inTransaction); - public String createComponentInstLogicalName(String instanceNumber, String componentInstanceName); - - public Either isComponentInstanceNameExist(String parentComponentId, NodeTypeEnum parentNodeType, String compInstId, String componentInstName); - - public Either validateParent(String parentId, String uniqId, boolean inTransaction); - - public Either getFullComponentInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType); - - public Either isAvailableRequirement(ComponentInstance fromResInstance, RequirementAndRelationshipPair relationPair); - - public Either isAvailableCapabilty(ComponentInstance toResInstance, RequirementAndRelationshipPair relationPair); - - public Either addPropertyValueToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index, boolean inTransaction); - - public Either addPropertyValueToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isvalidate, Integer index, boolean inTransaction); - /** * Adds Attribute to resource instance * @@ -197,8 +56,6 @@ public interface IComponentInstanceOperation { **/ public Either addAttributeValueToResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction); - public Either updatePropertyValueInResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean inTransaction); - /** * Updates Attribute on resource instance * @@ -209,13 +66,11 @@ public interface IComponentInstanceOperation { */ public Either updateAttributeValueInResourceInstance(ComponentInstanceProperty attribute, String resourceInstanceId, boolean inTransaction); - public Either createOrUpdateAttributeOfResourceInstance(ComponentInstanceProperty attributeInstanceProperty, String resourceInstanceId); public Either addInputValueToResourceInstance(ComponentInstanceInput input, String resourceInstanceId, Integer innerElement, boolean b); public Either updateInputValueInResourceInstance(ComponentInstanceInput input, String resourceInstanceId, boolean b); - public Either, StorageOperationStatus> fetchCIEnvArtifacts(String componentInstanceId); public StorageOperationStatus updateCustomizationUUID(String componentInstanceId); /** @@ -228,11 +83,4 @@ public interface IComponentInstanceOperation { */ public Either updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction); - Either>, TitanOperationStatus> getCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum); - - Either>, TitanOperationStatus> getRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum); - - Either>, TitanOperationStatus> getFulfilledCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum); - - Either>, TitanOperationStatus> getFulfilledRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java deleted file mode 100644 index 3eef59fa69..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.api; - -import java.util.List; -import java.util.Map; - -import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; -import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentParametersView; - -import fj.data.Either; - -public interface IComponentOperation { - public Either getComponent(String id, Class clazz); - - public Either, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType, boolean inTransacton); - - public Either getLightComponent(String id, boolean inTransaction); - - public Either getComponent(String id, boolean inTransaction); - - public Either getComponent(String id, ComponentParametersView componentParametersView, boolean inTransaction); - - public Either, StorageOperationStatus> getFilteredComponents(Map filters, boolean inTranscation); - - public Either getComponentByLabelAndId(String uniqueId, NodeTypeEnum nodeType, Class clazz); - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java index 8fd88f704f..b55eff6684 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java @@ -45,57 +45,15 @@ import fj.data.Either; public interface IGroupInstanceOperation { - public Either createGroupInstance(String ComponentInstId, GroupInstance groupInstance, boolean isCreateLogicalName); - - public Either createGroupInstance(TitanVertex ciVertex, String componentInstId, GroupInstance groupInstance, boolean isCreateLogicalName); - - public Either deleteGroupInstanceInstance(NodeTypeEnum containerNodeType, String containerComponentId, String groupInstUid); - - public Either updateGroupInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance); - - public Either, StorageOperationStatus> getAllGroupInstances(String componentInstId, NodeTypeEnum compInstNodeType); - - public Either getGroupInstanceById(String groupResourceId); - public TitanOperationStatus deleteAllGroupInstances(String componentInstId); + public Either, StorageOperationStatus> getAllGroupInstances(String componentInstId, NodeTypeEnum compInstNodeType); public Either increaseAndGetGroupInstancePropertyCounter(String groupInstanceId); - public Either isGroupInstanceNameExist(String parentComponentId, NodeTypeEnum parentNodeType, String compInstId, String componentInstName); - - public Either getFullGroupInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType); - public Either addPropertyValueToGroupInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index, boolean inTransaction); - public Either addPropertyValueToGroupInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isvalidate, Integer index, boolean inTransaction); - public Either updatePropertyValueInGroupInstance(ComponentInstanceProperty gropuInstanceProperty, String groupInstanceId, boolean inTransaction); - - public Either, StorageOperationStatus> fetchCIEnvArtifacts(String componentInstanceId); - - public StorageOperationStatus updateCustomizationUUID(String componentInstanceId); - - public String createGroupInstLogicalName(String instanceNumber, String groupInstanceName); - - public Either associateArtifactsToGroupInstance(String groupId, List artifactsId); StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact); - StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact); - /** - * updates group instance property values - * @param value - * @param newProperties - * @return - */ - public Either updateGroupInstancePropertyValues(GroupInstance value, List newProperties); - /** - * updates group instance property values - * @param oldGroupInstance - * @param newProperties - * @param inTransaction - * @return - */ - public Either updateGroupInstancePropertyValues(GroupInstance oldGroupInstance, List newProperties, Boolean inTransaction); - } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java index 3295adfe56..6dbbfb6b6e 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java @@ -34,72 +34,11 @@ import fj.data.Either; public interface IGroupOperation { - // add full group to component - public Either addGroupToGraph(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition); - - public Either addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition); - - public Either addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition, boolean inTransaction); - - public Either, StorageOperationStatus> addGroups(NodeTypeEnum nodeTypeEnum, String componentId, List groups, boolean inTransaction); - - // get group - public Either getGroupFromGraph(String uniqueId); - - public Either getGroup(String uniqueId); - - public Either getGroup(String uniqueId, boolean inTransaction); - - // get all groups under component - public Either, TitanOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum); - - public Either, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction); - - public Either, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum); - - // delete all groups under component - public Either, TitanOperationStatus> deleteAllGroupsFromGraph(String componentId, NodeTypeEnum compTypeEnum); - - public Either, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction); - - public Either, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum); - - // Association - public Either, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId, boolean inTransaction); - - public Either, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId); - - public Either, TitanOperationStatus> getAssociatedGroupsToComponentInstanceFromGraph(String componentInstanceId); - - public StorageOperationStatus associateGroupsToComponentInstance(List groups, String componentInstanceId, String compInstName, boolean inTransaction); - - public StorageOperationStatus associateGroupsToComponentInstance(List groups, String componentInstanceId, String compInstName); - - public Either, TitanOperationStatus> associateGroupsToComponentInstanceOnGraph(List groups, String componentInstanceId, String compInstName); - public Either, TitanOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String artifactId); - public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId, boolean inTransaction); - - public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId); - - public TitanOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact); - public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction); - public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact); - public boolean isGroupExist(String groupName, boolean inTransaction); - /** - * Updates Group Metadata (name and properties) - * @param groupToUpdateFromUniqueId - * @param newName - * @param groupToUpdateTo - * @param inTransaction - * @return - */ - public Either updateGroupName(String groupToUpdateFromUniqueId, - String newName, GroupDefinition groupToUpdateTo, boolean inTransaction); public StorageOperationStatus validateAndUpdatePropertyValue(GroupProperty property); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java index 8b44229df1..1cec537e3e 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java @@ -20,50 +20,21 @@ package org.openecomp.sdc.be.model.operations.api; -import java.util.List; -import java.util.Map; - +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstInputsMap; -import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.resources.data.AttributeData; +import org.openecomp.sdc.be.resources.data.InputValueData; import org.openecomp.sdc.be.resources.data.InputsData; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; +import java.util.List; public interface IInputsOperation { - Either deleteInput(String inputId); - - Either, TitanOperationStatus> addInputsToGraph(String componentId, NodeTypeEnum nodeType, Map inputs, Map dataTypes); - - TitanOperationStatus findNodeNonInheretedInputs(String uniqueId, List inputs); - - Either, StorageOperationStatus> getInputsOfComponent(String compId, String fromName, int amount); - - Either, TitanOperationStatus> getAllInputsOfResourceInstance(ComponentInstance compInstance); - - Either, StorageOperationStatus> deleteAllInputsAssociatedToNode(NodeTypeEnum nodeType, String uniqueId); - - // TitanOperationStatus findNodeNonInheretedAttribues(String uniqueId, - // NodeTypeEnum nodeType, List attributes); - - Either addInput(String inputName, InputDefinition inputDefinition, String componentId, NodeTypeEnum nodeType); - - Either addInputToGraph(String propertyName, InputDefinition inputDefinition, String componentId, NodeTypeEnum nodeType); - - Either updateInput(String inputId, InputDefinition newInDef, Map dataTypes); - - TitanOperationStatus findAllResourceInputs(String uniqueId, List inputs); - - Either getInputById(String uniqueId, boolean skipProperties, boolean skipinputsValue); + ImmutablePair findInputValue(String resourceInstanceId, String propertyId); - TitanOperationStatus addInputsToGraph(TitanVertex metadata, String componentId, Map inputs, Map dataTypes); + ComponentInstanceInput buildResourceInstanceInput(InputValueData propertyValueData, ComponentInstanceInput resourceInstanceInput); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java index e46460a502..c9a332f069 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java @@ -35,43 +35,23 @@ public interface IInterfaceLifecycleOperation { public Either createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction); - public StorageOperationStatus createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction, TitanVertex metadataVertex); - - public Either addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName); - public Either addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean inTransaction); - // public Either - // getInterface(String interfaceId); - // - // public Either - // getInterface(String interfaceId, boolean inTransaction); - public Either updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation interf); public Either updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation interf, boolean inTransaction); - public Either deleteInterfaceOperation(String resourceId, String interfaceName, String operationName); - public Either deleteInterfaceOperation(String resourceId, String interfaceName, String operationName, boolean inTransaction); public Either, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively, boolean inTransaction); public Either, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively); - public Either deleteInterfaceOfResourceOnGraph(String resourceId, InterfaceDefinition interfaceDef, boolean inTransaction); - public Either createInterfaceType(InterfaceDefinition interf); public Either createInterfaceType(InterfaceDefinition interf, boolean inTransaction); public Either getInterface(String interfaceId); - public StorageOperationStatus associateInterfaceToNode(GraphNode node, InterfaceDefinition interfaceDefinition, TitanVertex metadataVertex); - - public Either getSpecificOperation(String resourceId, String interfaceType, String operationName); - - public Either dissociateInterfaceFromNode(GraphNode node, InterfaceDefinition interfaceDefinition); - public String getShortInterfaceName(InterfaceDataDefinition interfaceDefinition); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java deleted file mode 100644 index ab99f20d4c..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.api; - -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; - -import fj.data.Either; - -public interface ILifecycleOperation { - - public ResourceOperation getResourceOperation(); - - public Either getComponentOwner(String resourceId, NodeTypeEnum nodeType, boolean inTransaction); - - public Either checkinComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction); - - public Either requestCertificationComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction); - - public Either startComponentCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction); - - public Either checkoutComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction); - - public Either certifyComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction); - - public Either cancelOrFailCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, LifecycleStateEnum nextState, boolean b); - - public Either deleteOldComponentVersions(NodeTypeEnum nodeType, String componentName, String uuid, boolean inTransaction); - - public Either undoCheckout(NodeTypeEnum nodeType, Component resource, User modifier, User currentOwner, boolean inTransaction); - - public ComponentOperation getComponentOperation(NodeTypeEnum componentType); - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java deleted file mode 100644 index 76f95f3c2b..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.api; - -import java.util.List; -import java.util.Set; - -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Product; - -import fj.data.Either; - -public interface IProductOperation extends IComponentOperation { - public Either, StorageOperationStatus> getProductCatalogData(boolean inTransaction); - - public Either createProduct(Product product); - - public Either createProduct(Product product, boolean inTransaction); - - public Either deleteProduct(String productId, boolean inTransaction); - - public Either, StorageOperationStatus> getFollowed(String userId, Set lifecycleStates, Set lastStateStates, boolean inTransaction); - - public void rollback(); - - public void commit(); - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java index f9f960fdbf..3dd49f1aee 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java @@ -32,29 +32,6 @@ import fj.data.Either; public interface IPropertyOperation { - /** - * add property to resource - * - * @param propertyName - * @param propertyDefinition - * @param nodeType - * @param id - * @return - * - * public Either addPropertyToResource( String propertyName, PropertyDefinition propertyDefinition, NodeTypeEnum nodeType, String id); - */ - - /** - * get property belongs to resource - * - * @param propertyName - * - property name - * @param resourceId - * - resource unique id - * @return - */ - public Either getPropertyOfResource(String propertyName, String resourceId); - /** * Delete all properties of resource * @@ -76,8 +53,6 @@ public interface IPropertyOperation { */ public Either addDataType(DataTypeDefinition dataTypeDefinition); - public Either addDataType(DataTypeDefinition dataTypeDefinition, boolean inTransaction); - /** * @param name * @return @@ -86,14 +61,10 @@ public interface IPropertyOperation { public Either getDataTypeByName(String name, boolean inTransaction); - public Either getDataTypeByNameWithoutDerived(String name, boolean inTransaction); - public Either getDataTypeByNameWithoutDerived(String name); public StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map dataTypes); - public Either updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition, boolean inTransaction); - public Either updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java deleted file mode 100644 index a2af44cf61..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.api; - -import java.util.List; -import java.util.Map; - -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.RequirementImplDef; - -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; - -public interface IRequirementOperation { - - /** - * add a requirement to resource - * - * @param reqName - * @param reqDefinition - * @param nodeType - * @param uniqueId - * @return - */ - public Either addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId); - - public Either addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction); - - public Either addRequirementImplToResource(String reqName, RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId); - - public Either addRequirementImplToResource(String reqName, RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId, boolean inTransaction); - - /** - * get requirement of resource - * - * @param reqName - * @param resourceId - * @return - */ - public Either getRequirementOfResource(String reqName, String resourceId); - - public Either getRequirementOfResource(String reqName, String resourceId, boolean inTransaction); - - public Either, StorageOperationStatus> getAllResourceRequirements(String resourceId, boolean inTransaction); - - Either>, StorageOperationStatus> getAllRequirementsOfResourceOnly(String resourceId, boolean inTransaction); - - public Either, TitanOperationStatus> getResourceRequirements(String resourceId); - - public Either, StorageOperationStatus> deleteAllRequirements(String resourceId, boolean inTransaction); - - public Either getRequirement(String uniqueId); - - StorageOperationStatus addRequirementToResource(TitanVertex metadataVertex, String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction); -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java deleted file mode 100644 index 8d9994ba8a..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java +++ /dev/null @@ -1,141 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.api; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Resource; - -import fj.data.Either; - -public interface IResourceOperation extends IComponentOperation { - - public TitanGenericDao getTitanGenericDao(); - - // public StorageOperationStatus lockResource(Resource resource); - // - // public StorageOperationStatus unlockResource(Resource resource); - - public Either createResource(Resource resource); - - public Either createResource(Resource resource, boolean inTransaction); - - public Either getResource(String resourceId); - - // public Either getResource_tx(String - // resourceId,boolean inTransaction); - - public Either getResource(String resourceId, boolean inTransaction); - - /** - * the method retrieves all the certified resources, the returned values are only abstract or only none abstract according to the supplied parameters. - * - * @param getAbstract - * the value defines which resources to return only abstract or only none abstract - * @return - */ - public Either, StorageOperationStatus> getAllCertifiedResources(boolean getAbstract); - - public Either, StorageOperationStatus> getAllCertifiedResources(boolean getAbstract, Boolean isHighest); - - public Either validateResourceNameExists(String resourceName, ResourceTypeEnum resourceType); - - public Either deleteResource(String resourceId); - - public Either deleteResource(String resourceId, boolean inTransaction); - - public Either updateResource(Resource resource); - - public Either updateResource(Resource resource, boolean inTransaction); - - public Either getNumberOfResourcesByName(String resourceName); - - // public Either, StorageOperationStatus> - // getResourceArtifactsForDelete(Resource resource); - - public Either, StorageOperationStatus> getFollowed(String userId, Set lifecycleStates, Set lastStateStates, boolean inTransaction); - - public Either, StorageOperationStatus> getCatalogData(Map propertiesToMatch, boolean inTransaction); - - public Either getLatestByName(String resourceName, boolean inTransaction); - - public Either overrideResource(Resource resource, Resource resourceSaved, boolean inTransaction); - - public Either, StorageOperationStatus> getTesterFollowed(String userId, Set lifecycleStates, boolean inTransaction); - - public Either, StorageOperationStatus> getResourceListByUuid(String uuid, boolean inTransaction); - - public Either, StorageOperationStatus> getLatestResourceByUuid(String uuid, boolean inTransaction); - - public Either, StorageOperationStatus> getResourceListBySystemName(String systemName, boolean inTransaction); - - public Either, StorageOperationStatus> getResourceCatalogData(boolean inTransaction); - - public Either, StorageOperationStatus> getResourceCatalogDataVFLatestCertifiedAndNonCertified(boolean inTransaction); - - public Either, StorageOperationStatus> getResourceByNameAndVersion(String name, String version, boolean inTransaction); - - public Either, StorageOperationStatus> getResourceByNameAndVersion(String name, String version); - - public Either getResourceBySystemNameAndVersion(String name, String version, Map additionalParams, boolean inTransaction); - - // public Either, StorageOperationStatus> - // getAllNotCheckoutResources(boolean getAbstract); - - // public Either, StorageOperationStatus> - // getAllNotCheckoutResources(boolean getAbstract, Boolean isHighest); - - public Either, StorageOperationStatus> getAllResourcesMarkedForDeletion(); - - public Either isResourceInUse(String resourceToDelete); - - public Either getLatestByToscaResourceName(String toscaResourceName, boolean inTransaction); - - public Either validateToscaResourceNameExists(String templateName); - - public Either validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends); - - /** - * - * @param resource the resource to look for its derived resources - * @return all resources which derives from the given resource - */ - Either, StorageOperationStatus> getAllDerivedResources(Resource resource); - - /** - * - * @return all root resources (i.e all normatives with tosca name {@code Resource.ROOT_RESOURCE} - */ - Either, StorageOperationStatus> getRootResources(); - - /** - * - * @return all resources with type VF - */ - Either, StorageOperationStatus> getVFResources(); - - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java deleted file mode 100644 index 51f21ce5b8..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.api; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.openecomp.sdc.be.model.*; - -import fj.data.Either; - -public interface IServiceOperation extends IComponentOperation { - - public Either createService(Service service); - - public Either createService(Service service, boolean inTransaction); - - public Either getService(String uniqueId); - - public Either getService(String uniqueId, boolean inTransaction); - - public Either getService(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction); - - public Either deleteService(String uniqueId); - - public Either deleteService(String uniqueId, boolean inTransaction); - - public Either validateServiceNameExists(String serviceName); - - public Either, StorageOperationStatus> getFollowed(String userId, Set lifecycleStates, Set lastStateStates, boolean inTransaction); - - public Either updateService(Service service, boolean inTransaction); - - public Either, StorageOperationStatus> getCatalogData(Map propertiesToMatch, boolean inTransaction); - - public Either, StorageOperationStatus> getTesterFollowed(String userId, Set lifecycleStates, boolean inTransaction); - - public Either, StorageOperationStatus> getCertifiedServicesWithDistStatus(Map propertiesToMatch, Set distStatus, boolean inTransaction); - - public Either updateDestributionStatus(Service service, User user, DistributionStatusEnum distributionStatus); - - public Either, StorageOperationStatus> getServiceCatalogData(boolean inTransaction); - - public Either, StorageOperationStatus> getServiceCatalogDataLatestCertifiedAndNotCertified(boolean inTransaction); - - public Either getServiceByNameAndVersion(String name, String version, Map additionalParams, boolean inTransaction); - - public Either getServiceByNameAndVersion(String name, String version); - - public Either getServiceBySystemNameAndVersion(String name, String version, boolean inTransaction); - - public Either, StorageOperationStatus> getServiceListByUuid(String uuid, boolean inTransaction); - - public Either, StorageOperationStatus> getLatestServiceByUuid(String uuid, boolean inTransaction); - - public Either, StorageOperationStatus> getServiceListBySystemName(String systemName, boolean inTransaction); - - Either , StorageOperationStatus> getAll(); -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java index 254432c682..3df954fc36 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java @@ -36,8 +36,6 @@ public interface IUserAdminOperation { public Either getUserData(String id, boolean inTransaction); - public Either getInactiveUserData(String id); - public Either saveUserData(User user); public Either updateUserData(User user); @@ -48,11 +46,6 @@ public interface IUserAdminOperation { public Either, ActionStatus> getAllUsersWithRole(String role, String status); - Either, ActionStatus> getAllUsers(); - public Either, StorageOperationStatus> getUserPendingTasksList(User user, Map properties); - public Either, ActionStatus> getUserDataWithFunctionalMenu(String userId); - - public Either createOrUpdateFunctionalMenu(String userId, String newFunctionalMenu); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ToscaDefinitionPathCalculator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ToscaDefinitionPathCalculator.java deleted file mode 100644 index 2a5893951a..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ToscaDefinitionPathCalculator.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.api; - -import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.model.ComponentInstance; - -import java.util.List; - -public interface ToscaDefinitionPathCalculator { - - List calculateToscaDefinitionPath(ComponentInstance componentInstance, GraphEdge edge); - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AllOperationsUtil.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AllOperationsUtil.java deleted file mode 100644 index c005176238..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AllOperationsUtil.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import org.springframework.stereotype.Component; - -@Component("all-operations") -public class AllOperationsUtil { - - @javax.annotation.Resource - private PropertyOperation propertyOperation; - - @javax.annotation.Resource - private RequirementOperation requirementOperation; - - @javax.annotation.Resource - private CapabilityOperation capabilityOperation; - - @javax.annotation.Resource - private ResourceOperation resourceOperation; - - public PropertyOperation getPropertyOperation() { - return propertyOperation; - } - - public RequirementOperation getRequirementOperation() { - return requirementOperation; - } - - public CapabilityOperation getCapabilityOperation() { - return capabilityOperation; - } - - public ResourceOperation getResourceOperation() { - return resourceOperation; - } - -} 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 1e1c9267e6..d9fe1eea92 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 @@ -130,24 +130,6 @@ public class ArtifactOperation implements IArtifactOperation { } - @Override - public StorageOperationStatus addArifactToComponent(TitanVertex artifactInfo, TitanVertex parentVertex, String label) { - - // save logical artifact ref name on edge as property - Map properties = new HashMap(); - properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), label); - String groupInfo = (String) titanGenericDao.getProperty(artifactInfo, GraphPropertiesDictionary.ARTIFACT_GROUP_TYPE.getProperty()); - if (groupInfo != null) - properties.put(GraphEdgePropertiesDictionary.GROUP_TYPE.getProperty(), groupInfo); - TitanOperationStatus relation = titanGenericDao.createEdge(parentVertex, artifactInfo, GraphEdgeLabels.ARTIFACT_REF, properties); - if (!relation.equals(TitanOperationStatus.OK)) { - log.debug("Failed to create relation in graph from id {} to new artifact {}", parentVertex, label); - return DaoStatusConverter.convertTitanStatusToStorageStatus(relation); - } - return StorageOperationStatus.OK; - - } - @Override public StorageOperationStatus addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, TitanVertex parentVertex) { @@ -344,156 +326,6 @@ public class ArtifactOperation implements IArtifactOperation { } } - @Override - public Either updateHeatEnvArtifact( String id, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, boolean inTransaction){ - - - Either status = dissociateAndAssociateHeatEnvArtifact(id, artifactEnvInfo, artifactId, newArtifactId, type, inTransaction); - - - if (status.isRight()) { - if (false == inTransaction) { - titanGenericDao.rollback(); - } - log.debug("Failed to update artifact {} of {} {}. status is {}", artifactId, type.getName(), id, status.right().value()); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "Failed to update artifact " + artifactId + " of " + type.getName() + " " + id + ". status is" + status.right().value(), artifactId, - String.valueOf(status.right().value())); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactId, String.valueOf(status.right().value())); - 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); - } - - } - - private Either dissociateAndAssociateHeatEnvArtifact(String id, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, boolean inTransaction) { - - ArtifactDefinition heatEnvArt = artifactEnvInfo; - if(heatEnvArt == null ){ - Either heatEnvEither = getHeatEnvByGeneratedFromId(artifactId); - if (heatEnvEither.isRight()) { - log.error("No heat env artifact node for id = {} ", artifactId); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - heatEnvArt = heatEnvEither.left().value(); - } - - Either status = updateArtifactOnGraph(heatEnvArt, heatEnvArt.getUniqueId(), type, id); - if(status.isRight()){ - log.error("Failed to update heat env. status is {}", status.right().value()); - return status; - } - - UniqueIdData generatedFromArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, heatEnvArt.getUniqueId()); - UniqueIdData oldArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId); - - Either deleteRelation = titanGenericDao.deleteRelation(generatedFromArtifactNode, oldArtifactNode, GraphEdgeLabels.GENERATED_FROM); - if (deleteRelation.isRight()) { - TitanOperationStatus titanStatus = deleteRelation.right().value(); - if (titanStatus == TitanOperationStatus.NOT_FOUND) { - titanStatus = TitanOperationStatus.INVALID_ID; - } - Either.right(titanStatus); - } - - UniqueIdData newArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, newArtifactId); - - Either createRelation = titanGenericDao.createRelation(generatedFromArtifactNode, newArtifactNode, GraphEdgeLabels.GENERATED_FROM, null); - if (createRelation.isRight()) { - log.error("Failed to create relation from heat_env {} to heat {}", newArtifactId, generatedFromArtifactNode); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value())); - } - return status; - } - - @Override - public Either updateArifactDefinition(ArtifactDefinition artifactInfo, boolean inTransaction) { - Either status = updateArifactDataDefinition(artifactInfo); - - if (status.isRight()) { - if (false == inTransaction) { - titanGenericDao.rollback(); - } - log.debug("Failed to update artifact {}", artifactInfo.getUniqueId()); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "Failed to update artifact " + artifactInfo.getUniqueId() + ". status is" + status.right().value(), artifactInfo.getUniqueId(), - String.valueOf(status.right().value())); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getUniqueId(), String.valueOf(status.right().value())); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value())); - } else { - if (false == inTransaction) { - titanGenericDao.commit(); - } - ArtifactData artifactData = status.left().value(); - - ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData); - log.debug("The returned ArtifactDefintion is {}", artifactDefResult); - return Either.left(artifactDefResult); - } - } - - @Override - public Either updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, boolean inTransaction) { - - updateVersionAndDate(artifactInfo, artifactInfo.getArtifactVersion()); - - Either status = updateArifactDataDefinition(artifactInfo); - - if (status.isRight()) { - if (false == inTransaction) { - titanGenericDao.rollback(); - } - log.debug("Failed to update artifact {}", artifactInfo.getUniqueId()); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "Failed to update artifact " + artifactInfo.getUniqueId() + ". status is" + status.right().value(), artifactInfo.getUniqueId(), - String.valueOf(status.right().value())); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getUniqueId(), String.valueOf(status.right().value())); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value())); - } else { - if (false == inTransaction) { - titanGenericDao.commit(); - } - ArtifactData artifactData = status.left().value(); - - ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData); - log.debug("The returned ArtifactDefintion is {}" , artifactDefResult); - return Either.left(artifactDefResult); - } - } - - @Override - public Either getHeatEnvByGeneratedFromId(String generatedFromId) { - String heatEnvId = generatedFromId.concat("env"); - Either heatEnvEither = getArtifactById(heatEnvId, true); - if (heatEnvEither.isRight()) { - log.error("No heat env artifact node for id = {} ", heatEnvId); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - return heatEnvEither; - } - - private Either updateArifactDataDefinition(ArtifactDefinition artifactInfo) { - Either graph = titanGenericDao.getGraph(); - if (graph.isRight()) { - return Either.right(graph.right().value()); - } - - ArtifactData artifactData = new ArtifactData(artifactInfo); - - Either status = titanGenericDao.updateNode(artifactData, ArtifactData.class); - - if (status.isRight()) { - return Either.right(status.right().value()); - - } - return Either.left(status.left().value()); - } - @Override public Either removeArifactFromResource(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact, boolean inTransaction) { Either status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact); @@ -519,10 +351,6 @@ public class ArtifactOperation implements IArtifactOperation { } } - public Either updateToscaArtifactNameOnGraph(ArtifactDefinition artifactInfo, String artifactId, NodeTypeEnum type, String id) { - return updateArtifactOnGraph(artifactInfo, artifactId, type, id); - } - @SuppressWarnings("null") private Either updateArtifactOnGraph(ArtifactDefinition artifactInfo, String artifactId, NodeTypeEnum type, String id) { @@ -740,30 +568,7 @@ public class ArtifactOperation implements IArtifactOperation { return Either.left(true); } - public Either getParentsOfArtifact(String artifactId, NodeTypeEnum type) { - Either graph = titanGenericDao.getGraph(); - if (graph.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); - } - TitanGraph tGraph = graph.left().value(); - @SuppressWarnings("unchecked") - Iterable verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId).vertices(); - Iterator 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 iterEdge = artifactV.edges(Direction.IN, GraphEdgeLabels.ARTIFACT_REF.getProperty()); - int edgeCount = 0; - while (iterEdge.hasNext()) { - Edge edge = iterEdge.next(); - ++edgeCount; - } - return Either.left(edgeCount); - } - - public Either removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { + private Either removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { Either graph = titanGenericDao.getGraph(); if (graph.isRight()) { return Either.right(graph.right().value()); @@ -928,288 +733,7 @@ public class ArtifactOperation implements IArtifactOperation { } - public Either, StorageOperationStatus> getArtifactsVertecies(String parentId, NodeTypeEnum parentType, boolean inTransaction) { - Either, StorageOperationStatus> result = null; - try { - Either 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 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 iterator = vertices.iterator(); - - Map artifactMap = new HashMap(); - while (iterator.hasNext()) { - Vertex vertex = iterator.next(); - Iterator iteratorEdge = vertex.edges(Direction.OUT, GraphEdgeLabels.ARTIFACT_REF.getProperty()); - - if (iteratorEdge != null) { - - while (iteratorEdge.hasNext()) { - Edge edge = iteratorEdge.next(); - - TitanVertex artifactV = (TitanVertex) edge.inVertex(); - String label = (String) titanGenericDao.getProperty(artifactV, GraphPropertiesDictionary.ARTIFACT_LABEL.getProperty()); - artifactMap.put(label, artifactV); - log.debug("Artifact was added to list {}", label); - } - } - } - result = Either.left(artifactMap); - return result; - } finally { - if (inTransaction == false) { - if (result == null || result.isRight()) { - this.titanGenericDao.rollback(); - } else { - this.titanGenericDao.commit(); - } - - } - } - - } - - @Override - public Either getArtifactById(String id, boolean inTransaction) { - Either result = null; - try { - Either artifact = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), id, ArtifactData.class); - if (artifact.isRight()) { - if (artifact.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - result = Either.right(StorageOperationStatus.ARTIFACT_NOT_FOUND); - } else { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(artifact.right().value())); - } - return result; - } - ArtifactData artifactData = artifact.left().value(); - - ArtifactDefinition artifactDef = new ArtifactDefinition(artifactData.getArtifactDataDefinition()); - List heatParams = new ArrayList(); - StorageOperationStatus heatParametersStatus = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDef.getUniqueId(), heatParams); - if (!heatParametersStatus.equals(StorageOperationStatus.OK)) { - log.debug("failed to get heat parameters for artifact {}", id); - return Either.right(heatParametersStatus); - } - if (!heatParams.isEmpty()) { - artifactDef.setListHeatParameters(heatParams); - } - - Either, TitanOperationStatus> generatedFromArtifact = titanGenericDao.getChild(artifactData.getUniqueIdKey(), (String) artifactData.getUniqueId(), GraphEdgeLabels.GENERATED_FROM, - NodeTypeEnum.ArtifactRef, ArtifactData.class); - if (generatedFromArtifact.isLeft()) { - ImmutablePair pair = generatedFromArtifact.left().value(); - String generatedFromId = (String) pair.left.getUniqueId(); - log.debug("artifact {} is generated from {}.", artifactData.getUniqueId(), generatedFromId); - artifactDef.setGeneratedFromId(generatedFromId); - Either, StorageOperationStatus> heatParamsForEnv = getHeatParamsForEnv(artifactDef); - if (heatParamsForEnv.isRight()) { - log.debug("failed to get heat parameters values for heat artifact {}", artifactDef.getUniqueId()); - return Either.right(heatParamsForEnv.right().value()); - } else { - artifactDef.setListHeatParameters(heatParamsForEnv.left().value()); - } - } - - result = Either.left(artifactDef); - return result; - } finally { - if (inTransaction == false) { - if (result == null || result.isRight()) { - this.titanGenericDao.rollback(); - } else { - this.titanGenericDao.commit(); - } - - } - } - } - - public Either, StorageOperationStatus> getHeatParamsForEnv(ArtifactDefinition heatEnvArtifact) { - - List heatParams = new ArrayList(); - StorageOperationStatus heatParametersStatus = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, heatEnvArtifact.getGeneratedFromId(), heatParams); - if (!heatParametersStatus.equals(StorageOperationStatus.OK)) { - log.debug("failed to get heat parameters for node {}", heatEnvArtifact.getGeneratedFromId()); - return Either.right(heatParametersStatus); - } - if (!heatParams.isEmpty()) { - - Map heatValuesMap = new HashMap(); - Either>, TitanOperationStatus> heatEnvValuesWithEdges = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), heatEnvArtifact.getUniqueId(), - GraphEdgeLabels.PARAMETER_VALUE, NodeTypeEnum.HeatParameterValue, HeatParameterValueData.class); - - if (heatEnvValuesWithEdges.isRight() && !heatEnvValuesWithEdges.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - TitanOperationStatus status = heatEnvValuesWithEdges.right().value(); - if (!status.equals(TitanOperationStatus.NOT_FOUND)) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } else if (heatEnvValuesWithEdges.isLeft()) { - for (ImmutablePair pair : heatEnvValuesWithEdges.left().value()) { - HeatParameterValueData parameterValue = pair.left; - Object heatParameterName = pair.right.getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty()); - heatValuesMap.put((String) heatParameterName, parameterValue); - } - } - - for (HeatParameterDefinition parameter : heatParams) { - if (parameter.getCurrentValue() != null) { - if ("number".equals(parameter.getType())) { - parameter.setDefaultValue(new BigDecimal(parameter.getCurrentValue()).toPlainString()); - } else { - parameter.setDefaultValue(parameter.getCurrentValue()); - } - } - HeatParameterValueData heatParameterValueData = heatValuesMap.get(parameter.getName()); - if (heatParameterValueData != null && heatParameterValueData.getValue() != null) { - if ("number".equals(parameter.getType())) { - parameter.setCurrentValue(new BigDecimal(heatParameterValueData.getValue()).toPlainString()); - } else { - parameter.setCurrentValue(heatParameterValueData.getValue()); - } - parameter.setUniqueId((String) heatParameterValueData.getUniqueId()); - - } - } - } - - return Either.left(heatParams); - - } - - @Override - public Either, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, String groupType) { - - Either, StorageOperationStatus> result = null; - try { - Either 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 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 iterator = vertices.iterator(); - Vertex vertex = iterator.next(); - - Map edgeProperties = null; - if (groupType != null) { - edgeProperties = new HashMap<>(); - edgeProperties.put(GraphEdgePropertiesDictionary.GROUP_TYPE.getProperty(), groupType); - } - Either>, TitanOperationStatus> childrenByEdgeCriteria = titanGenericDao.getChildrenByEdgeCriteria(vertex, parentId, GraphEdgeLabels.ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class, - edgeProperties); - - if (childrenByEdgeCriteria.isRight()) { - TitanOperationStatus status = childrenByEdgeCriteria.right().value(); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - List> list = childrenByEdgeCriteria.left().value(); - - Map artifactsMap = new HashMap<>(); - - for (ImmutablePair pair : list) { - ArtifactData artifactData = pair.getLeft(); - ArtifactDefinition artifactDefinition = new ArtifactDefinition(artifactData.getArtifactDataDefinition()); - - List 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); - } - - Either, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactDefinition.getUniqueId(), GraphEdgeLabels.GENERATED_FROM, - NodeTypeEnum.ArtifactRef, ArtifactData.class); - - if (getResult.isRight()) { - TitanOperationStatus status = getResult.right().value(); - if (!status.equals(TitanOperationStatus.NOT_FOUND)) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } else { - ImmutablePair immutablePair = getResult.left().value(); - artifactDefinition.setGeneratedFromId((String) immutablePair.left.getUniqueId()); - } - - artifactsMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - log.debug("Artifact {} was added to list ", artifactData.getUniqueId()); - } - - result = Either.left(artifactsMap); - return result; - - } finally { - if (inTransaction == false) { - if (result == null || result.isRight()) { - this.titanGenericDao.rollback(); - } else { - this.titanGenericDao.commit(); - } - - } - } - } - - @Override - public Either addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String parentId, NodeTypeEnum parentType, boolean failIfExist) { - - Either result = null; - Either heatArtifactOnGraph = addArifactToComponent(artifactHeatEnv, parentId, parentType, failIfExist, true); - if (heatArtifactOnGraph.isRight()) { - log.debug("failed to create heat env artifact on graph"); - result = heatArtifactOnGraph; - return result; - } - - ArtifactDefinition artifactDefinition = heatArtifactOnGraph.left().value(); - // add relation from heatEnv to heat - UniqueIdData heatData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactHeat.getUniqueId()); - UniqueIdData heatEnvData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactDefinition.getUniqueId()); - - Either relation = titanGenericDao.getRelation(heatEnvData, heatData, GraphEdgeLabels.GENERATED_FROM); - if (relation.isRight()) { - // TODO: add error in case of error - TitanOperationStatus status = relation.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - Either createRelation = titanGenericDao.createRelation(heatEnvData, heatData, GraphEdgeLabels.GENERATED_FROM, null); - if (createRelation.isRight()) { - status = createRelation.right().value(); - log.debug("failed to add relation from heat_env artifact to heat artifact. error: {}", status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - } - } - - artifactDefinition.setGeneratedFromId(artifactHeat.getUniqueId()); - log.trace("heat env artifact added successfuly to resource instance"); - result = Either.left(artifactDefinition); - return result; - } - - public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion) { + private void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion) { if (oldVesrion == null || oldVesrion.isEmpty()) oldVesrion = "0"; @@ -1240,96 +764,4 @@ public class ArtifactOperation implements IArtifactOperation { artifactData.setArtifactVersion(String.valueOf(newVersion)); } - @Override - public Either getHeatArtifactByHeatEnvId(String heatEnvId, boolean inTransaction) { - - Either result = null; - try { - Either 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 vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), heatEnvId).vertices(); - if (vertices == null || vertices.iterator() == null || false == vertices.iterator().hasNext()) { - log.debug("No nodes for type {} for id = {}", NodeTypeEnum.ArtifactRef, heatEnvId); - result = Either.right(StorageOperationStatus.INVALID_ID); - return result; - } - - Iterator iterator = vertices.iterator(); - Vertex vertex = iterator.next(); - - Map edgeProperties = null; - Either>, TitanOperationStatus> childrenByEdgeCriteria = titanGenericDao.getChildrenByEdgeCriteria(vertex, heatEnvId, GraphEdgeLabels.GENERATED_FROM, NodeTypeEnum.ArtifactRef, ArtifactData.class, - edgeProperties); - - if (childrenByEdgeCriteria.isRight()) { - TitanOperationStatus status = childrenByEdgeCriteria.right().value(); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - List> list = childrenByEdgeCriteria.left().value(); - - if (list == null || list.isEmpty() == true) { - return Either.right(StorageOperationStatus.NOT_FOUND); - } - - if (list.size() > 1) { - return Either.right(StorageOperationStatus.INVALID_ID); - } - - ImmutablePair immutablePair = list.get(0); - - ArtifactDefinition artifactDefinition = new ArtifactDefinition(immutablePair.left.getArtifactDataDefinition()); - - log.debug("The artifact {} was generated from artifact {}", heatEnvId, artifactDefinition); - - result = Either.left(artifactDefinition); - return result; - - } finally { - if (inTransaction == false) { - if (result == null || result.isRight()) { - this.titanGenericDao.rollback(); - } else { - this.titanGenericDao.commit(); - } - - } - } - } - - @Override - public Either getLatestArtifactDataByArtifactUUID(String artifactUUID, boolean inTransaction) { - Either result = null; - try { - NodeTypeEnum nodeType = NodeTypeEnum.ArtifactRef; - Map propertiesToMatch = new HashMap<>(); - propertiesToMatch.put(GraphPropertiesDictionary.ARTIFACT_UUID.getProperty(), artifactUUID); - Either, TitanOperationStatus> getArtifactEither = titanGenericDao.getByCriteria(nodeType, propertiesToMatch, ArtifactData.class); - if (getArtifactEither.isRight()) { - log.debug("Couldn't fetch artifact data for artifact with uuid {}, error: {}", nodeType, getArtifactEither.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getArtifactEither.right().value())); - } else { - List artifacts = getArtifactEither.left().value(); - ArtifactData latestArtifact = artifacts.size() == 1 ? artifacts.get(0) - : artifacts.stream().max((a1, a2) -> Double.compare(Double.parseDouble(a1.getArtifactDataDefinition().getArtifactVersion()), Double.parseDouble(a2.getArtifactDataDefinition().getArtifactVersion()))).get(); - result = Either.left(latestArtifact); - } - return result; - } finally { - if (!inTransaction) { - if (result == null || result.isRight()) { - this.titanGenericDao.rollback(); - } else { - this.titanGenericDao.commit(); - } - } - } - } - } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java deleted file mode 100644 index 279aab667c..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java +++ /dev/null @@ -1,461 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.function.Consumer; -import java.util.function.Supplier; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.operations.api.IAttributeOperation; -import org.openecomp.sdc.be.model.operations.api.IPropertyOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.resources.data.AttributeData; -import org.openecomp.sdc.be.resources.data.AttributeValueData; -import org.openecomp.sdc.common.datastructure.Wrapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; - -/** - * Class For Data Model Logic Relevant For Attributes - * - * @author mshitrit - * - */ -@Component("attribute-operation") -public class AttributeOperation extends AbstractOperation implements IAttributeOperation { - private static Logger log = LoggerFactory.getLogger(AttributeOperation.class.getName()); - @Autowired - private IPropertyOperation propertyOperation; - - /** - * - * Add attribute to graph. - * - * 1. Add attribute 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 attributeDefinition - * @return - */ - private Either addAttributeToNodeType(PropertyDefinition attributeDefinition, NodeTypeEnum nodeType, String nodeUniqueId) { - String attUniqueId = UniqueIdBuilder.buildAttributeUid(nodeUniqueId, attributeDefinition.getName()); - Supplier dataBuilder = () -> buildAttributeData(attributeDefinition, attUniqueId); - Supplier defNameGenerator = () -> "Attribute : " + attributeDefinition.getName(); - - return addDefinitionToNodeType(attributeDefinition, nodeType, nodeUniqueId, GraphEdgeLabels.ATTRIBUTE, dataBuilder, defNameGenerator); - - } - - private TitanOperationStatus addAttributeToNodeType(TitanVertex metadataVertex, PropertyDefinition attributeDefinition, NodeTypeEnum nodeType, String nodeUniqueId) { - String attUniqueId = UniqueIdBuilder.buildAttributeUid(nodeUniqueId, attributeDefinition.getName()); - Supplier dataBuilder = () -> buildAttributeData(attributeDefinition, attUniqueId); - Supplier defNameGenerator = () -> "Attribute : " + attributeDefinition.getName(); - - return addDefinitionToNodeType(metadataVertex, attributeDefinition, nodeType, nodeUniqueId, GraphEdgeLabels.ATTRIBUTE, dataBuilder, defNameGenerator); - - } - - private AttributeData buildAttributeData(PropertyDefinition attributeDefinition, String attUniqueId) { - attributeDefinition.setUniqueId(attUniqueId); - return new AttributeData(attributeDefinition); - } - - @Override - public Either deleteAttribute(String attributeId) { - Either either = deleteAttributeFromGraph(attributeId); - if (either.isRight()) { - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value()); - return Either.right(storageStatus); - } - return Either.left(either.left().value()); - } - - @Override - public Either, StorageOperationStatus> deleteAllAttributeAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) { - Wrapper errorWrapper; - List attributes = new ArrayList<>(); - TitanOperationStatus findAllResourceAttribues = findNodeNonInheretedAttribues(uniqueId, NodeTypeEnum.Resource, attributes); - errorWrapper = (findAllResourceAttribues != TitanOperationStatus.OK) ? new Wrapper<>(findAllResourceAttribues) : new Wrapper<>(); - - if (errorWrapper.isEmpty()) { - for (PropertyDefinition attDef : attributes) { - log.debug("Before deleting attribute from graph {}", attDef.getUniqueId()); - Either deleteNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Attribute), attDef.getUniqueId(), AttributeData.class); - if (deleteNode.isRight()) { - errorWrapper.setInnerElement(deleteNode.right().value()); - break; - } - } - } - - if (errorWrapper.isEmpty()) { - Map attributesMap = attributes.stream().collect(Collectors.toMap(e -> e.getName(), e -> e)); - return Either.left(attributesMap); - } else { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(errorWrapper.getInnerElement())); - } - - } - - private Either deleteAttributeFromGraph(String attributeId) { - log.debug("Before deleting attribute from graph {}", attributeId); - return titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Attribute), attributeId, AttributeData.class); - } - - @Override - public TitanOperationStatus addAttributesToGraph(TitanVertex metadataVertex, Map attributes, String resourceId, Map dataTypes) { - TitanOperationStatus titanStatus = TitanOperationStatus.OK; - for (PropertyDefinition attribute : attributes.values()) { - TitanOperationStatus eitherAddAttribute = addAttributeToGraphByVertex(metadataVertex, attribute, resourceId, dataTypes); - if (!eitherAddAttribute.equals(TitanOperationStatus.OK)) { - titanStatus = eitherAddAttribute; - break; - } - } - return titanStatus; - } - - @Override - public Either, TitanOperationStatus> getAllAttributesOfResourceInstance(ComponentInstance compInstance) { - - Either, TitanOperationStatus> result; - - Either>, TitanOperationStatus> attributeImplNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), compInstance.getUniqueId(), - GraphEdgeLabels.ATTRIBUTE_VALUE, NodeTypeEnum.AttributeValue, AttributeValueData.class); - - // Build From Resource - if (attributeImplNodes.isRight() && attributeImplNodes.right().value() == TitanOperationStatus.NOT_FOUND) { - result = getAttributesFromResource(compInstance); - } - // Build From Instance - else if (attributeImplNodes.isLeft()) { - List> attributesFromRI = attributeImplNodes.left().value(); - result = mergeAttributesResults(getAttributesFromResource(compInstance), convertToComponentInstanceAttribute(attributesFromRI)); - } - // Error - else { - TitanOperationStatus status = attributeImplNodes.right().value(); - result = Either.right(status); - } - - return result; - } - - private Either, TitanOperationStatus> mergeAttributesResults(Either, TitanOperationStatus> eitherAttributesThatDoesNotExistOnRI, - Either, TitanOperationStatus> eitherAttributesThatExistOnRI) { - - Either, TitanOperationStatus> result; - if (eitherAttributesThatExistOnRI.isRight()) { - result = Either.right(eitherAttributesThatExistOnRI.right().value()); - } else if (eitherAttributesThatDoesNotExistOnRI.isRight()) { - result = Either.right(eitherAttributesThatDoesNotExistOnRI.right().value()); - } else { - final List attributesThatExistOnRI = eitherAttributesThatExistOnRI.left().value(); - final List attributesThatDoesNotExistOnRI = eitherAttributesThatDoesNotExistOnRI.left().value(); - Set attributesIdThatExistOnRI = attributesThatExistOnRI.stream().map(e -> e.getUniqueId()).collect(Collectors.toSet()); - // Attributes From The Resource Without attributes that also exist - // on the instance - Stream filterAttributesThatDoesNotExistOnRI = attributesThatDoesNotExistOnRI.stream().filter(e -> !attributesIdThatExistOnRI.contains(e.getUniqueId())); - // Add Fields From Resource Attributes - fillAttributeInfoFromResource(attributesThatExistOnRI, attributesThatDoesNotExistOnRI); - // Adding the Attributes on the instance for the full list - List mergedList = Stream.concat(filterAttributesThatDoesNotExistOnRI, attributesThatExistOnRI.stream()).collect(Collectors.toList()); - result = Either.left(mergedList); - } - return result; - } - - private void fillAttributeInfoFromResource(List attributesThatExistOnRI, List attributesThatDoesNotExistOnRI) { - attributesThatExistOnRI.stream() - .forEach(e -> addAttributeInfo(e, - // Finds the same attribute in the resource - attributesThatDoesNotExistOnRI.stream().filter(e2 -> e2.getUniqueId().equals(e.getUniqueId())).findAny().get())); - - } - - private void addAttributeInfo(ComponentInstanceProperty attributeFromRI, ComponentInstanceProperty attributeFromResource) { - attributeFromRI.setName(attributeFromResource.getName()); - attributeFromRI.setDescription(attributeFromResource.getDescription()); - attributeFromRI.setDefaultValue(attributeFromResource.getDefaultValue()); - attributeFromRI.setStatus(attributeFromResource.getStatus()); - attributeFromRI.setSchema(attributeFromResource.getSchema()); - if (StringUtils.isEmpty(attributeFromRI.getValue())) { - attributeFromRI.setValue(attributeFromResource.getDefaultValue()); - } - } - - private Either, TitanOperationStatus> getAttributesFromResource(ComponentInstance compInstance) { - Either, TitanOperationStatus> result; - List attributes = new ArrayList<>(); - // Attributes does not exist on Ri - fetch them from resource - TitanOperationStatus findAllResourceAttribues = findAllResourceAttributesRecursively(compInstance.getComponentUid(), attributes); - if (findAllResourceAttribues != TitanOperationStatus.OK) { - result = Either.right(findAllResourceAttribues); - } else { - List buildAttInstanceFromResource = attributes.stream().map(attDef -> new ComponentInstanceProperty(false, attDef, null)).collect(Collectors.toList()); - - // Set Value to be default value in case it is empty - Consumer valueSetter = att -> { - if (StringUtils.isEmpty(att.getValue())) { - att.setValue(att.getDefaultValue()); - } - }; - buildAttInstanceFromResource.stream().forEach(valueSetter); - - result = Either.left(buildAttInstanceFromResource); - } - return result; - } - - private Either, TitanOperationStatus> convertToComponentInstanceAttribute(List> list) { - Either, TitanOperationStatus> result = null; - List componentInstanceAttribute = new ArrayList<>(); - for (ImmutablePair attributeValue : list) { - AttributeValueData attributeValueData = attributeValue.getLeft(); - String attributeValueUid = attributeValueData.getUniqueId(); - - Either, TitanOperationStatus> attributeDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.AttributeValue), attributeValueUid, GraphEdgeLabels.ATTRIBUTE_IMPL, - NodeTypeEnum.Attribute, AttributeData.class); - - if (attributeDefRes.isRight()) { - TitanOperationStatus status = attributeDefRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - result = Either.right(status); - break; - } else { - ImmutablePair attributeDefPair = attributeDefRes.left().value(); - String attributeUniqueId = attributeDefPair.left.getUniqueId(); - - ComponentInstanceProperty resourceInstanceAttribute = new ComponentInstanceProperty(); - // set attribute original unique id - resourceInstanceAttribute.setUniqueId(attributeUniqueId); - // set hidden - resourceInstanceAttribute.setHidden(attributeValueData.isHidden()); - // set value - resourceInstanceAttribute.setValue(attributeValueData.getValue()); - // set property value unique id - resourceInstanceAttribute.setValueUniqueUid(attributeValueUid); - - resourceInstanceAttribute.setType(attributeValueData.getType()); - - componentInstanceAttribute.add(resourceInstanceAttribute); - } - - } - if (result == null) { - result = Either.left(componentInstanceAttribute); - } - return result; - } - - /** - * fetch all attributes under a given resource(includes its parents' resources) - * - * @param resourceId - * @param attributes - * @return - */ - @Override - public TitanOperationStatus findAllResourceAttributesRecursively(String resourceId, List attributes) { - final NodeElementFetcher singleNodeFetcher = (resourceIdParam, attributesParam) -> findNodeNonInheretedAttribues(resourceIdParam, NodeTypeEnum.Resource, attributesParam); - return findAllResourceElementsDefinitionRecursively(resourceId, attributes, singleNodeFetcher); - - } - - @Override - public TitanOperationStatus findNodeNonInheretedAttribues(String uniqueId, NodeTypeEnum nodeType, List attributes) { - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.ATTRIBUTE, NodeTypeEnum.Attribute, - AttributeData.class); - - if (childrenNodes.isRight()) { - TitanOperationStatus status = childrenNodes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - return status; - } - - List> values = childrenNodes.left().value(); - if (values != null) { - - for (ImmutablePair immutablePair : values) { - AttributeData attData = immutablePair.getLeft(); - String attributeName = attData.getAttributeDataDefinition().getName(); - - log.debug("Attribute {} is associated to node {}", attributeName, uniqueId); - AttributeData attributeData = immutablePair.getKey(); - PropertyDefinition attributeDefinition = this.convertAttributeDataToAttributeDefinition(attributeData, attributeName, uniqueId); - - attributes.add(attributeDefinition); - - log.trace("findAttributesOfNode - property {} associated to node {}", attributeDefinition, uniqueId); - } - - } - - return TitanOperationStatus.OK; - } - - @Override - public PropertyDefinition convertAttributeDataToAttributeDefinition(AttributeData attributeData, String attributeName, String resourceId) { - log.debug("The object returned after create attribute is {}", attributeData); - PropertyDefinition attributeDefResult = new PropertyDefinition(attributeData.getAttributeDataDefinition()); - attributeDefResult.setName(attributeName); - attributeDefResult.setParentUniqueId(resourceId); - return attributeDefResult; - } - - @Override - public Either addAttribute(PropertyDefinition attributeDefinition, String resourceId) { - - Either eitherResult; - Either, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - log.debug("Cannot find any data type. Status is {}.", status); - eitherResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } else { - Either either = addAttributeToGraph(attributeDefinition, resourceId, allDataTypes.left().value()); - if (either.isRight()) { - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value()); - eitherResult = Either.right(storageStatus); - } else { - eitherResult = Either.left(either.left().value()); - } - } - return eitherResult; - } - - @Override - public Either updateAttribute(String attributeId, PropertyDefinition newAttDef, Map dataTypes) { - - StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(newAttDef, dataTypes); - if (validateAndUpdateAttribute != StorageOperationStatus.OK) { - return Either.right(validateAndUpdateAttribute); - } - - Either either = updateAttributeFromGraph(attributeId, newAttDef); - if (either.isRight()) { - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value()); - return Either.right(storageStatus); - } - return Either.left(either.left().value()); - } - - private Either updateAttributeFromGraph(String attributeId, PropertyDefinition attributeDefenition) { - log.debug("Before updating attribute on graph {}", attributeId); - - // get the original property data - Either eitherAttribute = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Attribute), attributeId, AttributeData.class); - if (eitherAttribute.isRight()) { - log.debug("Problem while get Attribute with id {}. Reason - {}", attributeId, eitherAttribute.right().value().name()); - return Either.right(eitherAttribute.right().value()); - } - AttributeData orgAttributeData = eitherAttribute.left().value(); - PropertyDataDefinition orgAttributeDataDefinition = orgAttributeData.getAttributeDataDefinition(); - - // create new property data to update - AttributeData newAttributeData = new AttributeData(); - newAttributeData.setAttributeDataDefinition(attributeDefenition); - PropertyDataDefinition newAttributeDataDefinition = newAttributeData.getAttributeDataDefinition(); - - // update the original property data with new values - if (!Objects.equals(orgAttributeDataDefinition.getDefaultValue(), newAttributeDataDefinition.getDefaultValue())) { - orgAttributeDataDefinition.setDefaultValue(newAttributeDataDefinition.getDefaultValue()); - } - - if (!Objects.equals(orgAttributeDataDefinition.getDescription(), newAttributeDataDefinition.getDescription())) { - orgAttributeDataDefinition.setDescription(newAttributeDataDefinition.getDescription()); - } - - if (!Objects.equals(orgAttributeDataDefinition.getType(), newAttributeDataDefinition.getType())) { - orgAttributeDataDefinition.setType(newAttributeDataDefinition.getType()); - } - - orgAttributeDataDefinition.setSchema(newAttributeDataDefinition.getSchema()); - - return titanGenericDao.updateNode(orgAttributeData, AttributeData.class); - } - - @Override - public ComponentInstanceProperty buildResourceInstanceAttribute(AttributeValueData attributeValueData, ComponentInstanceProperty resourceInstanceAttribute) { - - Boolean hidden = attributeValueData.isHidden(); - String uid = attributeValueData.getUniqueId(); - return new ComponentInstanceProperty(hidden, resourceInstanceAttribute, uid); - } - - @Override - public Either addAttributeToGraph(PropertyDefinition attribute, String resourceId, Map dataTypes) { - Either eitherResult; - StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(attribute, dataTypes); - if (validateAndUpdateAttribute != StorageOperationStatus.OK) { - log.error("Attribute {} is invalid. Status is {}", attribute, validateAndUpdateAttribute); - eitherResult = Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } else { - eitherResult = addAttributeToNodeType(attribute, NodeTypeEnum.Resource, resourceId); - - } - return eitherResult; - } - - @Override - public TitanOperationStatus addAttributeToGraphByVertex(TitanVertex metadataVertex, PropertyDefinition attribute, String resourceId, Map dataTypes) { - StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(attribute, dataTypes); - TitanOperationStatus result; - if (validateAndUpdateAttribute != StorageOperationStatus.OK) { - log.error("Attribute {} is invalid. Status is {}", attribute, validateAndUpdateAttribute); - result = TitanOperationStatus.ILLEGAL_ARGUMENT; - } else { - result = addAttributeToNodeType(metadataVertex, attribute, NodeTypeEnum.Resource, resourceId); - - } - return result; - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java deleted file mode 100644 index 818089feee..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java +++ /dev/null @@ -1,1170 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.tinkerpop.gremlin.structure.Edge; -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.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.operations.api.ICapabilityInstanceOperation; -import org.openecomp.sdc.be.resources.data.CapabilityData; -import org.openecomp.sdc.be.resources.data.CapabilityInstData; -import org.openecomp.sdc.be.resources.data.ComponentInstanceData; -import org.openecomp.sdc.be.resources.data.PropertyData; -import org.openecomp.sdc.be.resources.data.PropertyValueData; -import org.openecomp.sdc.be.resources.data.UniqueIdData; -import org.openecomp.sdc.common.datastructure.Wrapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; - -/** - * public class CapabilityInstanceOperation provides methods for CRUD operations for CapabilityInstance on component instance level - * - * @author ns019t - * - */ -@Component("capability-instance-operation") -public class CapabilityInstanceOperation extends AbstractOperation implements ICapabilityInstanceOperation { - - private static Logger log = LoggerFactory.getLogger(CapabilityOperation.class.getName()); - - @Autowired - private PropertyOperation propertyOperation; - - @Autowired - private CapabilityOperation capabilityOperation; - - /** - * create capability instance of capability with property values for resource instance - * - * @param resourceInstanceId - * @param capabilityId - * @param propertyValues - * @param validateCapabilityInstExistence - * @param capabilityName - * @return - */ - @Override - public Either>, TitanOperationStatus> createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(String resourceInstanceId, String capabilityId, String capabilityName, - List propertyValues, boolean validateCapabilityInstExistence) { - Wrapper errorWrapper = new Wrapper<>(); - Wrapper overrideCapabilityDataWrapper = new Wrapper<>(); - Wrapper overrideCapabilityDefinitionWrapper = new Wrapper<>(); - Either createCapabilityRes = null; - CapabilityInstData createdCapabilityInstance = null; - - Wrapper> defaultPropertiesWrapper = new Wrapper<>(); - Either, TitanOperationStatus> getCapabilityRes = null; - Either getCapabilityDefinitionRes = null; - Either, TitanOperationStatus> addPropertyValuesRes = null; - Wrapper createdCapabilityInstanceIdWrapper = new Wrapper<>(); - if (validateCapabilityInstExistence) { - validateCapabilityInstanceExistence(resourceInstanceId, capabilityId, errorWrapper); - } - if (errorWrapper.isEmpty()) { - getCapabilityRes = getCapabilitiesOfResourceInstance(resourceInstanceId, capabilityId, capabilityName, errorWrapper); - } - if (errorWrapper.isEmpty()) { - getCapabilityDefinitionRes = getCapabiityDefinition(resourceInstanceId, capabilityId, errorWrapper, overrideCapabilityDataWrapper, getCapabilityRes); - } - if (errorWrapper.isEmpty()) { - createCapabilityRes = createCapabilityInstanceOnGraph(resourceInstanceId, capabilityId, errorWrapper, overrideCapabilityDataWrapper, overrideCapabilityDefinitionWrapper, getCapabilityDefinitionRes); - } - if (errorWrapper.isEmpty() && overrideCapabilityDefinitionWrapper.getInnerElement().getProperties() != null) { - createdCapabilityInstance = validateCapabilityInstanceProperties(resourceInstanceId, propertyValues, errorWrapper, overrideCapabilityDefinitionWrapper, createCapabilityRes, defaultPropertiesWrapper, createdCapabilityInstanceIdWrapper); - } - if (errorWrapper.isEmpty()) { - addPropertyValuesRes = addPropertyValueToCapabilityInstance(resourceInstanceId, propertyValues, errorWrapper, createCapabilityRes, defaultPropertiesWrapper, createdCapabilityInstanceIdWrapper); - } - Either>, TitanOperationStatus> result; - if (errorWrapper.isEmpty()) { - Map> resultMap = new HashMap<>(); - resultMap.put(createdCapabilityInstance, addPropertyValuesRes.left().value()); - result = Either.left(resultMap); - } else { - result = Either.right(errorWrapper.getInnerElement()); - } - return result; - } - - @Override - public TitanOperationStatus createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(TitanVertex resourceInstanceVertex, String resourceInstanceId, String capabilityId, String capabilityName, - List propertyValues, boolean validateCapabilityInstExistence) { - Wrapper errorWrapper = new Wrapper<>(); - Wrapper overrideCapabilityDataWrapper = new Wrapper<>(); - Wrapper overrideCapabilityDefinitionWrapper = new Wrapper<>(); - Either createCapabilityRes = null; - TitanVertex createdCapabilityInstance = null; - - Wrapper> defaultPropertiesWrapper = new Wrapper<>(); - Either, TitanOperationStatus> getCapabilityRes = null; - Either getCapabilityDefinitionRes = null; - TitanOperationStatus addPropertyValuesRes = null; - Wrapper createdCapabilityInstanceIdWrapper = new Wrapper<>(); - if (validateCapabilityInstExistence) { - validateCapabilityInstanceExistence(resourceInstanceVertex, resourceInstanceId, capabilityId, errorWrapper); - } - if (errorWrapper.isEmpty()) { - getCapabilityRes = getCapabilitiesOfResourceInstance(resourceInstanceVertex, resourceInstanceId, capabilityId, capabilityName, errorWrapper); - } - if (errorWrapper.isEmpty()) { - getCapabilityDefinitionRes = getCapabiityDefinitionByVertex(resourceInstanceId, capabilityId, errorWrapper, overrideCapabilityDataWrapper, getCapabilityRes); - } - if (errorWrapper.isEmpty()) { - createCapabilityRes = createCapabilityInstanceOnGraphByVertex(resourceInstanceVertex, resourceInstanceId, capabilityId, errorWrapper, overrideCapabilityDataWrapper, overrideCapabilityDefinitionWrapper, getCapabilityDefinitionRes); - } - if (errorWrapper.isEmpty() && overrideCapabilityDefinitionWrapper.getInnerElement().getProperties() != null) { - createdCapabilityInstance = validateCapabilityInstancePropertiesByVertex(resourceInstanceId, propertyValues, errorWrapper, overrideCapabilityDefinitionWrapper, createCapabilityRes.left().value(), defaultPropertiesWrapper, - createdCapabilityInstanceIdWrapper); - } - if (errorWrapper.isEmpty()) { - addPropertyValuesRes = addPropertyValueToCapabilityInstanceByVertex(resourceInstanceId, propertyValues, errorWrapper, createCapabilityRes, defaultPropertiesWrapper, createdCapabilityInstanceIdWrapper); - } - - return addPropertyValuesRes; - } - - private Either, TitanOperationStatus> addPropertyValueToCapabilityInstance(String resourceInstanceId, List propertyValues, Wrapper errorWrapper, - Either createCapabilityRes, Wrapper> defaultPropertiesWrapper, Wrapper createdCapabilityInstanceIdWrapper) { - Either, TitanOperationStatus> addPropertyValuesRes; - log.debug("Before adding property values to capability instance {}.",createdCapabilityInstanceIdWrapper.getInnerElement()); - addPropertyValuesRes = addPropertyValuesToCapabilityInstance(createCapabilityRes.left().value(), propertyValues, defaultPropertiesWrapper.getInnerElement()); - if (addPropertyValuesRes.isRight()) { - errorWrapper.setInnerElement(addPropertyValuesRes.right().value()); - log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement()); - } - log.debug("After adding property values to capability instance {}. status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement()); - return addPropertyValuesRes; - } - - private TitanOperationStatus addPropertyValueToCapabilityInstanceByVertex(String resourceInstanceId, List propertyValues, Wrapper errorWrapper, - Either createCapabilityRes, Wrapper> defaultPropertiesWrapper, Wrapper createdCapabilityInstanceIdWrapper) { - log.trace("Before adding property values to capability instance {}", createdCapabilityInstanceIdWrapper.getInnerElement()); - TitanOperationStatus addPropertyValuesRes = addPropertyValuesToCapabilityInstance(createCapabilityRes.left().value(), propertyValues, defaultPropertiesWrapper.getInnerElement()); - if (!addPropertyValuesRes.equals(TitanOperationStatus.OK)) { - errorWrapper.setInnerElement(addPropertyValuesRes); - log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement()); - } - log.trace("After adding property values to capability instance {}. status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement()); - return addPropertyValuesRes; - } - - private CapabilityInstData validateCapabilityInstanceProperties(String resourceInstanceId, List propertyValues, Wrapper errorWrapper, - Wrapper overrideCapabilityDefinitionWrapper, Either createCapabilityRes, Wrapper> defaultPropertiesWrapper, - Wrapper createdCapabilityInstanceIdWrapper) { - CapabilityInstData createdCapabilityInstance; - createdCapabilityInstance = createCapabilityRes.left().value(); - createdCapabilityInstanceIdWrapper.setInnerElement(createdCapabilityInstance.getUniqueId()); - Map defaultProperties = overrideCapabilityDefinitionWrapper.getInnerElement().getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); - defaultPropertiesWrapper.setInnerElement(defaultProperties); - log.debug("Before validating property values of capability instance {}",createdCapabilityInstanceIdWrapper.getInnerElement()); - Either result = validateCapabilityInstanceProperties(defaultProperties, propertyValues); - if (result.isRight()) { - errorWrapper.setInnerElement(result.right().value()); - log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement()); - } - log.debug("After validating property values of capability instance {}. status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement()); - return createdCapabilityInstance; - } - - private TitanVertex validateCapabilityInstancePropertiesByVertex(String resourceInstanceId, List propertyValues, Wrapper errorWrapper, - Wrapper overrideCapabilityDefinitionWrapper, TitanVertex createCapabilityRes, Wrapper> defaultPropertiesWrapper, Wrapper createdCapabilityInstanceIdWrapper) { - - String id = (String) titanGenericDao.getProperty(createCapabilityRes, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - createdCapabilityInstanceIdWrapper.setInnerElement(id); - Map defaultProperties = overrideCapabilityDefinitionWrapper.getInnerElement().getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); - defaultPropertiesWrapper.setInnerElement(defaultProperties); - log.trace("Before validating property values of capability instance {}", createdCapabilityInstanceIdWrapper.getInnerElement()); - Either result = validateCapabilityInstanceProperties(defaultProperties, propertyValues); - if (result.isRight()) { - errorWrapper.setInnerElement(result.right().value()); - log.debug("Failed to add properties to capability instance {} of resource instance {}, status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement()); - } - log.trace("After validating property values of capability instance {}, status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement()); - return createCapabilityRes; - } - - private Either createCapabilityInstanceOnGraph(String resourceInstanceId, String capabilityId, Wrapper errorWrapper, Wrapper overrideCapabilityDataWrapper, - Wrapper overrideCapabilityDefinitionWrapper, Either getCapabilityDefinitionRes) { - Either createCapabilityRes; - log.debug("Before creating capability instance of capability {} on graph.", capabilityId); - overrideCapabilityDefinitionWrapper.setInnerElement(getCapabilityDefinitionRes.left().value()); - CapabilityInstData capabilityInstance = buildCapabilityInstanceData(resourceInstanceId, overrideCapabilityDefinitionWrapper.getInnerElement()); - createCapabilityRes = createCapabilityInstanceOnGraph(resourceInstanceId, overrideCapabilityDataWrapper.getInnerElement(), capabilityInstance); - if (createCapabilityRes.isRight()) { - errorWrapper.setInnerElement(createCapabilityRes.right().value()); - log.debug("Failed to create capability instance of capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - } - log.debug("After creating capability instance of capability {} on graph, status is {}", capabilityId, errorWrapper.getInnerElement()); - return createCapabilityRes; - } - - private Either createCapabilityInstanceOnGraphByVertex(TitanVertex riVertex, String resourceInstanceId, String capabilityId, Wrapper errorWrapper, - Wrapper overrideCapabilityDataWrapper, Wrapper overrideCapabilityDefinitionWrapper, Either getCapabilityDefinitionRes) { - Either createCapabilityRes; - log.trace("Before creating capability instance of capability {} on graph", capabilityId); - overrideCapabilityDefinitionWrapper.setInnerElement(getCapabilityDefinitionRes.left().value()); - CapabilityInstData capabilityInstance = buildCapabilityInstanceData(resourceInstanceId, overrideCapabilityDefinitionWrapper.getInnerElement()); - createCapabilityRes = createCapabilityInstanceOnGraph(riVertex, resourceInstanceId, overrideCapabilityDataWrapper.getInnerElement(), capabilityInstance); - if (createCapabilityRes.isRight()) { - errorWrapper.setInnerElement(createCapabilityRes.right().value()); - log.debug("Failed to create capability instance of capability {} of resource instance {}, status is {} ", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - } - log.debug("After creating capability instance of capability {} on graph, status is {}", capabilityId, errorWrapper.getInnerElement()); - return createCapabilityRes; - } - - private Either getCapabiityDefinition(String resourceInstanceId, String capabilityId, Wrapper errorWrapper, Wrapper overrideCapabilityDataWrapper, - Either, TitanOperationStatus> getCapabilityRes) { - Either getCapabilityDefinitionRes; - log.debug("Before getting capability definition {} for resource instance {}", capabilityId, resourceInstanceId); - CapabilityData overrideCapabilityData = getCapabilityRes.left().value().getLeft(); - overrideCapabilityDataWrapper.setInnerElement(overrideCapabilityData); - getCapabilityDefinitionRes = capabilityOperation.getCapabilityByCapabilityData(overrideCapabilityData); - if (getCapabilityDefinitionRes.isRight()) { - errorWrapper.setInnerElement(getCapabilityDefinitionRes.right().value()); - log.debug("Failed to retrieve capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - } - log.debug("After getting capability definition for {} for resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - return getCapabilityDefinitionRes; - } - - private Either getCapabiityDefinitionByVertex(String resourceInstanceId, String capabilityId, Wrapper errorWrapper, Wrapper overrideCapabilityDataWrapper, - Either, TitanOperationStatus> getCapabilityRes) { - Either getCapabilityDefinitionRes; - log.trace("Before getting capability definition {} for resource instance {}", capabilityId, resourceInstanceId); - - TitanVertex overrideCapabilityData = getCapabilityRes.left().value().getLeft(); - - overrideCapabilityDataWrapper.setInnerElement(overrideCapabilityData); - getCapabilityDefinitionRes = capabilityOperation.getCapabilityByCapabilityData(overrideCapabilityData); - if (getCapabilityDefinitionRes.isRight()) { - errorWrapper.setInnerElement(getCapabilityDefinitionRes.right().value()); - log.debug("Failed to retrieve capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - } - log.debug("After getting capability definition for {} for resource instance {} status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - return getCapabilityDefinitionRes; - } - - private Either, TitanOperationStatus> getCapabilitiesOfResourceInstance(String resourceInstanceId, String capabilityId, String capabilityName, Wrapper errorWrapper) { - Either, TitanOperationStatus> getCapabilityRes; - log.debug("Before getting capability {} for resource instance {}", capabilityId, resourceInstanceId); - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName); - getCapabilityRes = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class, props); - if (getCapabilityRes.isRight()) { - errorWrapper.setInnerElement(getCapabilityRes.right().value()); - log.debug("Failed to get capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - } - log.debug("After getting capability for {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - return getCapabilityRes; - } - - private Either, TitanOperationStatus> getCapabilitiesOfResourceInstance(TitanVertex instanceVertex, String resourceInstanceId, String capabilityId, String capabilityName, - Wrapper errorWrapper) { - Either, TitanOperationStatus> getCapabilityRes; - log.trace("Before getting capability {} {} {}", capabilityId, " for resource instance ", resourceInstanceId); - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName); - getCapabilityRes = titanGenericDao.getChildByEdgeCriteria(instanceVertex, GraphEdgeLabels.CALCULATED_CAPABILITY, props); - if (getCapabilityRes.isRight()) { - errorWrapper.setInnerElement(getCapabilityRes.right().value()); - log.debug("Failed to get capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - } - log.trace("After getting capability for {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - return getCapabilityRes; - } - - private void validateCapabilityInstanceExistence(String resourceInstanceId, String capabilityId, Wrapper errorWrapper) { - log.debug("Before validation of existence of capability instance of capability {} for resource instance {}", capabilityId, resourceInstanceId); - boolean capabilityInstOfCapabilityAlreadyExists; - Either validateCapabilityInstExistenceRes = validateCapabilityInstExistence(resourceInstanceId, capabilityId); - if (validateCapabilityInstExistenceRes.isRight()) { - errorWrapper.setInnerElement(validateCapabilityInstExistenceRes.right().value()); - log.debug("Failed to validate uniqueness of capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - } else { - capabilityInstOfCapabilityAlreadyExists = validateCapabilityInstExistenceRes.left().value(); - if (capabilityInstOfCapabilityAlreadyExists) { - errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST); - log.debug("Failed to create capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - } - } - log.debug("After validation of existence of capability instance of capability {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - } - - private void validateCapabilityInstanceExistence(TitanVertex resourceInstanceVertex, String resourceInstanceId, String capabilityId, Wrapper errorWrapper) { - log.trace("Before validation of existence of capability instance of capability {} for resource instance {}", capabilityId, resourceInstanceId); - boolean capabilityInstOfCapabilityAlreadyExists; - Either validateCapabilityInstExistenceRes = validateCapabilityInstExistence(resourceInstanceId, capabilityId); - if (validateCapabilityInstExistenceRes.isRight()) { - errorWrapper.setInnerElement(validateCapabilityInstExistenceRes.right().value()); - log.debug("Failed to validate uniqueness of capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - } else { - capabilityInstOfCapabilityAlreadyExists = validateCapabilityInstExistenceRes.left().value(); - if (capabilityInstOfCapabilityAlreadyExists) { - errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST); - log.debug("Failed to create capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - } - } - log.debug("After validation of existence of capability instance of capability {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); - } - - private Either, TitanOperationStatus> addPropertyValuesToCapabilityInstance(CapabilityInstData createdCapabilityInstance, List propertyValues, Map defaultProperties) { - TitanOperationStatus error = null; - List createdPropertyValues = new ArrayList<>(); - for (ComponentInstanceProperty property : propertyValues) { - log.debug("Before adding property value {} to capability instance {}", property.getName(), createdCapabilityInstance.getUniqueId()); - PropertyValueData propertyData = buildPropertyValueData(property.getName(), property.getType(), property.getValue(), createdCapabilityInstance.getUniqueId()); - Either addPropertyValueRes = addPropertyValueToCapabilityInstance(createdCapabilityInstance, propertyData, defaultProperties.get(property.getName())); - if (addPropertyValueRes.isRight()) { - error = addPropertyValueRes.right().value(); - log.debug("Failed to add property to capability instance {} of resource instance, status is {}", createdCapabilityInstance.getUniqueId(), error); - break; - } else { - createdPropertyValues.add(addPropertyValueRes.left().value()); - } - log.debug("After adding property value {} to capability instance {}. status is {}", property.getName(), createdCapabilityInstance.getUniqueId(), error); - } - if (error == null) { - return Either.left(createdPropertyValues); - } - return Either.right(error); - } - - private TitanOperationStatus addPropertyValuesToCapabilityInstance(TitanVertex createdCapabilityInstancevertex, List propertyValues, Map defaultProperties) { - TitanOperationStatus error = null; - String id = (String) titanGenericDao.getProperty(createdCapabilityInstancevertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - for (ComponentInstanceProperty property : propertyValues) { - log.trace("Before adding property value {} to capability instance {}", property.getName(), id); - PropertyValueData propertyData = buildPropertyValueData(property.getName(), property.getType(), property.getValue(), id); - TitanOperationStatus addPropertyValueRes = addPropertyValueToCapabilityInstance(createdCapabilityInstancevertex, propertyData, defaultProperties.get(property.getName()), id); - if (!addPropertyValueRes.equals(TitanOperationStatus.OK)) { - error = addPropertyValueRes; - log.debug("Failed to add property to capability instance {} of resource instance. status is {}", id, error); - break; - } - log.debug("After adding property value {} to capability instance {}. status is {}", property.getName(), id, error); - } - if (error == null) { - return TitanOperationStatus.OK; - } - return error; - } - - private PropertyValueData buildPropertyValueData(String propertyName, String propertyType, String propertyValue, String capabilityInstanceId) { - PropertyValueData propertyData = new PropertyValueData(); - String uniqueId = UniqueIdBuilder.buildPropertyValueUniqueId(capabilityInstanceId, propertyName); - Long creationTime = System.currentTimeMillis(); - propertyData.setUniqueId(uniqueId); - propertyData.setValue(propertyValue); - propertyData.setType(propertyType); - propertyData.setCreationTime(creationTime); - propertyData.setModificationTime(creationTime); - return propertyData; - } - - private Either addPropertyValueToCapabilityInstance(CapabilityInstData createdCapabilityInstance, PropertyValueData propertyValue, PropertyDefinition propertyDefinition) { - TitanOperationStatus error = null; - Map props = null; - Either createRelationRes; - PropertyValueData createdValue = null; - log.debug("Before creating property value node {} on graph", propertyValue.getUniqueId()); - Either createValueRes = titanGenericDao.createNode(propertyValue, PropertyValueData.class); - if (createValueRes.isRight()) { - error = createValueRes.right().value(); - log.debug("Failed to create property value for capability instance {} of resource instance. status is {}", createdCapabilityInstance.getUniqueId(), error); - } - log.debug("After creating property value node {} on graph. status is {}", propertyValue.getUniqueId(), error); - if (error == null) { - log.debug("Before creating relation from property value node {} to capability instance {}", propertyValue.getUniqueId(), createdCapabilityInstance.getUniqueId()); - createdValue = createValueRes.left().value(); - props = new HashMap<>(); - props.put(GraphPropertiesDictionary.PROPERTY_NAME.name(), propertyDefinition.getName()); - props.put(GraphPropertiesDictionary.PROPERTY_ID.name(), propertyDefinition.getUniqueId()); - createRelationRes = titanGenericDao.createRelation(createdCapabilityInstance, createdValue, GraphEdgeLabels.PROPERTY_VALUE, props); - if (createRelationRes.isRight()) { - error = createRelationRes.right().value(); - log.debug("Failed to create relation from capability instance {} to property value {}. status is {}", createdCapabilityInstance.getUniqueId(), createdValue.getUniqueId(), error); - } - log.debug("After creating relation from property value node {} to capability instance {}. status is {}", propertyValue.getUniqueId(), createdCapabilityInstance.getUniqueId(), error); - } - if (error == null) { - log.debug("Before creating relation from property value node {} to property {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId()); - createRelationRes = titanGenericDao.createRelation(propertyValue, new PropertyData(propertyDefinition, null), GraphEdgeLabels.PROPERTY_IMPL, props); - if (createRelationRes.isRight()) { - error = createRelationRes.right().value(); - log.debug("Failed to create relation from property value {} to property {}. status is {}", createdValue.getUniqueId(), propertyDefinition.getUniqueId(), error); - } - log.debug("After creating relation from property value node {} to property {}. status is {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId(), error); - } - if (error == null) { - return Either.left(createdValue); - } - return Either.right(error); - } - - private TitanOperationStatus addPropertyValueToCapabilityInstance(TitanVertex createdCapabilityInstanceVertex, PropertyValueData propertyValue, PropertyDefinition propertyDefinition, String id) { - TitanOperationStatus error = null; - Map props = null; - TitanOperationStatus createRelationRes; - log.trace("Before creating property value node {} on graph.", propertyValue.getUniqueId()); - Either createValueRes = titanGenericDao.createNode(propertyValue); - if (createValueRes.isRight()) { - error = createValueRes.right().value(); - log.debug("Failed to create property value for capability instance {} of resource instance. status is {}", id, error); - } - log.trace("After creating property value node {} on graph status is {}", propertyValue.getUniqueId(), error); - TitanVertex createdPropVertex = null; - String createdId = null; - if (error == null) { - log.trace("Before creating relation from property value node {} to capability instance {} ", propertyValue.getUniqueId() , id); - props = new HashMap<>(); - props.put(GraphPropertiesDictionary.PROPERTY_NAME.name(), propertyDefinition.getName()); - props.put(GraphPropertiesDictionary.PROPERTY_ID.name(), propertyDefinition.getUniqueId()); - createdPropVertex = createValueRes.left().value(); - createRelationRes = titanGenericDao.createEdge(createdCapabilityInstanceVertex, createdPropVertex, GraphEdgeLabels.PROPERTY_VALUE, props); - if (!createRelationRes.equals(TitanOperationStatus.OK)) { - error = createRelationRes; - createdId = (String) titanGenericDao.getProperty(createdPropVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - log.debug("Failed to create relation from capability instance {} to property value {}. status is {}", id, createdId, error); - } - log.trace("After creating relation from property value node {} to capability instance {}. status is {}", propertyValue.getUniqueId(), id, error); - } - if (error == null) { - log.trace("Before creating relation from property value node {} to property {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId()); - createRelationRes = titanGenericDao.createEdge(createdPropVertex, new PropertyData(propertyDefinition, null), GraphEdgeLabels.PROPERTY_IMPL, props); - if (!createRelationRes.equals(TitanOperationStatus.OK)) { - error = createRelationRes; - log.debug("Failed to create relation from property value {} to property {}. status is {}", createdId, propertyDefinition.getUniqueId(), error); - } - log.debug("After creating relation from property value node {} to property {}. status is {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId(), error); - } - if (error == null) { - return TitanOperationStatus.OK; - } - return error; - } - - private Either validateCapabilityInstanceProperties(Map defaultProperties, List propertyValues) { - Either result = Either.left(true); - for (ComponentInstanceProperty property : propertyValues) { - result = validateUpdateCapabilityInstancePropertyValue(property, defaultProperties); - if (result.isRight()) { - break; - } - } - return result; - } - - private Either validateUpdateCapabilityInstancePropertyValue(ComponentInstanceProperty property, Map defaultProperties) { - PropertyDefinition defaultProperty; - String propertyName = property.getName(); - Either result = null; - if (defaultProperties.containsKey(propertyName)) { - defaultProperty = defaultProperties.get(propertyName); - String propertyType = property.getType() == null || property.getType().isEmpty() ? defaultProperty.getType() : property.getType(); - - String innerType = null; - if (property.getSchema() != null && property.getSchema().getProperty() != null) - innerType = property.getSchema().getProperty().getType(); - if (innerType == null && defaultProperty.getSchema() != null && defaultProperty.getSchema().getProperty() != null) - innerType = defaultProperty.getSchema().getProperty().getType(); - - if (defaultProperty.getType().equals(propertyType)) { - String propertyValue = property.getValue(); - Either, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - log.debug("Failed to update property value. status is {}", status); - result = Either.right(status); - } - if (result == null) { - Either updatedPropertyValueRes = propertyOperation.validateAndUpdatePropertyValue(propertyType, propertyValue, innerType, allDataTypes.left().value()); - if (updatedPropertyValueRes.isLeft()) { - if (updatedPropertyValueRes.left().value() != null) - property.setDefaultValue(updatedPropertyValueRes.left().value().toString()); - result = Either.left(true); - } else { - result = Either.right(TitanOperationStatus.INVALID_PROPERTY); - } - } - log.debug("The property with name {} has invalid type {} or invalid value {}.", propertyName, propertyType, propertyValue); - - } else { - result = Either.right(TitanOperationStatus.PROPERTY_NAME_ALREADY_EXISTS); - log.debug("The property with name {} and different type already exists.", propertyName); - } - } else { - result = Either.right(TitanOperationStatus.NOT_FOUND); - log.debug("Failed to find property with name {}.", propertyName); - } - return result; - } - - /** - * validate capability instance uniqueness - * - * @param resourceInstanceId - * @param capabilityId - * @return - */ - @Override - public Either validateCapabilityInstExistence(String resourceInstanceId, String capabilityId) { - Either result = null; - TitanOperationStatus error; - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capabilityId); - Either getCapabilityInstanceEdgeRes = titanGenericDao.getOutgoingEdgeByCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, GraphEdgeLabels.CAPABILITY_INST, props); - if (getCapabilityInstanceEdgeRes.isRight()) { - error = getCapabilityInstanceEdgeRes.right().value(); - if (error.equals(TitanOperationStatus.NOT_FOUND)) { - result = Either.left(false); - } else { - log.debug("Failed to get outgoing edge for resource instance {}. status is {}.", resourceInstanceId, error); - result = Either.right(error); - } - } - if (result == null) { - result = Either.left(true); - } - return result; - } - - @Override - public Either validateCapabilityInstExistence(TitanVertex instanceVertex, String resourceInstanceId, String capabilityId) { - Either result = null; - TitanOperationStatus error; - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capabilityId); - Either getCapabilityInstanceEdgeRes = titanGenericDao.getOutgoingEdgeByCriteria(instanceVertex, GraphEdgeLabels.CAPABILITY_INST, props); - if (getCapabilityInstanceEdgeRes.isRight()) { - error = getCapabilityInstanceEdgeRes.right().value(); - if (error.equals(TitanOperationStatus.NOT_FOUND)) { - result = Either.left(false); - } else { - log.debug("Failed to get outgoing edge for resource instance {} status is {}", resourceInstanceId, error); - result = Either.right(error); - } - } - if (result == null) { - result = Either.left(true); - } - return result; - } - - private Either createCapabilityInstanceOnGraph(String resourceInstanceId, CapabilityData overrideCapabilityData, CapabilityInstData capabilityInstance) { - log.debug("Before creation of capability instance of capability {} for resource instance {}", overrideCapabilityData.getUniqueId(), resourceInstanceId); - - Either createRelationRes; - CapabilityInstData createdCapabilityInstance = null; - String capabilityInstanceId = null; - TitanOperationStatus error = null; - Either createCapabilityInstanceRes = titanGenericDao.createNode(capabilityInstance, CapabilityInstData.class); - if (createCapabilityInstanceRes.isRight()) { - error = createCapabilityInstanceRes.right().value(); - log.debug("Failed to create capability instance of capability {} for resource instance {}. status is {}.", overrideCapabilityData.getUniqueId(), resourceInstanceId, error); - } - log.debug("After creation of capability instance of capability {} for resource instance {}. status is {}.", overrideCapabilityData.getUniqueId(), resourceInstanceId, error); - if (error == null) { - createdCapabilityInstance = createCapabilityInstanceRes.left().value(); - capabilityInstanceId = createdCapabilityInstance.getUniqueId(); - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), overrideCapabilityData.getUniqueId()); - UniqueIdData resourceInstanceIdData = new UniqueIdData(NodeTypeEnum.ResourceInstance, resourceInstanceId); - log.debug("Before associating resource instance {} to capability instance.", resourceInstanceId); - createRelationRes = titanGenericDao.createRelation(resourceInstanceIdData, capabilityInstance, GraphEdgeLabels.CAPABILITY_INST, props); - if (createRelationRes.isRight()) { - error = createRelationRes.right().value(); - log.debug("Failed to assotiate resource instance {} to capability instance {}. status is {}", resourceInstanceId, capabilityInstanceId, error); - } - log.debug("After associating resource instance {} to capability instance {}. status is {}", resourceInstanceId, capabilityInstanceId, error); - } - if (error == null) { - log.debug("Before associating capability instance {} to capability {}.", capabilityInstanceId, overrideCapabilityData.getUniqueId()); - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), overrideCapabilityData.getUniqueId()); - createRelationRes = titanGenericDao.createRelation(createdCapabilityInstance, overrideCapabilityData, GraphEdgeLabels.INSTANCE_OF, props); - if (createRelationRes.isRight()) { - error = createRelationRes.right().value(); - log.debug("Failed to associate capability instance {} to capability {}. status is {}", capabilityInstanceId, overrideCapabilityData.getUniqueId(), error); - } - log.debug("After associating capability instance {} to capability {}. status is {}.", capabilityInstanceId, overrideCapabilityData.getUniqueId(), error); - } - if (error == null) { - return createCapabilityInstanceRes; - } - return Either.right(error); - } - - private Either createCapabilityInstanceOnGraph(TitanVertex riVertex, String resourceInstanceId, TitanVertex overrideCapabilityDataVertex, CapabilityInstData capabilityInstance) { - String overrideCapabilityDataId = (String) titanGenericDao.getProperty(overrideCapabilityDataVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - log.trace("Before creation of capability instance of capability {} for resource instance {}", overrideCapabilityDataVertex, resourceInstanceId); - - TitanOperationStatus createRelationRes; - TitanVertex createdCapabilityInstance = null; - String capabilityInstanceId = null; - TitanOperationStatus error = null; - Either createCapabilityInstanceRes = titanGenericDao.createNode(capabilityInstance); - if (createCapabilityInstanceRes.isRight()) { - error = createCapabilityInstanceRes.right().value(); - log.debug("Failed to create capability instance of capability {} for resource instance {} status is {}", overrideCapabilityDataId, resourceInstanceId, error); - } - log.trace("After creation of capability instance of capability {} for resource instance {} status is {}", overrideCapabilityDataId, resourceInstanceId, error); - if (error == null) { - createdCapabilityInstance = createCapabilityInstanceRes.left().value(); - capabilityInstanceId = (String) titanGenericDao.getProperty(createdCapabilityInstance, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), overrideCapabilityDataId); - log.debug("Before associating resource instance {} to capability instance.", resourceInstanceId); - - createRelationRes = titanGenericDao.createEdge(riVertex, capabilityInstance, GraphEdgeLabels.CAPABILITY_INST, props); - if (!createRelationRes.equals(TitanOperationStatus.OK)) { - error = createRelationRes; - log.debug("Failed to assotiate resource instance {} to capability instance {} status is {}", resourceInstanceId, capabilityInstanceId, error); - } - if (log.isTraceEnabled()) { - log.trace("After associating resource instance {} to capability instance {}. status is {}", resourceInstanceId, capabilityInstanceId, error); - } - } - if (error == null) { - log.trace("Before associating capability instance {} to capability {}", capabilityInstanceId, overrideCapabilityDataId); - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), overrideCapabilityDataId); - createRelationRes = titanGenericDao.createEdge(createdCapabilityInstance, overrideCapabilityDataVertex, GraphEdgeLabels.INSTANCE_OF, props); - if (!createRelationRes.equals(TitanOperationStatus.OK)) { - error = createRelationRes; - log.debug("Failed to associate capability instance {} to capability {} status is {}", capabilityInstanceId, overrideCapabilityDataId, error); - } - log.debug("After associating capability instance {} to capability {}. status is {}", capabilityInstanceId, overrideCapabilityDataId, error); - } - if (error == null) { - return createCapabilityInstanceRes; - } - return Either.right(error); - } - - private CapabilityInstData buildCapabilityInstanceData(String resourceInstanceId, CapabilityDefinition capability) { - CapabilityInstData capabilityInstance = new CapabilityInstData(); - Long creationTime = System.currentTimeMillis(); - String uniqueId = UniqueIdBuilder.buildCapabilityInstanceUid(resourceInstanceId, capability.getName()); - - capabilityInstance.setCreationTime(creationTime); - capabilityInstance.setModificationTime(creationTime); - capabilityInstance.setUniqueId(uniqueId); - - return capabilityInstance; - } - - /** - * delete capability instance from resource instance - * - * @param resourceInstanceId - * @param capabilityInstanceId - * @return - */ - @Override - public Either deleteCapabilityInstanceFromResourceInstance(String resourceInstanceId, String capabilityInstanceId) { - log.debug("Before deleting of capability instance {} from resource instance {}.", capabilityInstanceId, resourceInstanceId); - - Either deleteCapabilityInstRes = null; - TitanOperationStatus error = null; - Either deleteProperyValuesRes = deleteAllPropertyValuesOfCapabilityInstance(resourceInstanceId, capabilityInstanceId); - if (deleteProperyValuesRes.isRight()) { - error = deleteProperyValuesRes.right().value(); - log.debug("Failed to delete property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); - } - if (error == null) { - deleteCapabilityInstRes = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstanceId, CapabilityInstData.class); - if (deleteCapabilityInstRes.isRight()) { - error = deleteCapabilityInstRes.right().value(); - log.debug("Failed to delete capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); - } - } - log.debug("After deleting of capability instance {} from resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); - if (error == null) { - return Either.left(deleteCapabilityInstRes.left().value()); - } - return Either.right(error); - } - - private Either deleteAllPropertyValuesOfCapabilityInstance(String resourceInstanceId, String capabilityInstanceId) { - log.debug("Before deleting all property values of capability instance {} from resource instance {}", capabilityInstanceId, resourceInstanceId); - TitanOperationStatus error = null; - List> deletePropertiesPairs; - Either>, TitanOperationStatus> getPropertyValuesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstanceId, - GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class); - if (getPropertyValuesRes.isRight()) { - error = getPropertyValuesRes.right().value(); - log.debug("Failed to retrieve property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); - } - if (error == null) { - deletePropertiesPairs = getPropertyValuesRes.left().value(); - for (ImmutablePair propertyPair : deletePropertiesPairs) { - Either deletePropertyRes = titanGenericDao.deleteNode(propertyPair.getLeft(), PropertyValueData.class); - if (deletePropertyRes.isRight()) { - error = deletePropertyRes.right().value(); - log.debug("Failed to delete property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); - break; - } - } - } - log.debug("After deleting all property values of capability instance from resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); - if (error == null) { - return Either.left(true); - } - return Either.right(error); - } - - /** - * get all capability instances for resource instance returns all Capability Instances related to Resource Instance as List or TitanOperationStatus if error occurs or if Resource Instance have no any related Capability - * Instance - * - * @param resourceInstanceId - * @return Either, TitanOperationStatus> - */ - @Override - public Either>, TitanOperationStatus> getAllCapabilityInstancesOfResourceInstance(String resourceInstanceId) { - log.debug("Before deleting all capability instances of resource instance {}", resourceInstanceId); - TitanOperationStatus error = null; - Either>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, - GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class); - if (getCapabilityInstancesRes.isRight()) { - error = getCapabilityInstancesRes.right().value(); - log.debug("Failed to retrieve capability Instances of resource instance {}. status is {}", resourceInstanceId, error); - } - log.debug("After deleting all capability instances of resource instance {}. status is {}", resourceInstanceId, error); - if (error == null) { - return getCapabilityInstancesRes; - } - return Either.right(error); - } - - /** - * get capability instance of capability for resource instance - * - * @param resourceInstanceId - * @param capabilityId - * @return - */ - @Override - public Either getCapabilityInstanceOfCapabilityOfResourceInstance(String resourceInstanceId, String capabilityId) { - TitanOperationStatus error = null; - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capabilityId); - Either, TitanOperationStatus> getCapabilityInstanceRes = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, - GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class, props); - if (getCapabilityInstanceRes.isRight()) { - error = getCapabilityInstanceRes.right().value(); - log.debug("Failed to retrieve capability Instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error); - } - if (error == null) { - return Either.left(getCapabilityInstanceRes.left().value().getLeft()); - } - return Either.right(error); - } - - /** - * update capability property values - * - * @param resourceInstanceId - * @param propertyValues - * @param capabilityId - * @return - */ - @Override - public Either, TitanOperationStatus> updateCapabilityPropertyValues(String resourceInstanceId, String capabilityId, List propertyValues) { - log.debug("Before updating property values of capability {} of resource instance {}.", capabilityId, resourceInstanceId); - TitanOperationStatus error = null; - Map props = new HashMap<>(); - CapabilityInstData capabilityInstance = null; - String capabilityInstanceId = null; - Either deleteProperyValuesRes; - - CapabilityData overrideCapabilityData; - CapabilityDefinition overrideCapabilityDefinition; - Map defaultProperties = null; - Either, TitanOperationStatus> getCapabilityDataRes = null; - Either, TitanOperationStatus> addPropertyValuesRes = null; - Either getCapabilityDefinitionRes = null; - - log.debug("Before getting all capability instances of resource instance {}.", resourceInstanceId); - props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capabilityId); - Either, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, - GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class, props); - if (getCapabilityInstancesRes.isRight()) { - error = getCapabilityInstancesRes.right().value(); - log.debug("Failed to retrieve capability Instances of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error); - } - log.debug("After getting all capability instances of resource instance {}. status is {}.", resourceInstanceId, error); - if (error == null) { - log.debug("Before deleting all capability instances of resource instance {}.", resourceInstanceId); - capabilityInstance = getCapabilityInstancesRes.left().value().getLeft(); - capabilityInstanceId = capabilityInstance.getUniqueId(); - deleteProperyValuesRes = deleteAllPropertyValuesOfCapabilityInstance(resourceInstanceId, capabilityInstanceId); - if (deleteProperyValuesRes.isRight()) { - error = deleteProperyValuesRes.right().value(); - log.debug("Failed to delete property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); - } - log.debug("After deleting all capability instances of resource instance {}. status is {}", resourceInstanceId, error); - } - if (error == null) { - log.debug("Before getting capability {} of resource instance {}", capabilityId, resourceInstanceId); - getCapabilityDataRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class); - if (getCapabilityDataRes.isRight()) { - error = getCapabilityDataRes.right().value(); - log.debug("Failed to get capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error); - } - log.debug("After getting capability {} of resource instance {}. status is {}.", capabilityId, resourceInstanceId, error); - } - if (error == null) { - log.debug("Before getting capability definition for capability {} of resource instance {}.", capabilityId, resourceInstanceId); - overrideCapabilityData = getCapabilityDataRes.left().value().getLeft(); - getCapabilityDefinitionRes = capabilityOperation.getCapabilityByCapabilityData(overrideCapabilityData); - if (getCapabilityDefinitionRes.isRight()) { - error = getCapabilityDefinitionRes.right().value(); - log.debug("Failed to retrieve capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error); - } - log.debug("After getting capability definition for capability {} of resource instance {}. status is {}.", capabilityId, resourceInstanceId, error); - } - if (error == null) { - log.debug("Before validating capability properties of capability instance {} of resource instance {}.", capabilityInstanceId, resourceInstanceId); - overrideCapabilityDefinition = getCapabilityDefinitionRes.left().value(); - if (overrideCapabilityDefinition.getProperties() != null) { - defaultProperties = overrideCapabilityDefinition.getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); - } - Either result = validateCapabilityInstanceProperties(defaultProperties, propertyValues); - if (result.isRight()) { - error = result.right().value(); - log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}", capabilityInstance.getUniqueId(), resourceInstanceId, error); - } - log.debug("After validating capability properties of capability instance {} of resource instance {}. status is {}.", capabilityInstanceId, resourceInstanceId, error); - } - if (error == null) { - log.debug("Before adding property values to capability instance {} of resource instance {}.", capabilityInstanceId, resourceInstanceId); - addPropertyValuesRes = addPropertyValuesToCapabilityInstance(capabilityInstance, propertyValues, defaultProperties); - if (addPropertyValuesRes.isRight()) { - error = addPropertyValuesRes.right().value(); - log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}", capabilityInstance.getUniqueId(), resourceInstanceId, error); - } - log.debug("Before adding property values to capability instance {} of resource instance {}.", capabilityInstanceId, resourceInstanceId); - } - log.debug("After updating property values of capability {} of resource instance {}. status is {}.", capabilityId, resourceInstanceId, error); - if (error == null) { - return addPropertyValuesRes; - } - return Either.right(error); - } - - /** - * clone and associate capability instance with property values - * - * @param createdComponentInstance - * @param capability - * @param capabilityInstPair - * @return - */ - @Override - public Either>, TitanOperationStatus> cloneAssociateCapabilityInstanceWithPropertyValues(ComponentInstanceData createdComponentInstance, CapabilityDefinition capability, - ImmutablePair capabilityInstPair) { - - TitanOperationStatus error = null; - String componentInstanceId = createdComponentInstance.getUniqueId(); - String capabilityInstanceId = capabilityInstPair.getLeft().getUniqueId(); - - log.debug("Before cloning capability instance with property values of capability instance {} of resource instance {}.", capabilityInstanceId, componentInstanceId); - List> propertyValuePairs; - List newPropertyValues = new ArrayList<>(); - CapabilityInstData cloneCapabilityInstance = null; - Either cloneCapabilityInstanceNodeRes = null; - - log.debug("Before getting all property values of component instance {} of resource instance {}.", capabilityInstanceId, componentInstanceId); - Either>, TitanOperationStatus> getPropertyValuesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstPair.getLeft().getUniqueId(), - GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class); - if (getPropertyValuesRes.isRight()) { - error = getPropertyValuesRes.right().value(); - log.debug("Failed to retrieve property values of capability instance {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), componentInstanceId, error); - } - log.debug("After getting all property values of component instance {} of resource instance {}. status is {}.", capabilityInstanceId, componentInstanceId, error); - if (error == null) { - CapabilityInstData cloneCapabilityInst = buildCapabilityInstanceData(componentInstanceId, capability); - log.debug("Before creating capability instance node {} on graph.", cloneCapabilityInst.getUniqueId()); - cloneCapabilityInstanceNodeRes = titanGenericDao.createNode(cloneCapabilityInst, CapabilityInstData.class); - if (cloneCapabilityInstanceNodeRes.isRight()) { - error = cloneCapabilityInstanceNodeRes.right().value(); - log.debug("Failed to create capability instance of capability {} of component instance {}. status is {}", capability.getUniqueId(), componentInstanceId, error); - } - log.debug("After creating capability instance node {} on graph. status is {}.", cloneCapabilityInst.getUniqueId(), error); - } - - if (error == null) { - log.debug("Before creating relation from capability instance {} to capability {} on graph.", cloneCapabilityInstanceNodeRes.left().value().getUniqueId(), capability.getUniqueId()); - cloneCapabilityInstance = cloneCapabilityInstanceNodeRes.left().value(); - CapabilityData capabilityData = buildCapabilityData(capability); - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capabilityData.getUniqueId()); - Either createRelationRes = titanGenericDao.createRelation(cloneCapabilityInstance, capabilityData, GraphEdgeLabels.INSTANCE_OF, props); - if (createRelationRes.isRight()) { - error = createRelationRes.right().value(); - log.debug("Failed to associate capability instance {} to capability {}. status is {}", cloneCapabilityInstance.getUniqueId(), capability.getUniqueId(), error); - } - log.debug("After creating relation from capability instance {} to capability {} on graph. status is.", cloneCapabilityInstanceNodeRes.left().value().getUniqueId(), capability.getUniqueId(), error); - } - - if (error == null) { - log.debug("Before cloning property values of component instance {}.", capabilityInstanceId); - propertyValuePairs = getPropertyValuesRes.left().value(); - for (ImmutablePair propertyValuePair : propertyValuePairs) { - Either clonePropertyValueRes = cloneAssociatePropertyValue(cloneCapabilityInstance, propertyValuePair); - if (clonePropertyValueRes.isRight()) { - error = clonePropertyValueRes.right().value(); - log.debug("Failed to clone property value {} of capability {} of component instance {}. status is {}", propertyValuePair.getLeft().getUniqueId(), capability.getUniqueId(), componentInstanceId, error); - break; - } else { - newPropertyValues.add(clonePropertyValueRes.left().value()); - } - } - log.debug("After cloning property values of component instance {}. status is {}.", capabilityInstanceId, error); - } - log.debug("After cloning capability instance with property values of capability instance {} of resource instance {}. status is {}.", capabilityInstanceId, componentInstanceId, error); - if (error == null) { - return Either.left(new ImmutablePair>(cloneCapabilityInstance, newPropertyValues)); - } - return Either.right(error); - } - - public Either cloneAssociateCapabilityInstanceWithPropertyValues(TitanVertex componentInstanceVertex, CapabilityDefinition capability, ImmutablePair capabilityInstPair) { - - TitanOperationStatus error = null; - String componentInstanceId = (String) titanGenericDao.getProperty(componentInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - String capabilityInstanceId = capabilityInstPair.getLeft().getUniqueId(); - - if (log.isTraceEnabled()) { - log.trace("Before cloning capability instance with property values of capability instance {} of resource instance {}", capabilityInstanceId, componentInstanceId); - } - List> propertyValuePairs; - Either cloneCapabilityInstanceNodeRes = null; - - if (log.isTraceEnabled()) { - log.trace("Before getting all property values of component instance {} of resource instance {}", capabilityInstanceId, componentInstanceId); - } - Either>, TitanOperationStatus> getPropertyValuesRes = titanGenericDao.getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstPair.getLeft().getUniqueId(), - GraphEdgeLabels.PROPERTY_VALUE); - if (getPropertyValuesRes.isRight()) { - error = getPropertyValuesRes.right().value(); - log.debug("Failed to retrieve property values of capability instance {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), componentInstanceId, error); - } - if (log.isTraceEnabled()) { - log.trace("After getting all property values of component instance {} of resource instance {}. status is {}", capabilityInstanceId, componentInstanceId, error); - } - if (error == null) { - CapabilityInstData cloneCapabilityInst = buildCapabilityInstanceData(componentInstanceId, capability); - log.trace("Before creating capability instance node {} on graph", cloneCapabilityInst.getUniqueId()); - cloneCapabilityInstanceNodeRes = titanGenericDao.createNode(cloneCapabilityInst); - if (cloneCapabilityInstanceNodeRes.isRight()) { - error = cloneCapabilityInstanceNodeRes.right().value(); - log.debug("Failed to create capability instance of capability {} of component instance {}. status is {}", capability.getUniqueId(), componentInstanceId, error); - } - if (log.isTraceEnabled()) { - log.trace("After creating capability instance node {} on graph. status is {}", cloneCapabilityInst.getUniqueId(), error); - } - } - CapabilityData capabilityData; - TitanVertex cloneCapabilityInstance = null; - if (error == null) { - if (log.isTraceEnabled()) { - log.trace("Before creating relation from capability instance {} to capability {} on graph", capability.getUniqueId(), capability.getUniqueId()); - } - capabilityData = buildCapabilityData(capability); - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capabilityData.getUniqueId()); - cloneCapabilityInstance = cloneCapabilityInstanceNodeRes.left().value(); - TitanOperationStatus createRelationRes = titanGenericDao.createEdge(cloneCapabilityInstance, capabilityData, GraphEdgeLabels.INSTANCE_OF, props); - if (!createRelationRes.equals(TitanOperationStatus.OK)) { - error = createRelationRes; - log.debug("Failed to associate capability instance {} to capability {}. status is {}", capabilityData.getUniqueId(), capability.getUniqueId(), createRelationRes); - } - log.trace("After creating relation from capability instance {} to capability {} on graph. status is {}", capabilityData.getUniqueId(), capability.getUniqueId(), error); - } - - if (error == null) { - log.trace("Before cloning property values of component instance {} ", capabilityInstanceId); - propertyValuePairs = getPropertyValuesRes.left().value(); - for (ImmutablePair propertyValuePair : propertyValuePairs) { - TitanOperationStatus clonePropertyValueRes = cloneAssociatePropertyValue(cloneCapabilityInstance, propertyValuePair); - if (!clonePropertyValueRes.equals(TitanOperationStatus.OK)) { - error = clonePropertyValueRes; - log.debug("Failed to clone property value of capability {} of component instance {}. status is {}", capability.getUniqueId(), componentInstanceId, error); - break; - } - } - log.debug("After cloning property values of component instance {}. status is {}", capabilityInstanceId, error); - } - log.debug("After cloning capability instance with property values of capability instance {} of resource instance {}. status is {}.", capabilityInstanceId, componentInstanceId, error); - if (error == null) { - return Either.left(cloneCapabilityInstance); - } - return Either.right(error); - } - - private CapabilityData buildCapabilityData(CapabilityDefinition capability) { - CapabilityData capabilityData = new CapabilityData(); - capabilityData.setUniqueId(capability.getUniqueId()); - capabilityData.setDescription(capability.getDescription()); - capabilityData.setType(capability.getType()); - capabilityData.setMaxOccurrences(capability.getMaxOccurrences()); - capabilityData.setMinOccurrences(capability.getMinOccurrences()); - List validSourceTypes = capability.getValidSourceTypes(); - if (validSourceTypes != null) { - capabilityData.setValidSourceTypes(validSourceTypes); - } - return capabilityData; - } - - private Either cloneAssociatePropertyValue(CapabilityInstData cloneCapabilityInstance, ImmutablePair propertyValuePair) { - TitanOperationStatus error = null; - String propertyValueID = propertyValuePair.getLeft().getUniqueId(); - String capabilityInstanceId = cloneCapabilityInstance.getUniqueId(); - log.debug("Before cloning property values {} of component instance {}.", propertyValueID, capabilityInstanceId); - - Map props = propertyValuePair.getRight().getProperties(); - PropertyData propertyData = new PropertyData(); - String propertyId = (String) props.get(GraphPropertiesDictionary.PROPERTY_ID.name()); - propertyData.getPropertyDataDefinition().setUniqueId(propertyId); - - PropertyValueData propertyValue = buildPropertyValueData((String) props.get(GraphPropertiesDictionary.PROPERTY_NAME.name()), propertyValuePair.getLeft().getType(), propertyValuePair.getLeft().getValue(), capabilityInstanceId); - PropertyValueData createdValue = null; - Either createRelationRes; - - log.debug("Before creating property values node {} on graph.", propertyValue.getUniqueId()); - Either createValueRes = titanGenericDao.createNode(propertyValue, PropertyValueData.class); - if (createValueRes.isRight()) { - error = createValueRes.right().value(); - log.debug("Failed to create property value for capability instance {} of resource instance. status is {}.", cloneCapabilityInstance.getUniqueId(), error); - } - log.debug("After creating property values node {} on graph. status is {}.", propertyValue.getUniqueId(), error); - if (error == null) { - createdValue = createValueRes.left().value(); - log.debug("Before creating relation from capability instance {} to property value {}.", capabilityInstanceId, createdValue.getUniqueId()); - createRelationRes = titanGenericDao.createRelation(cloneCapabilityInstance, createdValue, GraphEdgeLabels.PROPERTY_VALUE, props); - if (createRelationRes.isRight()) { - error = createRelationRes.right().value(); - log.debug("Failed to create relation from capability instance {} to property value {}. status is {}.", cloneCapabilityInstance.getUniqueId(), createdValue.getUniqueId(), error); - } - log.debug("After creating relation from capability instance {} to property value {}. status is {}.", capabilityInstanceId, createdValue.getUniqueId(), error); - } - if (error == null) { - log.debug("Before creating relation from property value {} to property {}.", createdValue, propertyData.getUniqueId()); - createRelationRes = titanGenericDao.createRelation(createdValue, propertyData, GraphEdgeLabels.PROPERTY_IMPL, props); - if (createRelationRes.isRight()) { - error = createRelationRes.right().value(); - log.debug("Failed to create relation from property value {} to property {}. status is {}.", createdValue.getUniqueId(), propertyId, error); - } - log.debug("Before creating relation from property value {} to property {}. status is {}.", createdValue, propertyData.getUniqueId(), error); - } - log.debug("After cloning property values {} of component instance {}. status is {}.", propertyValueID, capabilityInstanceId, error); - if (error == null) { - return Either.left(createdValue); - } - return Either.right(error); - } - - private TitanOperationStatus cloneAssociatePropertyValue(TitanVertex capabilityInstanceVertex, ImmutablePair propertyValuePair) { - TitanOperationStatus error = null; - TitanVertex propertyVertex = propertyValuePair.getLeft(); - String propertyValueID = (String) titanGenericDao.getProperty(propertyVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - String capabilityInstanceId = (String) titanGenericDao.getProperty(capabilityInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - if (log.isTraceEnabled()) { - log.trace("Before cloning property values {} of component instance {}", propertyValueID, capabilityInstanceId); - } - - Map props = titanGenericDao.getProperties(propertyValuePair.getRight()); - PropertyData propertyData = new PropertyData(); - String propertyId = (String) props.get(GraphPropertiesDictionary.PROPERTY_ID.name()); - propertyData.getPropertyDataDefinition().setUniqueId(propertyId); - - String propertyType = (String) titanGenericDao.getProperty(propertyVertex, GraphPropertiesDictionary.TYPE.getProperty()); - String propertyValueStr = (String) titanGenericDao.getProperty(propertyVertex, GraphPropertiesDictionary.VALUE.getProperty()); - - PropertyValueData propertyValue = buildPropertyValueData((String) props.get(GraphPropertiesDictionary.PROPERTY_NAME.name()), propertyType, propertyValueStr, capabilityInstanceId); - TitanVertex createdValue = null; - TitanOperationStatus createRelationRes; - - log.trace("Before creating property values node {} on graph.", propertyValue.getUniqueId()); - Either createValueRes = titanGenericDao.createNode(propertyValue); - String capabiltyInstId = (String) titanGenericDao.getProperty(capabilityInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - if (createValueRes.isRight()) { - error = createValueRes.right().value(); - log.debug("Failed to create property value for capability instance {} of resource instance. status is {}", capabiltyInstId, error); - } - if (log.isTraceEnabled()) { - log.trace("After creating property values node {} on graph. status is {} ", propertyValue.getUniqueId(), error); - } - if (error == null) { - createdValue = createValueRes.left().value(); - log.trace("Before creating relation from capability instance {} to property value {}", capabilityInstanceId, propertyValue.getUniqueId()); - createRelationRes = titanGenericDao.createEdge(capabilityInstanceVertex, createdValue, GraphEdgeLabels.PROPERTY_VALUE, props); - if (!createRelationRes.equals(TitanOperationStatus.OK)) { - error = createRelationRes; - log.debug("Failed to create relation from capability instance {} to property value {}. status is {}", capabiltyInstId, propertyValue.getUniqueId(), error); - } - if (log.isTraceEnabled()) { - log.trace("After creating relation from capability instance {} to property value {}. status is {} ", capabilityInstanceId, propertyValue.getUniqueId(), error); - } - } - if (error == null) { - log.trace("Before creating relation from property value {} to property {} ", createdValue, propertyData.getUniqueId()); - createRelationRes = titanGenericDao.createEdge(createdValue, propertyData, GraphEdgeLabels.PROPERTY_IMPL, props); - if (!createRelationRes.equals(TitanOperationStatus.OK)) { - error = createRelationRes; - log.debug("Failed to create relation from property value {} to property {}. status is {}", propertyValue.getUniqueId(), propertyId, error); - } - if (log.isTraceEnabled()) { - log.trace("Before creating relation from property value {} to property {}. status is {}", createdValue, propertyData.getUniqueId(), error); - } - } - log.trace("After cloning property values {} of component instance {}. status is {}", propertyValueID, capabilityInstanceId, error); - if (error == null) { - return TitanOperationStatus.OK; - } - return error; - } -} 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 ad43c60b0f..a4be274781 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 @@ -89,934 +89,8 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit this.titanGenericDao = titanGenericDao; } - @Override - public Either addCapability(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition, boolean inTransaction) { - - Either result = null; - - try { - - Either addCapStatus = addCapabilityToResource(resourceId, capabilityName, capabilityDefinition); - - if (addCapStatus.isRight()) { - log.debug("Failed to add capability {} [{}] to Graph", capabilityName, capabilityDefinition); - BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add Capability", capabilityName, String.valueOf(addCapStatus.right().value())); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addCapStatus.right().value())); - return result; - } else { - CapabilityData capabilityData = addCapStatus.left().value(); - - String capabilityUid = capabilityData.getUniqueId(); - Either capabilityRes = getCapability(capabilityUid, true); - log.debug("After fetching capability {} with uid {}. status is {}" ,capabilityName, capabilityUid,capabilityRes); - - if (capabilityRes.isRight()) { - StorageOperationStatus status = capabilityRes.right().value(); - log.debug("Failed to fetch capability {} with uid {}. status is {}", capabilityName, capabilityUid, status); - result = Either.right(status); - return result; - } - - CapabilityDefinition value = capabilityRes.left().value(); - log.debug("The returned CapabilityDefinition is {}", value); - result = Either.left(value); - - return result; - } - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - @Override - public StorageOperationStatus addCapability(TitanVertex metadataVertex, String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition, boolean inTransaction) { - - StorageOperationStatus result = StorageOperationStatus.OK; - try { - - TitanOperationStatus addCapStatus = addCapabilityToResource(metadataVertex, resourceId, capabilityName, capabilityDefinition); - - if (!addCapStatus.equals(TitanOperationStatus.OK)) { - log.debug("Failed to add capability {} [{}] to Graph", capabilityName, capabilityDefinition); - BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add Capability", capabilityName, String.valueOf(addCapStatus)); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(addCapStatus); - } - } finally { - if (false == inTransaction) { - if (result == null || !result.equals(TitanOperationStatus.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(); - } - } - } - return result; - } - - private CapabilityDefinition convertCDataToCDefinition(CapabilityData capabilityData) { - - CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); - capabilityDefinition.setType(capabilityData.getType()); - - return capabilityDefinition; - } - - @Override - public Either getCapability(String uniqueId) { - - return getCapability(uniqueId, false); - } - - public Either, StorageOperationStatus> getAllCapabilitiesOfResource(String resourceId, boolean recursively, boolean inTransaction) { - - Map capabilities = new HashMap<>(); - Either, StorageOperationStatus> result = null; - Set caseInsensitiveCapabilityNames = new HashSet<>(); - - try { - TitanOperationStatus status = getAllCapabilitiesRecusive(NodeTypeEnum.Resource, resourceId, recursively, capabilities, caseInsensitiveCapabilityNames, inTransaction); - if (!status.equals(TitanOperationStatus.OK)) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - result = Either.left(capabilities); - return result; - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - public TitanOperationStatus getAllCapabilitiesRecusive(NodeTypeEnum nodeType, String resourceId, boolean recursively, Map capabilities, Set caseInsensitiveCapabilityNames, boolean inTransaction) { - - TitanOperationStatus findStatus; - - if (recursively) { - findStatus = findAllCapabilitiesRecursively(resourceId, capabilities, caseInsensitiveCapabilityNames); - - } else { - findStatus = getCapabilitisOfResourceOnly(resourceId, capabilities, caseInsensitiveCapabilityNames); - } - if (!findStatus.equals(TitanOperationStatus.OK)) { - return findStatus; - } - - List derivedFromList = new ArrayList<>(); - TitanOperationStatus fillResourceDerivedListFromGraph = fillResourceDerivedListFromGraph(resourceId, derivedFromList); - if (!fillResourceDerivedListFromGraph.equals(TitanOperationStatus.OK)) { - log.debug("fail to find all valid sources of capability. status = {}", fillResourceDerivedListFromGraph.name()); - return fillResourceDerivedListFromGraph; - } - capabilities.forEach((name, capability) -> capability.setCapabilitySources(derivedFromList)); - return TitanOperationStatus.OK; - } - - protected TitanOperationStatus findAllCapabilitiesRecursively(String resourceId, Map capabilities, Set caseInsensitiveCapabilityNames) { - - TitanOperationStatus resourceCapabilitiesStatus = getCapabilitisOfResourceOnly(resourceId, capabilities, caseInsensitiveCapabilityNames); - - if (!resourceCapabilitiesStatus.equals(TitanOperationStatus.OK)) { - return resourceCapabilitiesStatus; - } - - Either, 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.equals(TitanOperationStatus.NOT_FOUND)) { - log.debug("Failed to find parent capabilities of resource {}. status is {}", resourceId, parentNodesStatus); - BeEcompErrorManager.getInstance().logBeFailedFindParentError("Fetch parent capabilities", resourceId, String.valueOf(parentNodesStatus)); - return parentNodesStatus; - } - } - if (parentNodes.isLeft()) { - ImmutablePair parnetNodePair = parentNodes.left().value(); - String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - TitanOperationStatus addParentIntStatus = findAllCapabilitiesRecursively(parentUniqueId, capabilities, caseInsensitiveCapabilityNames); - - if (addParentIntStatus != TitanOperationStatus.OK) { - log.debug("Failed to fetch all capabilities of resource {}", parentUniqueId); - return addParentIntStatus; - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus getCapabilitisOfResourceOnly(String resourceId, Map capabilities, Set caseInsensitiveCapabilityNames) { - Either>, TitanOperationStatus> allCapabilitiesRes = getAllCapabilitiesPairs(resourceId); - if (allCapabilitiesRes.isRight()) { - TitanOperationStatus status = allCapabilitiesRes.right().value(); - log.debug("After fetching all capabilities of resource {}. status is {}", resourceId, status); - if (status.equals(TitanOperationStatus.NOT_FOUND)) { - status = TitanOperationStatus.OK; - } - return status; - } - - List> capabilityPairs = allCapabilitiesRes.left().value(); - - if (capabilityPairs != null) { - for (ImmutablePair capabilityPair : capabilityPairs) { - CapabilityData capabilityData = capabilityPair.getKey(); - GraphEdge graphEdge = capabilityPair.getValue(); - Map edgeProps = graphEdge.getProperties(); - if (edgeProps != null) { - String capabilityName = (String) edgeProps.get(GraphPropertiesDictionary.NAME.getProperty()); - if (capabilityName == null) { - log.error("Capability name was not found for capability {}", capabilityData.getUniqueId()); - return TitanOperationStatus.INVALID_ELEMENT; - } - Either capabilityDefRes = getCapabilityByCapabilityData(capabilityData); - if (capabilityDefRes.isRight()) { - TitanOperationStatus status = capabilityDefRes.right().value(); - return status; - } - CapabilityDefinition capabilityDefinition = capabilityDefRes.left().value(); - capabilityDefinition.setOwnerId(resourceId); - log.debug("Before adding capability {} with definition {} to result.", capabilityName, capabilityDefinition); - // US631462 - if (caseInsensitiveCapabilityNames.contains(capabilityName.toLowerCase())) { - log.debug("The capability {} was already defined in derived resource (case insensitive). Ignore {} from resource {}", capabilityName, capabilityName, resourceId); - } else { - capabilities.put(capabilityName, capabilityDefinition); - caseInsensitiveCapabilityNames.add(capabilityName.toLowerCase()); - } - } else { - log.debug("Capability name was not found for capability {}", capabilityData.getUniqueId()); - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", capabilityData.getUniqueId(), String.valueOf(TitanOperationStatus.INVALID_ELEMENT)); - return TitanOperationStatus.INVALID_ELEMENT; - } - - } - } - return TitanOperationStatus.OK; - } - - @Override - public Either getCapability(String uniqueId, boolean inTransaction) { - - Either result = null; - - try { - Either capabiltyRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), uniqueId, CapabilityData.class); - if (capabiltyRes.isRight()) { - TitanOperationStatus status = capabiltyRes.right().value(); - log.debug("Failed to retrieve capability {} from graph. status is {}", uniqueId, status); - - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", uniqueId, String.valueOf(status)); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - CapabilityData capabilityData = capabiltyRes.left().value(); - CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); - capabilityDefinition.setDescription(capabilityData.getDescription()); - capabilityDefinition.setUniqueId(capabilityData.getUniqueId()); - capabilityDefinition.setValidSourceTypes(capabilityData.getValidSourceTypes()); - capabilityDefinition.setMinOccurrences(capabilityData.getMinOccurrences()); - capabilityDefinition.setMaxOccurrences(capabilityData.getMaxOccurrences()); - - Either capabilityTypeRes = getCapabilityTypeOfCapability(uniqueId); - if (capabilityTypeRes.isRight()) { - TitanOperationStatus status = capabilityTypeRes.right().value(); - log.debug("Failed to retrieve capability type of capability {}. status is {}", uniqueId, status); - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", uniqueId, String.valueOf(status)); - - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - CapabilityTypeData capabilityTypeData = capabilityTypeRes.left().value(); - capabilityDefinition.setType(capabilityTypeData.getCapabilityTypeDataDefinition().getType()); - - Either, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), uniqueId, GraphEdgeLabels.CAPABILITY, - NodeTypeEnum.Resource, ResourceMetadataData.class); - if (parentNode.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentNode.right().value())); - } else { - ImmutablePair pair = parentNode.left().value(); - capabilityDefinition.setOwnerId(pair.left.getMetadataDataDefinition().getUniqueId()); - List derivedFromList = new ArrayList<>(); - TitanOperationStatus fillResourceDerivedListFromGraph = fillResourceDerivedListFromGraph(pair.left.getMetadataDataDefinition().getUniqueId(), derivedFromList); - if (fillResourceDerivedListFromGraph.equals(TitanOperationStatus.OK)) { - capabilityDefinition.setCapabilitySources(derivedFromList); - } - } - - Either, TitanOperationStatus> getPropertiesRes = getPropertiesOfCapability(uniqueId, capabilityTypeData.getCapabilityTypeDataDefinition().getType()); - if (getPropertiesRes.isRight() && !getPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - TitanOperationStatus status = getPropertiesRes.right().value(); - log.debug("Failed to retrieve properties of capability {}. status is {}", uniqueId, status); - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Properties of Capability", uniqueId, String.valueOf(status)); - - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - if (getPropertiesRes.isLeft()) { - List properties = new ArrayList<>(); - for (PropertyDefinition property : getPropertiesRes.left().value()) { - properties.add(new ComponentInstanceProperty(property, null, null)); - } - capabilityDefinition.setProperties(properties); - } - result = Either.left(capabilityDefinition); - - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - private TitanOperationStatus fillResourceDerivedListFromGraph(String uniqueId, List derivedFromList) { - - Either resourceNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqueId, ResourceMetadataData.class); - - if (resourceNode.isRight()) { - TitanOperationStatus parentNodesStatus = resourceNode.right().value(); - if (!parentNodesStatus.equals(TitanOperationStatus.NOT_FOUND)) { - log.debug("Failed to find resource {} . status is {}", uniqueId, parentNodesStatus); - return parentNodesStatus; - } - } - - derivedFromList.add(((ResourceMetadataDataDefinition) resourceNode.left().value().getMetadataDataDefinition()).getToscaResourceName()); - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqueId, GraphEdgeLabels.DERIVED_FROM, - NodeTypeEnum.Resource, ResourceMetadataData.class); - - if (childrenNodes.isRight() && (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND)) { - return childrenNodes.right().value(); - } else if (childrenNodes.isLeft()) { - - List> pairList = childrenNodes.left().value(); - for (ImmutablePair pair : pairList) { - return fillResourceDerivedListFromGraph(pair.left.getMetadataDataDefinition().getUniqueId(), derivedFromList); - } - } - return TitanOperationStatus.OK; - } - - public Either getCapabilityByCapabilityData(CapabilityData capabilityData) { - - Either result; - - CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); - capabilityDefinition.setDescription(capabilityData.getDescription()); - capabilityDefinition.setUniqueId(capabilityData.getUniqueId()); - capabilityDefinition.setValidSourceTypes(capabilityData.getValidSourceTypes()); - capabilityDefinition.setMinOccurrences(capabilityData.getMinOccurrences()); - capabilityDefinition.setMaxOccurrences(capabilityData.getMaxOccurrences()); - - String capabilityUid = capabilityData.getUniqueId(); - Either capabilityTypeRes = getCapabilityTypeOfCapability(capabilityUid); - if (capabilityTypeRes.isRight()) { - TitanOperationStatus status = capabilityTypeRes.right().value(); - log.debug("Failed to retrieve capability type of capability {} . status is {}", capabilityUid, status); - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", capabilityUid, String.valueOf(status)); - - return Either.right(status); - } - - CapabilityTypeData capabilityTypeData = capabilityTypeRes.left().value(); - capabilityDefinition.setType(capabilityTypeData.getCapabilityTypeDataDefinition().getType()); - - Either, TitanOperationStatus> capabilityPropertiesRes = getPropertiesOfCapability(capabilityUid, capabilityDefinition.getType()); - if (capabilityPropertiesRes.isRight() && !capabilityPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - TitanOperationStatus status = capabilityPropertiesRes.right().value(); - log.debug("Failed to retrieve properties of capability {} . status is {}", capabilityUid, status); - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", capabilityUid, String.valueOf(status)); - - result = Either.right(status); - return result; - } - if (capabilityPropertiesRes.isLeft()) { - List properties = new ArrayList<>(); - for (PropertyDefinition property : capabilityPropertiesRes.left().value()) { - properties.add(new ComponentInstanceProperty(property, null, null)); - } - capabilityDefinition.setProperties(properties); - } - result = Either.left(capabilityDefinition); - return result; - } - - public Either getCapabilityByCapabilityData(TitanVertex capabilityDataVertex) { - - Either result; - - CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); - Map props = titanGenericDao.getProperties(capabilityDataVertex); - CapabilityData capabilityData = GraphElementFactory.createElement((String) props.get(GraphPropertiesDictionary.LABEL.getProperty()), GraphElementTypeEnum.Node, props, CapabilityData.class); - capabilityDefinition.setDescription(capabilityData.getDescription()); - capabilityDefinition.setUniqueId(capabilityData.getUniqueId()); - capabilityDefinition.setValidSourceTypes(capabilityData.getValidSourceTypes()); - capabilityDefinition.setMinOccurrences(capabilityData.getMinOccurrences()); - capabilityDefinition.setMaxOccurrences(capabilityData.getMaxOccurrences()); - - String capabilityUid = capabilityData.getUniqueId(); - Either capabilityTypeRes = getCapabilityTypeOfCapability(capabilityUid); - if (capabilityTypeRes.isRight()) { - TitanOperationStatus status = capabilityTypeRes.right().value(); - log.debug("Failed to retrieve capability type of capability {} . status is {}", capabilityUid, status); - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", capabilityUid, String.valueOf(status)); - - return Either.right(status); - } - - CapabilityTypeData capabilityTypeData = capabilityTypeRes.left().value(); - capabilityDefinition.setType(capabilityTypeData.getCapabilityTypeDataDefinition().getType()); - - Either, TitanOperationStatus> capabilityPropertiesRes = getPropertiesOfCapability(capabilityUid, capabilityDefinition.getType()); - if (capabilityPropertiesRes.isRight() && !capabilityPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - TitanOperationStatus status = capabilityPropertiesRes.right().value(); - log.debug("Failed to retrieve properties of capability {} . status is {}", capabilityUid, status); - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", capabilityUid, String.valueOf(status)); - - result = Either.right(status); - return result; - } - if (capabilityPropertiesRes.isLeft()) { - List properties = new ArrayList<>(); - for (PropertyDefinition property : capabilityPropertiesRes.left().value()) { - properties.add(new ComponentInstanceProperty(property, null, null)); - } - capabilityDefinition.setProperties(properties); - } - result = Either.left(capabilityDefinition); - return result; - } - - public Either, TitanOperationStatus> getPropertiesOfCapability(String capabilityUid, String capabilityType) { - log.debug("Before getting properties of capability {} from graph " , capabilityUid); - - List properties; - Either, TitanOperationStatus> result = null; - Either, TitanOperationStatus> getPropertiesOfCapabilityTypeRes = null; - Either>, TitanOperationStatus> getPropertiesOfCapabilityRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, GraphEdgeLabels.PROPERTY, - NodeTypeEnum.Property, PropertyData.class); - if (getPropertiesOfCapabilityRes.isRight() && !getPropertiesOfCapabilityRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - TitanOperationStatus status = getPropertiesOfCapabilityRes.right().value(); - log.debug("failed to get properties of capability with id {}. status={}", capabilityUid, status); - result = Either.right(status); - } - if (result == null) { - String capabilityTypeUid = UniqueIdBuilder.buildCapabilityTypeUid(capabilityType); - getPropertiesOfCapabilityTypeRes = getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeUid); - if (getPropertiesOfCapabilityTypeRes.isRight() && !getPropertiesOfCapabilityTypeRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - TitanOperationStatus status = getPropertiesOfCapabilityTypeRes.right().value(); - log.error("Failed to retrieve properties for capability type {} from graph. status is {}", capabilityType, status); - result = Either.right(status); - } - } - if (result == null) { - result = getPropertiesOfCapabilityTypeRes.isRight() - ? (getPropertiesOfCapabilityRes.isRight() ? Either.right(TitanOperationStatus.NOT_FOUND) - : Either.left(getPropertiesOfCapabilityRes.left().value().stream().map(p -> propertyOperation.convertPropertyDataToPropertyDefinition(p.getKey(), null, capabilityUid)).collect(Collectors.toList()))) - : (getPropertiesOfCapabilityRes.isRight() ? Either.left(getPropertiesOfCapabilityTypeRes.left().value().values().stream().collect(Collectors.toList())) : null); - } - if (result == null) { - Map propertiesOfCapabilityType = getPropertiesOfCapabilityTypeRes.left().value(); - properties = getPropertiesOfCapabilityRes.left().value().stream() - .map(p -> propertyOperation.convertPropertyDataToPropertyDefinition(p.getKey(), (String) p.getRight().getProperties().get(GraphPropertiesDictionary.NAME.getProperty()), capabilityUid)).collect(Collectors.toList()); - properties.stream().forEach(p -> propertiesOfCapabilityType.remove(p.getName())); - properties.addAll(propertiesOfCapabilityType.values()); - result = Either.left(properties); - } - return result; - } - - @Override - public Either getCapabilityTypeOfCapability(String uniqueId) { - - Either, TitanOperationStatus> capabilityTypeRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), uniqueId, GraphEdgeLabels.TYPE_OF, NodeTypeEnum.CapabilityType, - CapabilityTypeData.class); - - if (capabilityTypeRes.isRight()) { - TitanOperationStatus status = capabilityTypeRes.right().value();// - log.debug("Cannot find capability type associated with capability {}. status is {}", uniqueId, status); - BeEcompErrorManager.getInstance().logBeFailedFindAssociationError("Fetch Capability type", NodeTypeEnum.CapabilityType.getName(), uniqueId, String.valueOf(status)); - return Either.right(capabilityTypeRes.right().value()); - } - - CapabilityTypeData capabilityTypeData = capabilityTypeRes.left().value().getKey(); - - return Either.left(capabilityTypeData); - - } - - @Override - public Either getCapability(String capabilityName, String resourceId) { - return getCapability(UniqueIdBuilder.buildCapabilityUid(resourceId, capabilityName)); - } - - @Override - public Either getCapability(String capabilityName, String resourceId, boolean inTransaction) { - return getCapability(UniqueIdBuilder.buildCapabilityUid(resourceId, capabilityName), inTransaction); - } - - @Override - public Either>, TitanOperationStatus> getAllCapabilitiesPairs(String resourceId) { - - Either>, TitanOperationStatus> capabilitiesNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.CAPABILITY, - NodeTypeEnum.Capability, CapabilityData.class); - - log.debug("After looking for all capabilities under resource {}. status is {}" , resourceId , capabilitiesNodes); - if (capabilitiesNodes.isRight()) { - TitanOperationStatus status = capabilitiesNodes.right().value(); - return Either.right(status); - } - - List> capabilities = capabilitiesNodes.left().value(); - if (capabilities == null || true == capabilities.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - return Either.left(capabilitiesNodes.left().value()); - } - - private Either addCapabilityToResource(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition) { - - log.debug("Going to add capability {} [ {} ] to resource uid {}" , capabilityName, capabilityDefinition, resourceId); - - Either createCapRes = createCapability(resourceId, capabilityName, capabilityDefinition); - - log.debug("After creating capability node in graph. status is {}", createCapRes); - if (createCapRes.isRight()) { - TitanOperationStatus status = createCapRes.right().value(); - log.error("Failed to create capability data node in graph. status is {}", status); - return Either.right(status); - } - CapabilityData capabilityData = createCapRes.left().value(); - - String capabilityType = capabilityDefinition.getType(); - - log.debug("Going to associate capability {} to its capabilityType {}", capabilityName, capabilityType); - - Either associateCapabilityTypeRes = associateCapabilityToCapabilityType(capabilityData, capabilityType); - log.debug("After associating capability {} to its capabilityType {}. status is {}", capabilityName, capabilityType, associateCapabilityTypeRes); - if (associateCapabilityTypeRes.isRight()) { - TitanOperationStatus status = associateCapabilityTypeRes.right().value(); - log.error("Failed to associate capability {} to its capabilityType {} in graph. status is {} ", capabilityName, capabilityType, status); - - return Either.right(status); - } - List ciProperties = capabilityDefinition.getProperties(); - if (ciProperties != null && !ciProperties.isEmpty()) { - List properties = ciProperties.stream().map(prop -> new PropertyDefinition(prop)).collect(Collectors.toList()); - Either, TitanOperationStatus> addPropertiesRes = addPropertiesToCapability(capabilityData, capabilityType, properties); - if (addPropertiesRes.isRight()) { - TitanOperationStatus operationStatus = addPropertiesRes.right().value(); - return Either.right(operationStatus); - } - } - - Either associateResourceRes = associateResourceToCapability(resourceId, capabilityName, capabilityData); - if (associateResourceRes.isRight()) { - TitanOperationStatus status = associateResourceRes.right().value(); - log.error("Failed to associate resource {} to capability {}. status is {}", resourceId, capabilityData, status); - return Either.right(status); - } - - return Either.left(capabilityData); - - } - - private TitanOperationStatus addCapabilityToResource(TitanVertex metadataVertex, String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition) { - - log.debug("Going to add capability {} [ {} ] to resource uid {}", capabilityName, capabilityDefinition, resourceId); - - Either createCapRes = createCapabilityVertex(resourceId, capabilityName, capabilityDefinition); - - log.debug("After creating capability node in graph. status is {}", createCapRes); - if (createCapRes.isRight()) { - TitanOperationStatus status = createCapRes.right().value(); - log.error("Failed to create capability data node in graph. status is {}", status); - return status; - } - TitanVertex capabilityVertex = createCapRes.left().value(); - - String capabilityType = capabilityDefinition.getType(); - - log.debug("Going to associate capability {} to its capabilityType {}", capabilityName, capabilityType); - - TitanOperationStatus associateCapabilityTypeRes = associateCapabilityToCapabilityType(capabilityVertex, capabilityType); - log.debug("After associating capability {} to its capabilityType {}. status is {}", capabilityName, capabilityType, associateCapabilityTypeRes); - if (!associateCapabilityTypeRes.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate capability {} to its capabilityType {} in graph. status is {} ", capabilityName, capabilityType, associateCapabilityTypeRes); - return associateCapabilityTypeRes; - } - List ciProperties = capabilityDefinition.getProperties(); - if (ciProperties != null && !ciProperties.isEmpty()) { - String capabiltyId = (String) titanGenericDao.getProperty(capabilityVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - List properties = ciProperties.stream().map(prop -> new PropertyDefinition(prop)).collect(Collectors.toList()); - TitanOperationStatus addPropertiesRes = addPropertiesToCapability(capabilityVertex, capabilityType, properties, capabiltyId); - if (!addPropertiesRes.equals(TitanOperationStatus.OK)) { - return addPropertiesRes; - } - } - - TitanOperationStatus associateResourceRes = associateResourceToCapability(resourceId, capabilityName, capabilityVertex, metadataVertex); - if (!associateResourceRes.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate resource{} to capability {}. status is {} ", resourceId, capabilityName, associateResourceRes); - } - - return associateResourceRes; - - } - - private Either associateCapabilityToCapabilityType(CapabilityData capabilityData, String capabilityType) { - UniqueIdData capabilityTypeIdData = new UniqueIdData(NodeTypeEnum.CapabilityType, UniqueIdBuilder.buildCapabilityTypeUid(capabilityType)); - log.debug("Before associating {} to capability type {}.", capabilityData, capabilityType); - Either createRelResult = titanGenericDao.createRelation(capabilityData, capabilityTypeIdData, GraphEdgeLabels.TYPE_OF, null); - log.debug("After associating {} to capability type {}. status is {}" , capabilityData, capabilityType, createRelResult); - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate capability {} to capability type {} in graph. status is {}", capabilityData, capabilityTypeIdData, operationStatus); - return Either.right(operationStatus); - } - return Either.left(createRelResult.left().value()); - - } - - private TitanOperationStatus associateCapabilityToCapabilityType(TitanVertex capabilityVertex, String capabilityType) { - - UniqueIdData capabilityTypeIdData = new UniqueIdData(NodeTypeEnum.CapabilityType, UniqueIdBuilder.buildCapabilityTypeUid(capabilityType)); - - log.debug("Before associating {} to capability type {}.", capabilityVertex, capabilityType); - TitanOperationStatus createRelResult = titanGenericDao.createEdge(capabilityVertex, capabilityTypeIdData, GraphEdgeLabels.TYPE_OF, null); - log.trace("After associating {} to capability type {}. status is {}", capabilityVertex, capabilityType, createRelResult); - if (!createRelResult.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate capability {} to capability type {} in graph. status is {}", capabilityVertex, capabilityTypeIdData, createRelResult); - } - return createRelResult; - } - - private Either associateResourceToCapability(String resourceId, String capabilityName, CapabilityData capabilityData) { - - UniqueIdData resourceIdData = new UniqueIdData(NodeTypeEnum.Resource, resourceId); - - log.debug("Before associating resource {} to capability {}.", resourceId, capabilityData); - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName); - Either createRelResult = titanGenericDao.createRelation(resourceIdData, capabilityData, GraphEdgeLabels.CAPABILITY, props); - log.debug("After associating resource {} to capability {}. status is {}" , resourceId, capabilityData, createRelResult); - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate resource {} to capability {} in graph. status is {}", resourceId, capabilityData, operationStatus); - return Either.right(operationStatus); - } - - return Either.left(createRelResult.left().value()); - - } - - private TitanOperationStatus associateResourceToCapability(String resourceId, String capabilityName, TitanVertex capabilityVertex, TitanVertex resourceVertex) { - - log.debug("Before associating resource {} to capability {}.", resourceId, capabilityName); - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName); - TitanOperationStatus createRelResult = titanGenericDao.createEdge(resourceVertex, capabilityVertex, GraphEdgeLabels.CAPABILITY, props); - log.debug("After associating resource {} to capability {}. status is {}", resourceId, capabilityName, createRelResult); - if (!createRelResult.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate resource {} to capability {} in graph. status is {}", resourceId, capabilityName, createRelResult); - } - - return createRelResult; - - } - - /** - * - * create capability node in the graph - * - * @param resourceId - * @param capabilityName - * @param capabilityDefinition - * @return - */ - private Either createCapability(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition) { - - CapabilityData capabilityData = new CapabilityData(); - String uid = UniqueIdBuilder.buildCapabilityUid(resourceId, capabilityName); - capabilityData.setUniqueId(uid); - Long creationTime = System.currentTimeMillis(); - capabilityData.setCreationTime(creationTime); - capabilityData.setModificationTime(creationTime); - capabilityData.setValidSourceTypes(capabilityDefinition.getValidSourceTypes()); - capabilityData.setMinOccurrences(capabilityDefinition.getMinOccurrences()); - capabilityData.setMaxOccurrences(capabilityDefinition.getMaxOccurrences()); - capabilityData.setDescription(capabilityDefinition.getDescription()); - - Either createNode = titanGenericDao.createNode(capabilityData, CapabilityData.class); - - log.debug("After creating capability node in the graph. status is {}", createNode); - - return createNode; - } - - private Either createCapabilityVertex(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition) { - - CapabilityData capabilityData = new CapabilityData(); - String uid = UniqueIdBuilder.buildCapabilityUid(resourceId, capabilityName); - capabilityData.setUniqueId(uid); - Long creationTime = System.currentTimeMillis(); - capabilityData.setCreationTime(creationTime); - capabilityData.setModificationTime(creationTime); - capabilityData.setValidSourceTypes(capabilityDefinition.getValidSourceTypes()); - capabilityData.setMinOccurrences(capabilityDefinition.getMinOccurrences()); - capabilityData.setMaxOccurrences(capabilityDefinition.getMaxOccurrences()); - capabilityData.setDescription(capabilityDefinition.getDescription()); - - Either createNode = titanGenericDao.createNode(capabilityData); - - log.debug("After creating capability node in the graph. status is {}", createNode); - - return createNode; - } @Override - public Either addCapability(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition) { - - return addCapability(resourceId, capabilityName, capabilityDefinition, false); - - } - - public StorageOperationStatus deleteCapabilityFromGraph(String capabilityUid) { - - TitanOperationStatus resultStatus = null; - - Either>, TitanOperationStatus> deletePropertiesStatus = deletePropertiesOfCapability(capabilityUid); - - if (deletePropertiesStatus.isRight() && !deletePropertiesStatus.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - resultStatus = deletePropertiesStatus.right().value(); - } - if (resultStatus == null) { - log.debug("Before deleting capability from graph {}" , capabilityUid); - Either deleteNodeStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, CapabilityData.class); - if (deleteNodeStatus.isRight()) { - resultStatus = deleteNodeStatus.right().value(); - } - } - if (resultStatus != null) { - log.debug("failed to delete capability with id {}. status={}", capabilityUid, resultStatus); - BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete capability", capabilityUid, String.valueOf(resultStatus)); - return DaoStatusConverter.convertTitanStatusToStorageStatus(resultStatus); - } - return StorageOperationStatus.OK; - } - - public Either, StorageOperationStatus> deleteAllCapabilities(String resourceId, boolean inTransaction) { - - Either, StorageOperationStatus> result = null; - try { - - Either, TitanOperationStatus> deleteAllRes = deleteAllCapabilitiesOfResource(resourceId); - if (deleteAllRes.isRight()) { - TitanOperationStatus status = deleteAllRes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to delete capabilities of resource {}. status is {}", resourceId, status); - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - Map value = deleteAllRes.left().value(); - result = Either.left(value); - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - } - - public Either, StorageOperationStatus> deleteAllCapabilities(String resourceId) { - - return deleteAllCapabilities(resourceId, false); - - } - - private Either, TitanOperationStatus> deleteAllCapabilitiesOfResource(String resourceId) { - TitanOperationStatus resultStatus = null; - Map capabilities = new HashMap<>(); - Set caseInsensitiveCapabilityNames = new HashSet<>(); - TitanOperationStatus capabilitisRes = getCapabilitisOfResourceOnly(resourceId, capabilities, caseInsensitiveCapabilityNames); - if (capabilitisRes != TitanOperationStatus.OK) { - return Either.right(capabilitisRes); - } - - if (capabilities.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - for (Entry entry : capabilities.entrySet()) { - CapabilityDefinition capabilityDefinition = entry.getValue(); - String capabilityUid = capabilityDefinition.getUniqueId(); - - log.debug("Before deleting properties of capability {} from graph " , capabilityUid); - - Either>, TitanOperationStatus> deletePropertiesStatus = deletePropertiesOfCapability(capabilityUid); - if (deletePropertiesStatus.isRight() && !deletePropertiesStatus.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - resultStatus = deletePropertiesStatus.right().value(); - } - if (resultStatus == null) { - Either deleteNodeRes = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, CapabilityData.class); - if (deleteNodeRes.isRight()) { - resultStatus = deleteNodeRes.right().value(); - } - } - if (resultStatus != null) { - log.debug("Failed to delete capability {} of resource {}", capabilityUid, resourceId); - BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete capability", capabilityUid, String.valueOf(resultStatus)); - return Either.right(resultStatus); - } - } - - return Either.left(capabilities); - - } - - public Map> convertCapabilityMap(Map capabilityMap, String ownerId, String ownerName) { - - Map> typeToRequirementMap = new HashMap<>(); - capabilityMap.forEach((capabilityName, capability) -> { - capability.setName(capabilityName); - if (typeToRequirementMap.containsKey(capability.getType())) { - typeToRequirementMap.get(capability.getType()).add(capability); - } else { - List list = new ArrayList<>(); - list.add(capability); - typeToRequirementMap.put(capability.getType(), list); - } - }); - return typeToRequirementMap; - } - - public TitanOperationStatus getCapabilitySourcesList(String resourceId, List derivedFromList) { - Map propertiesToMatch = new HashMap<>(); - propertiesToMatch.put(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId); - Either, TitanOperationStatus> getResponse = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class); - if (getResponse.isRight()) { - return getResponse.right().value(); - } else { - String toscaResourceName = ((ResourceMetadataDataDefinition) getResponse.left().value().get(0).getMetadataDataDefinition()).getToscaResourceName(); - derivedFromList.add(toscaResourceName); - } - - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, - NodeTypeEnum.Resource, ResourceMetadataData.class); - - while (childrenNodes.isLeft()) { - - List> pairList = childrenNodes.left().value(); - ResourceMetadataData left = pairList.get(0).left; - derivedFromList.add(((ResourceMetadataDataDefinition) left.getMetadataDataDefinition()).getToscaResourceName()); - String id = left.getMetadataDataDefinition().getUniqueId(); - childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), id, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class); - } - return TitanOperationStatus.OK; - } - - private Either, TitanOperationStatus> addPropertiesToCapability(CapabilityData capabilityData, String capabilityType, List properties) { - String capabilityTypeUid = UniqueIdBuilder.buildCapabilityTypeUid(capabilityType); - Either, TitanOperationStatus> allPropertiesOfCapabilityTypeRes = getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeUid); - if (allPropertiesOfCapabilityTypeRes.isRight() && !allPropertiesOfCapabilityTypeRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - TitanOperationStatus operationStatus = allPropertiesOfCapabilityTypeRes.right().value(); - log.error("Failed to retrieve properties for capability type {} from graph. status is {}", capabilityType, operationStatus); - return Either.right(operationStatus); - } - - Map propertiesOfCapabilityType = null; - - if (allPropertiesOfCapabilityTypeRes.isLeft() && allPropertiesOfCapabilityTypeRes.left() != null && !allPropertiesOfCapabilityTypeRes.left().value().isEmpty()) { - - propertiesOfCapabilityType = allPropertiesOfCapabilityTypeRes.left().value(); - Either, TitanOperationStatus> validateAndReducePropertiesRes = validatePropertyUniqueness(propertiesOfCapabilityType, properties); - if (validateAndReducePropertiesRes.isRight()) { - TitanOperationStatus operationStatus = validateAndReducePropertiesRes.right().value(); - log.error("Failed to add properties to capability {} in graph. status is {}", capabilityData.getUniqueId(), operationStatus); - return Either.right(operationStatus); - } - } - - Either, TitanOperationStatus> addPropertiesToCapabilityRes = propertyOperation.addPropertiesToElementType(capabilityData.getUniqueId(), NodeTypeEnum.Capability, properties); - if (addPropertiesToCapabilityRes.isRight()) { - TitanOperationStatus operationStatus = addPropertiesToCapabilityRes.right().value(); - log.error("Failed to add properties to capability {} in graph. status is {}", capabilityData.getUniqueId(), operationStatus); - return Either.right(operationStatus); - } - return Either.left(addPropertiesToCapabilityRes.left().value()); - } - - private TitanOperationStatus addPropertiesToCapability(TitanVertex capabilityVertex, String capabilityType, List properties, String uniqueId) { - String capabilityTypeUid = UniqueIdBuilder.buildCapabilityTypeUid(capabilityType); - Either, TitanOperationStatus> allPropertiesOfCapabilityTypeRes = getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeUid); - if (allPropertiesOfCapabilityTypeRes.isRight() && !allPropertiesOfCapabilityTypeRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - TitanOperationStatus operationStatus = allPropertiesOfCapabilityTypeRes.right().value(); - log.error("Failed to retrieve properties for capability type {} from graph. status is {}", capabilityType, operationStatus); - return operationStatus; - } - Map propertiesOfCapabilityType = null; - - if (allPropertiesOfCapabilityTypeRes.isLeft() && allPropertiesOfCapabilityTypeRes.left() != null && !allPropertiesOfCapabilityTypeRes.left().value().isEmpty()) { - - propertiesOfCapabilityType = allPropertiesOfCapabilityTypeRes.left().value(); - Either, TitanOperationStatus> validateAndReducePropertiesRes = validatePropertyUniqueness(propertiesOfCapabilityType, properties); - if (validateAndReducePropertiesRes.isRight()) { - TitanOperationStatus operationStatus = validateAndReducePropertiesRes.right().value(); - log.error("Failed to add properties to capability {} in graph. status is {}", capabilityVertex, operationStatus); - return operationStatus; - } - } - - String capabiltyId = (String) titanGenericDao.getProperty(capabilityVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - TitanOperationStatus addPropertiesToCapabilityRes = propertyOperation.addPropertiesToElementType(capabilityVertex, capabiltyId, NodeTypeEnum.Capability, properties); - if (!addPropertiesToCapabilityRes.equals(TitanOperationStatus.OK)) { - log.error("Failed to add properties to capability {} in graph. status is {}", capabiltyId, addPropertiesToCapabilityRes); - } - return addPropertiesToCapabilityRes; - } - public Either, TitanOperationStatus> validatePropertyUniqueness(Map propertiesOfCapabilityType, List properties) { Either, TitanOperationStatus> result = Either.left(properties); @@ -1043,119 +117,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit return result; } - public StorageOperationStatus validateUpdateCapabilityProperty(PropertyDefinition property) { - Either, TitanOperationStatus> allDataTypes = applicationDataTypeCache.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 DaoStatusConverter.convertTitanStatusToStorageStatus(allDataTypes.right().value()); - } - return propertyOperation.validateAndUpdateProperty(property, allDataTypes.left().value()); - } - - public StorageOperationStatus validateCapabilityProperties(List properties) { - StorageOperationStatus result = StorageOperationStatus.OK; - for (PropertyDefinition property : properties) { - result = validateUpdateCapabilityProperty(property); - if (!result.equals(StorageOperationStatus.OK)) - break; - } - return result; - } - - public Either>, TitanOperationStatus> deletePropertiesOfCapability(String capabilityUid) { - log.debug("Before deleting properties of capability {} from graph " , capabilityUid); - - Either>, TitanOperationStatus> deletePropertiesStatus = titanGenericDao.deleteChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, GraphEdgeLabels.PROPERTY, - NodeTypeEnum.Property, PropertyData.class); - if (deletePropertiesStatus.isRight()) { - TitanOperationStatus status = deletePropertiesStatus.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - log.debug("failed to delete properties of capability with id {}. status={}", capabilityUid, status); - } else { - log.debug("The Capability with id {} have no Properties. status={}", capabilityUid, status); - } - return Either.right(status); - } - return Either.left(deletePropertiesStatus.left().value()); - } - - @Override - public Either, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId, String capabilityType, List newProperties) { - return updatePropertiesOfCapability(uniqueId, capabilityType, newProperties, false); - } - @Override - public Either, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId, String capabilityType, List newProperties, boolean inTransaction) { - - Either, StorageOperationStatus> result = null; - try { - Either capabiltyRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), uniqueId, CapabilityData.class); - if (capabiltyRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(capabiltyRes.right().value())); - } - CapabilityData capabilityData = capabiltyRes.left().value(); - if (result == null) { - StorageOperationStatus propertiesValidationRes = validateCapabilityProperties(newProperties); - if (!propertiesValidationRes.equals(StorageOperationStatus.OK)) { - result = Either.right(propertiesValidationRes); - } - } - if (result == null) { - Either>, TitanOperationStatus> deletePropertiesRes = deletePropertiesOfCapability(uniqueId); - if (deletePropertiesRes.isRight() && !deletePropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deletePropertiesRes.right().value())); - } - } - if (result == null) { - Either, TitanOperationStatus> addPropertiesRes = addPropertiesToCapability(capabilityData, capabilityType, newProperties); - if (addPropertiesRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertiesRes.right().value())); - } else { - result = Either.left(addPropertiesRes.left().value()); - } - } - if (result.isRight()) { - log.debug("Failed to update properties of capability {}. status is {}", uniqueId, result); - } - return result; - } finally { - if (!inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - } - - public Either getCapabilityRelatedToResourceInstance(String resourceInstanceId, String capabilityUid) { - TitanOperationStatus error = null; - CapabilityData capability = null; - Either>, TitanOperationStatus> getCapabilitiesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, - GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class); - if (getCapabilitiesRes.isRight()) { - error = getCapabilitiesRes.right().value(); - log.debug("Failed to retrieve capabilities for resource instance {}. status is {}", resourceInstanceId, error); - } else { - List> capabilityPairsList = getCapabilitiesRes.left().value(); - List capabilityPair = capabilityPairsList.stream().filter(pair -> pair.getLeft().getUniqueId().equals(capabilityUid)).map(pair -> pair.getLeft()).collect(Collectors.toList()); - if (capabilityPair.isEmpty()) { - error = TitanOperationStatus.NOT_FOUND; - log.debug("Failed to retrieve capability {} for resource instance {}. status is {}", capabilityUid, resourceInstanceId, error); - } else { - capability = capabilityPair.get(0); - } - } - if (error == null) { - return Either.left(capability); - } - return Either.right(error); - } - public Either, TitanOperationStatus> getAllCapabilityTypePropertiesFromAllDerivedFrom(String firstParentType) { Map allProperies = new HashMap<>(); return getCapabilityTypePropertiesFromDerivedFromRecursively(firstParentType, allProperies); 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 ddd6017620..203135b31e 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 @@ -37,6 +37,7 @@ 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.ICapabilityTypeOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.CapabilityTypeData; @@ -54,7 +55,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab @Autowired private PropertyOperation propertyOperation; @Autowired - private CapabilityOperation capabilityOperation; + private ICapabilityOperation capabilityOperation; public CapabilityTypeOperation() { super(); 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 cb9adeda3f..1ef64aed98 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,30 +20,15 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.function.Function; -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.lang3.tuple.ImmutablePair; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.VertexProperty; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; -import org.openecomp.sdc.be.dao.graph.GraphElementFactory; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; @@ -51,74 +36,33 @@ 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.CapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyRule; -import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.GroupInstance; -import org.openecomp.sdc.be.model.HeatParameterDefinition; import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RelationshipImpl; -import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; -import org.openecomp.sdc.be.model.operations.api.IAttributeOperation; import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation; +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.ArtifactData; import org.openecomp.sdc.be.resources.data.AttributeData; import org.openecomp.sdc.be.resources.data.AttributeValueData; -import org.openecomp.sdc.be.resources.data.CapabilityData; -import org.openecomp.sdc.be.resources.data.CapabilityInstData; import org.openecomp.sdc.be.resources.data.ComponentInstanceData; -import org.openecomp.sdc.be.resources.data.ComponentMetadataData; 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.PropertyValueData; -import org.openecomp.sdc.be.resources.data.RelationshipInstData; -import org.openecomp.sdc.be.resources.data.RelationshipTypeData; -import org.openecomp.sdc.be.resources.data.RequirementData; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import org.openecomp.sdc.be.resources.data.UniqueIdData; -import org.openecomp.sdc.be.resources.data.UserData; -import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; -import org.openecomp.sdc.common.api.ArtifactTypeEnum; -import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.common.datastructure.Wrapper; -import org.openecomp.sdc.common.util.ValidationUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.thinkaurelius.titan.core.TitanEdge; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; -import com.thinkaurelius.titan.core.TitanVertexQuery; - -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 { @@ -129,24 +73,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo private static Logger log = LoggerFactory.getLogger(ComponentInstanceOperation.class.getName()); - @Autowired - private ResourceOperation resourceOperation; - - @Autowired - private ServiceOperation serviceOperation; - - @Autowired - CapabilityOperation capabilityOperation; - - @Autowired - private CapabilityInstanceOperation capabilityInstanceOperation; - - @Autowired - private RequirementOperation requirementOperation; - - @Autowired - private ArtifactOperation artifactOperation; - @Autowired TitanGenericDao titanGenericDao; @@ -154,20 +80,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo PropertyOperation propertyOperation; @Autowired - InputsOperation inputOperation; - - @Autowired - private IAttributeOperation attributeOperation; + private IInputsOperation inputOperation; @Autowired private ApplicationDataTypeCache dataTypeCache; - @Autowired - protected GroupOperation groupOperation; - - @Autowired - protected GroupInstanceOperation groupInstanceOperation; - /** * FOR TEST ONLY * @@ -178,5880 +95,580 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } @Override - public Either createComponentInstance(String parentComponentId, NodeTypeEnum nodeType, String instanceNumber, ComponentInstance componentInstance, NodeTypeEnum compInstNodeType, boolean inTransaction) { - - return createComponentInstance(parentComponentId, nodeType, instanceNumber, true, componentInstance, compInstNodeType, false, inTransaction); - - } - - private Either createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, boolean isCreateLocgicalName, ComponentInstance componentInstance, - NodeTypeEnum compInstNodeType, boolean allowDeleted, boolean inTransaction) { - Either result = null; + public Either increaseAndGetResourceInstanceSpecificCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, boolean inTransaction) { - if (!ValidationUtils.validateStringNotEmpty(componentInstance.getCustomizationUUID())) { - generateCustomizationUUID(componentInstance); - } + Either result = null; try { - Either addRes = addComponentInstanceToContainerComponent(containerComponentId, containerNodeType, instanceNumber, isCreateLocgicalName, componentInstance, compInstNodeType, allowDeleted); - if (addRes.isRight()) { - TitanOperationStatus status = addRes.right().value(); - log.error("Failed to add resource instance {} to service {}. status is {}", componentInstance, containerComponentId, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + Either graphResult = titanGenericDao.getGraph(); + if (graphResult.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); return result; } - - ComponentInstance value = addRes.left().value(); - result = Either.left(value); - - return result; - - } finally { - if (false == inTransaction) { - commitOrRollback(result); + Either 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; } - } - } - - private Either createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, boolean isCreateLocgicalName, ComponentInstance componentInstance, - NodeTypeEnum compInstNodeType, boolean allowDeleted, boolean inTransaction, TitanVertex metadataVertex) { - Either result = null; - - try { + Vertex vertex = vertexService.left().value(); - Either addRes = addComponentInstanceToContainerComponent(containerComponentId, containerNodeType, instanceNumber, isCreateLocgicalName, componentInstance, compInstNodeType, allowDeleted, metadataVertex); - if (addRes.isRight()) { - TitanOperationStatus status = addRes.right().value(); - log.error("Failed to add resource instance {} to service {}. status is {}", componentInstance, containerComponentId, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; + VertexProperty vertexProperty = vertex.property(counterType.getProperty()); + Integer counter = 0; + if (vertexProperty.isPresent()) { + if (vertexProperty.value() != null) { + counter = (Integer) vertexProperty.value(); + } } - TitanVertex value = addRes.left().value(); - result = Either.left(value); + counter++; + vertex.property(counterType.getProperty(), counter); + result = Either.left(counter); return result; } finally { if (false == inTransaction) { - commitOrRollback(result); + 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(); + } } } + } - @Override - public Either createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, ComponentInstance componentInstance, NodeTypeEnum instNodeType) { + private void connectAttValueDataToComponentInstanceData(Wrapper errorWrapper, ComponentInstanceData compIns, AttributeValueData attValueData) { - return createComponentInstance(containerComponentId, containerNodeType, instanceNumber, componentInstance, instNodeType, false); + Either 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); + } } - @Override - public Either deleteComponentInstance(NodeTypeEnum containerNodeType, String containerComponentId, String resourceInstUid, boolean inTransaction) { + private void connectAttValueDataToAttData(Wrapper errorWrapper, AttributeData attData, AttributeValueData attValueData) { - Either result = null; + Either createRelResult = titanGenericDao.createRelation(attValueData, attData, GraphEdgeLabels.ATTRIBUTE_IMPL, null); - try { + 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); - Either deleteRes = removeComponentInstanceFromComponent(containerNodeType, containerComponentId, resourceInstUid); + errorWrapper.setInnerElement(operationStatus); + } + } - if (deleteRes.isRight()) { - TitanOperationStatus status = deleteRes.right().value(); - log.error("Failed to remove resource instance {} from component {}. status is {}", resourceInstUid, containerComponentId, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } + private void createAttributeValueDataNode(ComponentInstanceProperty attributeInstanceProperty, Integer index, Wrapper errorWrapper, ComponentInstanceData resourceInstanceData, + Wrapper attValueDataWrapper) { + String valueUniqueUid = attributeInstanceProperty.getValueUniqueUid(); + if (valueUniqueUid == null) { - ComponentInstance value = deleteRes.left().value(); - result = Either.left(value); + String attValueDatauniqueId = UniqueIdBuilder.buildResourceInstanceAttributeValueUid(resourceInstanceData.getUniqueId(), index); + AttributeValueData attributeValueData = buildAttributeValueDataFromComponentInstanceAttribute(attributeInstanceProperty, attValueDatauniqueId); - return result; + log.debug("Before adding attribute value to graph {}", attributeValueData); + Either createNodeResult = titanGenericDao.createNode(attributeValueData, AttributeValueData.class); + log.debug("After adding attribute value to graph {}", attributeValueData); - } finally { - if (false == inTransaction) { - commitOrRollback(result); + if (createNodeResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + errorWrapper.setInnerElement(operationStatus); + } else { + attValueDataWrapper.setInnerElement(createNodeResult.left().value()); } - } - - } - - @Override - public Either deleteComponentInstance(NodeTypeEnum containerNodeType, String containerComponentId, String resourceInstUid) { - - return deleteComponentInstance(containerNodeType, containerComponentId, resourceInstUid, false); - } - private void commitOrRollback(Either result) { - 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(); + BeEcompErrorManager.getInstance().logInternalFlowError("CreateAttributeValueDataNode", "attribute value already exists.", ErrorSeverity.ERROR); + errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST); } } - @Override - public Either validateParent(String parentId, String uniqId, boolean inTransaction) { - - Either result = null; - Either updateRes = validateParentonGraph(parentId, uniqId, inTransaction); - - if (updateRes.isRight()) { - TitanOperationStatus status = updateRes.right().value(); - log.error("Failed to find resource instance name {}. status is {}", uniqId, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - Boolean value = updateRes.left().value(); - - result = Either.left(value); - - return result; - + 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; } - public Either validateParentonGraph(String parentId, String uniqId, boolean inTransaction) { + private static final class UpdateDataContainer { + final Wrapper valueDataWrapper; + final Wrapper dataWrapper; + final GraphEdgeLabels graphEdge; + final Supplier> someDataClassGen; + final Supplier> someValueDataClassGen; + final NodeTypeEnum nodeType; + final NodeTypeEnum nodeTypeValue; - Either graphRes = titanGenericDao.getGraph(); - if (graphRes.isRight()) { - log.debug("Failed to retrieve graph. status is {}", graphRes); - return Either.right(graphRes.right().value()); + private UpdateDataContainer(GraphEdgeLabels graphEdge, Supplier> someDataClassGen, Supplier> 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; } - TitanGraph titanGraph = graphRes.left().value(); - try { - Iterable vertices = titanGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), uniqId).vertices(); - if (vertices == null || false == vertices.iterator().hasNext()) { - return Either.right(TitanOperationStatus.INVALID_ID); - } - TitanVertex vertex = vertices.iterator().next(); - - TitanVertexQuery query = vertex.query(); - query = query.labels(GraphEdgeLabels.RESOURCE_INST.getProperty()).direction(Direction.IN); - Iterable verts = query.vertices(); - if (verts == null) { - log.debug("No edges in graph for criteria"); - return Either.right(TitanOperationStatus.INVALID_ID); - } - Iterator vIter = verts.iterator(); - if (vIter.hasNext()) { - Vertex vert = vIter.next(); - // vert.getProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - String resInstName = vert.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - if (resInstName.equals(parentId)) - return Either.left(Boolean.TRUE); - } - return Either.left(Boolean.FALSE); - } finally { - if (false == inTransaction) { - titanGraph.tx().commit(); - } + public Wrapper getValueDataWrapper() { + return valueDataWrapper; } - } - - public Either addComponentInstanceToContainerComponent(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, boolean isCreateLogicaName, ComponentInstance componentInstance, - NodeTypeEnum compInstNodeType, boolean allowDeleted) { - log.debug("Going to create component instance {} in component {}", componentInstance, containerComponentId); - Either metadataVertex = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), containerComponentId); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); + public Wrapper getDataWrapper() { + return dataWrapper; } - Either addComponentInstanceToContainerComponent = addComponentInstanceToContainerComponent(containerComponentId, containerNodeType, instanceNumber, isCreateLogicaName, componentInstance, compInstNodeType, - allowDeleted, metadataVertex.left().value()); - if (addComponentInstanceToContainerComponent.isRight()) { - TitanOperationStatus status = addComponentInstanceToContainerComponent.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); + public GraphEdgeLabels getGraphEdge() { + return graphEdge; } - TitanVertex ciVertex = addComponentInstanceToContainerComponent.left().value(); - Map properties = titanGenericDao.getProperties(ciVertex); - ComponentInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.ResourceInstance.getName(), GraphElementTypeEnum.Node, properties, ComponentInstanceData.class); - Either createdResourceInstanceRes = createGroupInstancesOnComponentInstance(componentInstance, ciVertex, createdComponentInstance); - return createdResourceInstanceRes; - } - - - public Either createGroupInstancesOnComponentInstance(ComponentInstance componentInstance, TitanVertex ciVertex, ComponentInstanceData createdComponentInstance) { - ComponentInstance createdResourceInstance = new ComponentInstance(createdComponentInstance.getComponentInstDataDefinition()); - createdResourceInstance.setGroupInstances(componentInstance.getGroupInstances()); - List groupInstancesList = new ArrayList(); - List group = null; - Either, TitanOperationStatus> groupEither = groupOperation.getAllGroupsFromGraph(createdResourceInstance.getComponentUid(), NodeTypeEnum.Resource); - if (groupEither.isRight() && groupEither.right().value() != TitanOperationStatus.OK && groupEither.right().value() != TitanOperationStatus.NOT_FOUND) { - TitanOperationStatus status = groupEither.right().value(); - log.debug("Failed to associate group instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status); - return Either.right(status); - } else { - if (groupEither.isLeft()) { - group = groupEither.left().value(); - if (group != null && !group.isEmpty()) { - List vfGroupsList = group.stream().filter(p -> p.getType().equals("org.openecomp.groups.VfModule")).collect(Collectors.toList()); - for (GroupDefinition groupDefinition : vfGroupsList) { - Either status = createGroupInstance(ciVertex, groupDefinition, createdResourceInstance); - if (status.isRight()) { - log.debug("Failed to associate group instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status); - - } else { - GroupInstance groupInstance = status.left().value(); - groupInstancesList.add(groupInstance); - } + public Supplier> getSomeDataClassGen() { + return someDataClassGen; + } - } - createdResourceInstance.setGroupInstances(groupInstancesList); - } - } + public Supplier> getSomeValueDataClassGen() { + return someValueDataClassGen; + } + public NodeTypeEnum getNodeType() { + return nodeType; } - return Either.left(createdResourceInstance); - } - public void generateCustomizationUUID(ComponentInstance componentInstance) { - UUID uuid = UUID.randomUUID(); - componentInstance.setCustomizationUUID(uuid.toString()); + public NodeTypeEnum getNodeTypeValue() { + return nodeTypeValue; + } } /** + * update value of attribute on resource instance * - * @param containerComponentId - * @param containerNodeType - * @param instanceNumber - * @param isCreateLogicaName - * @param componentInstance - * @param compInstNodeType - * @param allowDeleted - * @param metadataVertex + * @param resourceInstanceAttribute + * @param resourceInstanceId * @return */ - public Either addComponentInstanceToContainerComponent(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, boolean isCreateLogicaName, ComponentInstance componentInstance, - NodeTypeEnum compInstNodeType, boolean allowDeleted, TitanVertex metadataVertex) { - TitanOperationStatus status; - log.debug("Going to create component instance {} in component {}", componentInstance, containerComponentId); - String instOriginComponentId = componentInstance.getComponentUid(); - String logicalName = componentInstance.getName(); - if (isCreateLogicaName) - logicalName = createComponentInstLogicalName(instanceNumber, componentInstance.getName()); + private Either updateAttributeOfResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId) { - ComponentInstanceData componentInstanceData = buildComponentInstanceData(componentInstance, containerComponentId, logicalName); - Either originVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), instOriginComponentId); - if (originVertexEither.isRight()) { - log.debug("Failed to fetch vertex of origin resource for id {} error {}", instOriginComponentId, originVertexEither.right().value()); - return Either.right(originVertexEither.right().value()); + Either result = null; + Wrapper errorWrapper = new Wrapper<>(); + UpdateDataContainer 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 updateRes = titanGenericDao.updateNode(attributeValueData, AttributeValueData.class); + if (updateRes.isRight()) { + TitanOperationStatus status = updateRes.right().value(); + errorWrapper.setInnerElement(status); + } else { + result = Either.left(updateRes.left().value()); + } } - TitanVertex originVertex = originVertexEither.left().value(); - - Boolean isDeleted = (Boolean) titanGenericDao.getProperty(metadataVertex, GraphPropertiesDictionary.IS_DELETED.getProperty()); - - if (!allowDeleted && (isDeleted != null) && (isDeleted == true)) { - log.debug("Component {} is already deleted. Cannot add component instance", instOriginComponentId); - return Either.right(TitanOperationStatus.INVALID_ID); + if (!errorWrapper.isEmpty()) { + result = Either.right(errorWrapper.getInnerElement()); } - String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty()); - String resourceType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty()); - - log.trace("Before adding component instance to graph. componentInstanceData = {}", componentInstanceData); + return result; - Either createCIResult = titanGenericDao.createNode(componentInstanceData); + } - log.debug("After adding component instance to graph. status is = {}", createCIResult); + private Either addAttributeToResourceInstance(ComponentInstanceProperty attributeInstanceProperty, String resourceInstanceId, Integer index) { + Wrapper errorWrapper = new Wrapper<>(); + Wrapper compInsWrapper = new Wrapper<>(); + Wrapper attDataWrapper = new Wrapper<>(); + Wrapper attValueDataWrapper = new Wrapper<>(); - if (createCIResult.isRight()) { - status = createCIResult.right().value(); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance"); - log.debug("Failed to create component instance node in graph. status is {}", status); - return Either.right(status); - } - TitanVertex createdComponentInstanceVertex = createCIResult.left().value(); - TitanOperationStatus associateContainerRes = associateContainerCompToComponentInstance(metadataVertex, createdComponentInstanceVertex, logicalName); + // Verify RI Exist + validateRIExist(resourceInstanceId, compInsWrapper, errorWrapper); - String componentInstanceUniqueId = componentInstanceData.getUniqueId(); - if (associateContainerRes != TitanOperationStatus.OK) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance"); - log.debug("Failed to associate container component {} to component instance {}. Status is {}", containerComponentId, componentInstanceUniqueId, associateContainerRes); - return Either.right(associateContainerRes); + if (errorWrapper.isEmpty()) { + // Verify Attribute Exist + validateElementExistInGraph(attributeInstanceProperty.getUniqueId(), NodeTypeEnum.Attribute, () -> AttributeData.class, attDataWrapper, errorWrapper); } - String originId = (String) titanGenericDao.getProperty(createdComponentInstanceVertex, GraphPropertiesDictionary.TYPE.getProperty()); - - TitanOperationStatus associateToInstOriginComponent = associateToInstOriginComponent(createdComponentInstanceVertex, originVertex, originId); - if (associateToInstOriginComponent != TitanOperationStatus.OK) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance"); - log.debug("Failed to associate component instance {} to its origin component {}. Status is {}", componentInstanceUniqueId, componentInstanceData.getComponentInstDataDefinition().getComponentUid(), associateToInstOriginComponent); - return Either.right(associateToInstOriginComponent); + if (errorWrapper.isEmpty()) { + // Create AttributeValueData that is connected to RI + createAttributeValueDataNode(attributeInstanceProperty, index, errorWrapper, compInsWrapper.getInnerElement(), attValueDataWrapper); } - - TitanOperationStatus associateCompInstToRequirements = associateCompInstToRequirements(createdComponentInstanceVertex, containerNodeType, compInstNodeType, originId); - if (associateCompInstToRequirements != TitanOperationStatus.OK) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance"); - log.debug("Failed to associate component instance {} to its origin requirements. Status is {}", componentInstanceUniqueId, associateCompInstToRequirements); - return Either.right(associateCompInstToRequirements); - } - TitanOperationStatus associateCompInstToCapabilities = associateCompInstToCapabilities(createdComponentInstanceVertex, containerNodeType, compInstNodeType, originId); - if (associateCompInstToCapabilities != TitanOperationStatus.OK) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance"); - log.debug("Failed to associate component instance {} to its origin capabilities. Status is {}", componentInstanceUniqueId, associateCompInstToCapabilities); - return Either.right(associateCompInstToCapabilities); - } - // Capability instance with property values implementation - Either>, TitanOperationStatus> cloneCapabilityInstancesRes = null; - Either, TitanOperationStatus> associateComponentInstanceToCapabilityInstancesRes; - status = null; - if (!isCreateLogicaName) { - // in case of cloning of component instance - log.debug("Before cloning of capability instances of component instance {}.", componentInstance.getUniqueId()); - cloneCapabilityInstancesRes = cloneCapabilityInstancesOfResourceInstance(createdComponentInstanceVertex, componentInstance); - if (cloneCapabilityInstancesRes.isRight() && !cloneCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - status = cloneCapabilityInstancesRes.right().value(); - log.debug("Failed to clone capability instances of component instance {}. Status is {}", componentInstance.getUniqueId(), status); - } - log.trace("After cloning of capability instances of component instance {}. Status is {}", componentInstance.getUniqueId(), status); - } else if (containerNodeType.equals(NodeTypeEnum.Resource) && componentInstance.getCapabilities() != null && !componentInstance.getCapabilities().isEmpty()) { - // in case of creation from scar - TitanOperationStatus addPropertiesRes = createCapabilityInstancesWithPropertyValues(createdComponentInstanceVertex, componentInstanceUniqueId, componentInstance.getCapabilities(), true); - if (addPropertiesRes != TitanOperationStatus.OK) { - status = addPropertiesRes; - log.debug("Failed to create capability instances with property values for component instance {}. Status is {}", componentInstance.getUniqueId(), status); - } - } - if (status == null && containerNodeType.equals(NodeTypeEnum.Service)) { - Map properties = titanGenericDao.getProperties(createdComponentInstanceVertex); - ComponentInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.ResourceInstance.getName(), GraphElementTypeEnum.Node, properties, ComponentInstanceData.class); - if (cloneCapabilityInstancesRes == null || cloneCapabilityInstancesRes.isRight()) { - // in case of creating of service - log.trace("Before associating component instance {} to capability instances .", componentInstance.getUniqueId()); - associateComponentInstanceToCapabilityInstancesRes = associateComponentInstanceToCapabilityInstancesOfResourceInstance(componentInstance); - if (associateComponentInstanceToCapabilityInstancesRes.isRight() && !associateComponentInstanceToCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - status = associateComponentInstanceToCapabilityInstancesRes.right().value(); - log.debug("Failed to associate capability instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status); - } - log.trace("After associating component instance {} to capability instances . Status is {}", componentInstance.getUniqueId(), status); - } else { - // in case of cloning of service - log.trace("Before associating created component instance {} to cloned capability instances.", componentInstanceUniqueId); - TitanOperationStatus associationStatus = associateCreatedComponentInstanceToClonedCapabilityInstances(createdComponentInstanceVertex, componentInstanceUniqueId, cloneCapabilityInstancesRes.left().value()); - if (associationStatus != TitanOperationStatus.OK && associationStatus != TitanOperationStatus.NOT_FOUND) { - status = associationStatus; - log.debug("Failed to associate capability instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status); - } - log.trace("After associating created component instance {} to cloned capability instances. Status is {}", componentInstanceUniqueId, status); - } - } - - if (status == null) { - // ComponentInstance createdResourceInstance = new - // ComponentInstance(createdComponentInstance.getComponentInstDataDefinition()); - // - // String icon = (String) titanGenericDao.getProperty(originVertex, - // GraphPropertiesDictionary.ICON.getProperty()); - // createdResourceInstance.setIcon(icon); - return Either.left(createdComponentInstanceVertex); - } - return Either.right(status); - } - - private Either>, TitanOperationStatus> createCapabilityInstancesWithPropertyValues(String resourceInstanceId, Map> capabilities, - boolean isNewlyCreatedResourceInstance) { - TitanOperationStatus error; - Map> result = new HashMap<>(); - for (Entry> capailityEntry : capabilities.entrySet()) { - CapabilityDefinition capability = capailityEntry.getValue().get(0); - if (capability.getProperties() != null && !capability.getProperties().isEmpty()) { - Either>, TitanOperationStatus> addPropertiesRes = addCapabilityPropertyValuesToResourceInstance(resourceInstanceId, capability, isNewlyCreatedResourceInstance); - if (addPropertiesRes.isRight()) { - error = addPropertiesRes.right().value(); - log.debug("Failed to add property values to capabilities of component instance {}. Status is {}", resourceInstanceId, error); - return Either.right(error); - } else { - result.putAll(addPropertiesRes.left().value()); - } - } - } - return Either.left(result); - } - - private TitanOperationStatus createCapabilityInstancesWithPropertyValues(TitanVertex resourceInstanceVertex, String resourceInstanceId, Map> capabilities, boolean isNewlyCreatedResourceInstance) { - TitanOperationStatus result = TitanOperationStatus.OK; - - for (Entry> capailityEntry : capabilities.entrySet()) { - CapabilityDefinition capability = capailityEntry.getValue().get(0); - if (capability.getProperties() != null && !capability.getProperties().isEmpty()) { - TitanOperationStatus addPropertiesRes = addCapabilityPropertyValuesToResourceInstance(resourceInstanceVertex, resourceInstanceId, capability, isNewlyCreatedResourceInstance); - if (addPropertiesRes != TitanOperationStatus.OK) { - result = addPropertiesRes; - log.debug("Failed to add property values to capabilities of component instance {}. Status is {}", resourceInstanceId, result); - return result; - } - } - } - return result; - } - - private Either, TitanOperationStatus> associateCreatedComponentInstanceToClonedCapabilityInstances(String newComponentResourceId, List> capabilityInstances) { - TitanOperationStatus error = null; - List relationsToCapabilityInstances = new ArrayList<>(); - UniqueIdData componentInstanceIdData = new UniqueIdData(NodeTypeEnum.ResourceInstance, newComponentResourceId); - for (ImmutablePair capInstPair : capabilityInstances) { - Either associateComponentInstanceToCapabilityinstanceRes = titanGenericDao.createRelation(componentInstanceIdData, capInstPair.getLeft(), GraphEdgeLabels.CAPABILITY_INST, - capInstPair.getRight().getProperties()); - if (associateComponentInstanceToCapabilityinstanceRes.isRight()) { - error = associateComponentInstanceToCapabilityinstanceRes.right().value(); - log.debug("Failed to associate capability instance {} to resource instance {} status is {}.", capInstPair.getLeft().getUniqueId(), newComponentResourceId, error); - break; - } else { - relationsToCapabilityInstances.add(associateComponentInstanceToCapabilityinstanceRes.left().value()); - } - } - if (error == null) { - return Either.left(relationsToCapabilityInstances); - } - return Either.right(error); - } - - private TitanOperationStatus associateCreatedComponentInstanceToClonedCapabilityInstances(TitanVertex riVertex, String newComponentResourceId, List> capabilityInstances) { - TitanOperationStatus error = null; - for (ImmutablePair capInstPair : capabilityInstances) { - TitanOperationStatus associateComponentInstanceToCapabilityinstanceRes = titanGenericDao.createEdge(riVertex, capInstPair.getLeft(), GraphEdgeLabels.CAPABILITY_INST, capInstPair.getRight().getProperties()); - if (associateComponentInstanceToCapabilityinstanceRes != TitanOperationStatus.OK) { - error = associateComponentInstanceToCapabilityinstanceRes; - log.debug("Failed to associate capability instance {} to resource instance {} status is {} .", capInstPair.getLeft(), newComponentResourceId, error); - break; - } - } - if (error == null) { - return TitanOperationStatus.OK; - } - return error; - } - - private Either, TitanOperationStatus> associateComponentInstanceToCapabilityInstancesOfResourceInstance(ComponentInstance componentInstance) { - TitanOperationStatus error = null; - String resourceId = componentInstance.getComponentUid(); - String componentResourceId = componentInstance.getUniqueId(); - UniqueIdData componentInstanceIdData = new UniqueIdData(NodeTypeEnum.ResourceInstance, componentResourceId); - List> resourceInstancesPair; - List> allCapabilityInstancesList = new ArrayList<>(); - List relationsToCapabilityInstances = new ArrayList<>(); - Either>, TitanOperationStatus> getAllResourceInstanceRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, - GraphEdgeLabels.RESOURCE_INST, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class); - if (getAllResourceInstanceRes.isRight() && !getAllResourceInstanceRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - error = getAllResourceInstanceRes.right().value(); - log.debug("Failed to retrieve resource instances from resource {} status is {}.", resourceId, error); - } - if (getAllResourceInstanceRes.isLeft()) { - resourceInstancesPair = getAllResourceInstanceRes.left().value(); - ComponentInstanceData ri; - for (ImmutablePair riPair : resourceInstancesPair) { - ri = riPair.getLeft(); - Either>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), ri.getUniqueId(), - GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class); - if (getCapabilityInstancesRes.isRight() && !getCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - error = getCapabilityInstancesRes.right().value(); - log.debug("Failed to retrieve capability instances of resource instance {} status is {}.", ri.getUniqueId(), error); - break; - } - if (getCapabilityInstancesRes.isLeft()) { - allCapabilityInstancesList.addAll(getCapabilityInstancesRes.left().value()); - } - } - } - if (error == null && !allCapabilityInstancesList.isEmpty()) { - for (ImmutablePair capInstPair : allCapabilityInstancesList) { - Either associateComponentInstanceToCapabilityinstanceRes = titanGenericDao.createRelation(componentInstanceIdData, capInstPair.getLeft(), GraphEdgeLabels.CAPABILITY_INST, - capInstPair.getRight().getProperties()); - if (associateComponentInstanceToCapabilityinstanceRes.isRight()) { - error = associateComponentInstanceToCapabilityinstanceRes.right().value(); - log.debug("Failed to associate capability instance {} to resource instance {} status is {}.", capInstPair.getLeft().getUniqueId(), componentResourceId, error); - break; - } else { - relationsToCapabilityInstances.add(associateComponentInstanceToCapabilityinstanceRes.left().value()); - } - } + if (errorWrapper.isEmpty()) { + // Connect AttributeValueData (Att on RI) to AttData (Att on + // Resource) + connectAttValueDataToAttData(errorWrapper, attDataWrapper.getInnerElement(), attValueDataWrapper.getInnerElement()); } - if (error == null) { - return Either.left(relationsToCapabilityInstances); + if (errorWrapper.isEmpty()) { + // Connect AttributeValueData to RI + connectAttValueDataToComponentInstanceData(errorWrapper, compInsWrapper.getInnerElement(), attValueDataWrapper.getInnerElement()); } - return Either.right(error); - } - private NodeTypeEnum detectOriginType(String label, ComponentInstanceData componentInstanceData, String resourceTypeStr) { - NodeTypeEnum res = null; - res = NodeTypeEnum.getByName(label); - switch (res) { - case Service: - componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.SERVICE); - break; - case Product: - componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.PRODUCT); - break; - case Resource: - ResourceTypeEnum resourceType = ResourceTypeEnum.valueOf(resourceTypeStr); - switch (resourceType) { - case VF: - componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VF); - break; - case VFC: - componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VFC); - break; - case VFCMT: - componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VFCMT); - break; - case CP: - componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.CP); - break; - case VL: - componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VL); - break; - case CVFC: - componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.CVFC); - break; - case PNF: - componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.PNF); - break; - - } - break; - default: - break; + if (errorWrapper.isEmpty()) { + return Either.left(attValueDataWrapper.getInnerElement()); + } else { + return Either.right(errorWrapper.getInnerElement()); } - return res; - } - - private Either associateToInstOriginComponent(ComponentInstanceData componentInstanceData, NodeTypeEnum compInstNodeType) { - - UniqueIdData resourceIdData = new UniqueIdData(compInstNodeType, componentInstanceData.getComponentInstDataDefinition().getComponentUid()); - Either createRelation = titanGenericDao.createRelation(componentInstanceData, resourceIdData, GraphEdgeLabels.INSTANCE_OF, null); - - log.debug("After associating resource instance {} to resource {}. status is {}", componentInstanceData.getUniqueId(), componentInstanceData.getComponentInstDataDefinition().getUniqueId(), createRelation); - - return createRelation; - } - - private TitanOperationStatus associateToInstOriginComponent(TitanVertex componentInstanceVertex, TitanVertex originVertex, String originId) { - - TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstanceVertex, originVertex, GraphEdgeLabels.INSTANCE_OF, null); - - log.debug("After associating resource instance {} to resource {}. status is {}", componentInstanceVertex, originId, createRelation); - - return createRelation; } - private Either, TitanOperationStatus> associateCompInstToRequirements(ComponentInstanceData componentInstanceData, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType) { - log.trace("Starting to copy origin component requirements to its component instance"); - String compInstOriginId = componentInstanceData.getComponentInstDataDefinition().getComponentUid(); - List graphRelations = new ArrayList<>(); - - // case of VFC / CP / VL - if (compInstNodeType.equals(NodeTypeEnum.Resource)) { - createRequirementRelationsFromAtomicResource(componentInstanceData, compInstOriginId, graphRelations); + private void preUpdateElementOfResourceInstanceValidations(UpdateDataContainer updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, + String resourceInstanceId, Wrapper errorWrapper) { + if (errorWrapper.isEmpty()) { + // Verify VFC instance Exist + validateRIExist(resourceInstanceId, errorWrapper); } - // case of VF / Service / Product - createCalculatedRequirementRelationsFromComponent(componentInstanceData, containerNodeType, compInstNodeType, graphRelations, compInstOriginId); - - log.trace("Finished to copy origin component requirements to its component instance, created {} new calculated requirement relations", graphRelations.size()); - return Either.left(graphRelations); - } - private TitanOperationStatus associateCompInstToRequirements(TitanVertex componentInstanceVertex, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, String originId) { - log.trace("Starting to copy origin component requirements to its component instance"); - TitanOperationStatus status = TitanOperationStatus.OK; - // case of VFC / CP / VL - if (compInstNodeType.equals(NodeTypeEnum.Resource)) { - status = createRequirementRelationsFromAtomicResource(componentInstanceVertex, originId); - if (!status.equals(TitanOperationStatus.OK)) { - log.debug("Failed create relation to requirement of origin {} error {}", originId, status); - return status; - } + if (errorWrapper.isEmpty()) { + // Example: Verify Property connected to VFC exist + validateElementConnectedToComponentExist(updateDataContainer, resourceInstanceProerty, errorWrapper); } - // case of VF / Service / Product - status = createCalculatedRequirementRelationsFromComponent(componentInstanceVertex, containerNodeType, compInstNodeType, originId); - - log.trace("Finished to copy origin component requirements to its component instance with status {}", status); - return status; - } - - private void createRequirementRelationsFromAtomicResource(ComponentInstanceData componentInstanceData, String compInstOriginId, List graphRelations) { - Map requirements = new HashMap(); - Set caseInsensitiveReqNames = new HashSet<>(); - TitanOperationStatus status = requirementOperation.findAllRequirementsRecursively(compInstOriginId, requirements, caseInsensitiveReqNames); - if (status != TitanOperationStatus.OK) { - log.debug("Couldn't fetch requirements of component {}, error: {}", compInstOriginId, status); + if (errorWrapper.isEmpty()) { + // Example: Verify PropertyValue connected to VFC Instance exist + validateElementConnectedToComponentInstanceExist(updateDataContainer, resourceInstanceProerty, errorWrapper); } - log.trace("Found {} requirements for component {}, ", requirements.size(), compInstOriginId); - for (Entry reqPair : requirements.entrySet()) { - RequirementDefinition requirementDef = reqPair.getValue(); - RequirementData requirementData = new RequirementData(); - requirementData.setUniqueId(requirementDef.getUniqueId()); - - log.trace("Creating calculated requirement relation from component instance {} to requirement {}", componentInstanceData.getUniqueId(), requirementDef.getUniqueId()); - Map props = new HashMap(); - props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), reqPair.getKey()); - - props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), componentInstanceData.getUniqueId()); - if (requirementDef.getMinOccurrences() == null) { - props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), RequirementDataDefinition.MIN_OCCURRENCES); - } else { - props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requirementDef.getMinOccurrences()); - } - if (requirementDef.getMaxOccurrences() == null) { - props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES); - } else { - props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), requirementDef.getMaxOccurrences()); - } - - Either createRelation = titanGenericDao.createRelation(componentInstanceData, requirementData, GraphEdgeLabels.CALCULATED_REQUIREMENT, props); - if (createRelation.isRight()) { - TitanOperationStatus titanOperationStatus = createRelation.right().value(); - log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", componentInstanceData.getUniqueId(), requirementDef.getUniqueId(), titanOperationStatus); - } - graphRelations.add(createRelation.left().value()); + if (errorWrapper.isEmpty()) { + // Example: Verify PropertyValue connected Property + validateElementConnectedToInstance(updateDataContainer, resourceInstanceProerty, errorWrapper); } } - private TitanOperationStatus createRequirementRelationsFromAtomicResource(TitanVertex componentInstanceVertex, String compInstOriginId) { - Map requirements = new HashMap(); - Set caseInsensitiveReqNames = new HashSet<>(); - - TitanOperationStatus status = requirementOperation.findAllRequirementsRecursively(compInstOriginId, requirements, caseInsensitiveReqNames); - if (status != TitanOperationStatus.OK && status != TitanOperationStatus.NOT_FOUND) { - log.debug("Couldn't fetch requirements of component {}, error: {}", compInstOriginId, status); - return status; - } - - String compoInstId = (String) titanGenericDao.getProperty(componentInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - log.trace("Found {} requirements for component {}, ", requirements.size(), compInstOriginId); - for (Entry reqPair : requirements.entrySet()) { - RequirementDefinition requirementDef = reqPair.getValue(); - RequirementData requirementData = new RequirementData(); - requirementData.setUniqueId(requirementDef.getUniqueId()); - - log.trace("Creating calculated requirement relation from component instance {} to requirement {}", compoInstId, requirementDef.getUniqueId()); - Map props = new HashMap(); - props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), reqPair.getKey()); - - props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), compoInstId); - if (requirementDef.getMinOccurrences() == null) { - props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), RequirementDataDefinition.MIN_OCCURRENCES); - } else { - props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requirementDef.getMinOccurrences()); - } - if (requirementDef.getMaxOccurrences() == null) { - props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES); - } else { - props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), requirementDef.getMaxOccurrences()); - } + private void validateElementConnectedToInstance(UpdateDataContainer updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, + Wrapper errorWrapper) { + Either, TitanOperationStatus> child = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), resourceInstanceProerty.getValueUniqueUid(), + updateDataContainer.getGraphEdge(), updateDataContainer.getNodeType(), updateDataContainer.getSomeDataClassGen().get()); - TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstanceVertex, requirementData, GraphEdgeLabels.CALCULATED_REQUIREMENT, props); - if (!createRelation.equals(TitanOperationStatus.OK)) { - log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", compoInstId, requirementDef.getUniqueId(), createRelation); - return createRelation; + if (child.isRight()) { + TitanOperationStatus status = child.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; } - } - return TitanOperationStatus.OK; - } - - private Either, TitanOperationStatus> associateCompInstToCapabilities(ComponentInstanceData componentInstanceData, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType) { - - log.trace("Starting to copy origin component capabilities to its component instance"); - List graphRelations = new ArrayList<>(); - - String compInstOriginId = componentInstanceData.getComponentInstDataDefinition().getComponentUid(); - - // case of VFC / CP / VL - if (compInstNodeType.equals(NodeTypeEnum.Resource)) { - createCaculatedRelationsFromAtomicResource(componentInstanceData, graphRelations, compInstOriginId); - } - - // case of VF / Service / Product - createCalculatedCapabilityRelationsFromComponent(componentInstanceData, containerNodeType, compInstNodeType, graphRelations, compInstOriginId); - - log.trace("Finished to copy origin component capabilities to its component instance, created {} new calculated capability relations", graphRelations.size()); - return Either.left(graphRelations); - } - - private TitanOperationStatus associateCompInstToCapabilities(TitanVertex componentInstanceVertex, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, String originId) { - - log.trace("Starting to copy origin component capabilities to its component instance"); - TitanOperationStatus status = TitanOperationStatus.OK; + errorWrapper.setInnerElement(status); - // case of VFC / CP / VL - if (compInstNodeType.equals(NodeTypeEnum.Resource)) { - status = createCaculatedRelationsFromAtomicResource(componentInstanceVertex, originId); - if (!status.equals(TitanOperationStatus.OK)) { - return status; - } + } else { + updateDataContainer.getDataWrapper().setInnerElement(child.left().value().left); } - - // case of VF / Service / Product - status = createCalculatedCapabilityRelationsFromComponent(componentInstanceVertex, containerNodeType, compInstNodeType, originId); - - return status; } - private void createCalculatedRequirementRelationsFromComponent(ComponentInstanceData componentInstanceData, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, List graphRelations, String compInstOriginId) { - - Either, List>, TitanOperationStatus> componentInstancesOfComponent = getComponentInstancesOfComponent(compInstOriginId, containerNodeType, compInstNodeType); - if (componentInstancesOfComponent.isLeft() && !componentInstancesOfComponent.left().value().left.isEmpty()) { - List componentInstances = componentInstancesOfComponent.left().value().left; - for (ComponentInstance componentInstance : componentInstances) { - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(containerNodeType), componentInstance.getUniqueId(), - GraphEdgeLabels.CALCULATED_REQUIREMENT, NodeTypeEnum.Requirement, RequirementData.class); - - if (childrenNodes.isLeft() && !childrenNodes.left().value().isEmpty()) { - List> list = childrenNodes.left().value(); - for (ImmutablePair calculatedReq : list) { - - GraphEdge edge = calculatedReq.right; - Map properties = edge.getProperties(); - String source = null; - String occurrences = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES; - String minOccurrences = RequirementDataDefinition.MIN_OCCURRENCES; - - if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) { - source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty()); - } - if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty())) { - occurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - } - if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) { - minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty()); - } - - String capabilityName = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty()); - Either createRelation = createCalculatedRequirementEdge(componentInstanceData, source, capabilityName, calculatedReq.left, componentInstance, occurrences, minOccurrences); - if (createRelation.isLeft()) { - graphRelations.add(createRelation.left().value()); - } - } + private void validateElementConnectedToComponentInstanceExist(UpdateDataContainer updateDataContainer, + IComponentInstanceConnectedElement resourceInstanceProerty, Wrapper errorWrapper) { + String valueUniqueUid = resourceInstanceProerty.getValueUniqueUid(); + if (valueUniqueUid == null) { + errorWrapper.setInnerElement(TitanOperationStatus.INVALID_ID); + } else { + Either 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 TitanOperationStatus createCalculatedRequirementRelationsFromComponent(TitanVertex componentInstanceVertex, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, String compInstOriginId) { - - Either, List>, TitanOperationStatus> componentInstancesOfComponent = getComponentInstancesOfComponent(compInstOriginId, containerNodeType, compInstNodeType); - if (componentInstancesOfComponent.isLeft() && !componentInstancesOfComponent.left().value().left.isEmpty()) { - List componentInstances = componentInstancesOfComponent.left().value().left; - for (ComponentInstance componentInstance : componentInstances) { - - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(containerNodeType), componentInstance.getUniqueId(), - GraphEdgeLabels.CALCULATED_REQUIREMENT); - - if (childrenNodes.isLeft() && !childrenNodes.left().value().isEmpty()) { - List> list = childrenNodes.left().value(); - for (ImmutablePair calculatedReq : list) { - - Edge edge = calculatedReq.right; - Map properties = titanGenericDao.getProperties(edge); - String source = null; - String occurrences = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES; - String minOccurrences = RequirementDataDefinition.MIN_OCCURRENCES; - - if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) { - source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty()); - } - if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty())) { - occurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - } - if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) { - minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty()); - } + private void validateElementConnectedToComponentExist(UpdateDataContainer updateDataContainer, + IComponentInstanceConnectedElement resourceInstanceElementConnected, Wrapper errorWrapper) { + String uniqueId = resourceInstanceElementConnected.getUniqueId(); + Either findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeType()), uniqueId, updateDataContainer.getSomeDataClassGen().get()); - String capabilityName = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty()); - TitanOperationStatus createRelation = createCalculatedRequirementEdge(componentInstanceVertex, source, capabilityName, calculatedReq.left, componentInstance, occurrences, minOccurrences); - if (!createRelation.equals(TitanOperationStatus.OK)) { - log.debug("Failed to create calculated requirement edge, status ", createRelation); - return createRelation; - } - } - } - } + if (findPropertyDefRes.isRight()) { + TitanOperationStatus status = findPropertyDefRes.right().value(); + errorWrapper.setInnerElement(status); } - return TitanOperationStatus.OK; } - private void createCalculatedCapabilityRelationsFromComponent(ComponentInstanceData componentInstanceData, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, List graphRelations, String compInstOriginId) { - - Either, List>, TitanOperationStatus> componentInstancesOfComponent = getComponentInstancesOfComponent(compInstOriginId, containerNodeType, compInstNodeType); - if (componentInstancesOfComponent.isLeft() && !componentInstancesOfComponent.left().value().left.isEmpty()) { - List componentInstances = componentInstancesOfComponent.left().value().left; - for (ComponentInstance componentInstance : componentInstances) { - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(compInstNodeType), componentInstance.getUniqueId(), - GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class); - - if (childrenNodes.isLeft() && !childrenNodes.left().value().isEmpty()) { - List> list = childrenNodes.left().value(); - for (ImmutablePair calculatedCap : list) { - - GraphEdge edge = calculatedCap.right; - Map properties = edge.getProperties(); - String source = null; - if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) { - source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty()); - } - String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES; - String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES; - if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) { - minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty()); - } - if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty())) { - occurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - } - - String capabilityName = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty()); - Either createRelation = createCalculatedCapabilityEdge(componentInstanceData, source, capabilityName, calculatedCap.left, componentInstance.getUniqueId(), minOccurrences, occurrences); - if (createRelation.isLeft()) { - graphRelations.add(createRelation.left().value()); - } - } - } - } - } + private void validateRIExist(String resourceInstanceId, Wrapper errorWrapper) { + validateRIExist(resourceInstanceId, null, errorWrapper); } - private TitanOperationStatus createCalculatedCapabilityRelationsFromComponent(TitanVertex componentInstanceVertex, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, String compInstOriginId) { - - Either, List>, TitanOperationStatus> componentInstancesOfComponent = getComponentInstancesOfComponent(compInstOriginId, containerNodeType, compInstNodeType); - if (componentInstancesOfComponent.isLeft() && !componentInstancesOfComponent.left().value().left.isEmpty()) { - List componentInstances = componentInstancesOfComponent.left().value().left; - for (ComponentInstance componentInstance : componentInstances) { - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(compInstNodeType), componentInstance.getUniqueId(), - GraphEdgeLabels.CALCULATED_CAPABILITY); - - if (childrenNodes.isLeft() && !childrenNodes.left().value().isEmpty()) { - List> list = childrenNodes.left().value(); - for (ImmutablePair calculatedCap : list) { - - Edge edge = calculatedCap.right; - Map properties = titanGenericDao.getProperties(edge); - String source = null; - if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) { - source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty()); - } - String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES; - String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES; - if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) { - minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty()); - } - if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty())) { - occurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - } - - String capabilityName = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty()); - TitanOperationStatus createRelation = createCalculatedCapabilityEdge(componentInstanceVertex, source, capabilityName, calculatedCap.left, componentInstance.getUniqueId(), minOccurrences, occurrences); - if (!createRelation.equals(TitanOperationStatus.OK)) { - return createRelation; - } - } - } - } - } - return TitanOperationStatus.OK; + private void validateRIExist(String resourceInstanceId, Wrapper compInsDataWrapper, Wrapper errorWrapper) { + validateElementExistInGraph(resourceInstanceId, NodeTypeEnum.ResourceInstance, () -> ComponentInstanceData.class, compInsDataWrapper, errorWrapper); } - private void createCaculatedRelationsFromAtomicResource(ComponentInstanceData componentInstanceData, List graphRelations, String compInstOriginId) { - - Map capabilities = new HashMap(); - Set caseInsensitiveCapNames = new HashSet<>(); - TitanOperationStatus getAllCapabilities = capabilityOperation.getAllCapabilitiesRecusive(NodeTypeEnum.Resource, compInstOriginId, true, capabilities, caseInsensitiveCapNames, true); - - if (!getAllCapabilities.equals(TitanOperationStatus.OK)) { - if (getAllCapabilities != TitanOperationStatus.NOT_FOUND) { - log.debug("Couldn't fetch capabilities of component {}, error: {}", compInstOriginId, getAllCapabilities); - return; - } - } - log.trace("Found {} capabilities for component {}, ", capabilities.size(), compInstOriginId); - for (Entry capPair : capabilities.entrySet()) { - CapabilityDefinition capabilityData = capPair.getValue(); - log.trace("Creating calculated capability relation from component instance {} to capability {}", componentInstanceData.getUniqueId(), capabilityData.getUniqueId()); - CapabilityData capabilityDataNode = new CapabilityData(); - capabilityDataNode.setUniqueId(capabilityData.getUniqueId()); - String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES; - String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES; - if (capabilityData.getMinOccurrences() != null) { - minOccurrences = capabilityData.getMinOccurrences(); + public void validateElementExistInGraph(String elementUniqueId, NodeTypeEnum elementNodeType, Supplier> elementClassGen, Wrapper elementDataWrapper, + Wrapper errorWrapper) { + Either 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; } - if (capabilityData.getMinOccurrences() != null) { - occurrences = capabilityData.getMaxOccurrences(); + errorWrapper.setInnerElement(status); + } else { + if (elementDataWrapper != null) { + elementDataWrapper.setInnerElement(findResInstanceRes.left().value()); } - - Either createRelation = createCalculatedCapabilityEdge(componentInstanceData, compInstOriginId, capPair.getKey(), capabilityDataNode, componentInstanceData.getUniqueId(), minOccurrences, occurrences); - graphRelations.add(createRelation.left().value()); } } - private TitanOperationStatus createCaculatedRelationsFromAtomicResource(TitanVertex componentInstanceVertex, String compInstOriginId) { + /** + * add property to resource instance + * + * @param resourceInstanceId + * @param index + * @return + */ + private Either addInputToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index) { - Map capabilities = new HashMap(); - Set caseInsensitiveCapNames = new HashSet<>(); - TitanOperationStatus getAllCapabilities = capabilityOperation.getAllCapabilitiesRecusive(NodeTypeEnum.Resource, compInstOriginId, true, capabilities, caseInsensitiveCapNames, true); + Either findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class); - if (!getAllCapabilities.equals(TitanOperationStatus.OK)) { - if (getAllCapabilities != TitanOperationStatus.NOT_FOUND) { - log.debug("Couldn't fetch capabilities of component {}, error: {}", compInstOriginId, getAllCapabilities); + if (findResInstanceRes.isRight()) { + TitanOperationStatus status = findResInstanceRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; } + return Either.right(status); } - log.trace("Found {} capabilities for component {}, ", capabilities.size(), compInstOriginId); - String compoInstId = (String) titanGenericDao.getProperty(componentInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - for (Entry capPair : capabilities.entrySet()) { - CapabilityDefinition capabilityData = capPair.getValue(); - log.trace("Creating calculated capability relation from component instance {} to capability {}", compoInstId, capabilityData.getUniqueId()); - CapabilityData capabilityDataNode = new CapabilityData(); - capabilityDataNode.setUniqueId(capabilityData.getUniqueId()); - String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES; - String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES; - if (capabilityData.getMinOccurrences() != null) { - minOccurrences = capabilityData.getMinOccurrences(); - } - if (capabilityData.getMinOccurrences() != null) { - occurrences = capabilityData.getMaxOccurrences(); - } + String propertyId = resourceInstanceInput.getUniqueId(); + Either findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Input), propertyId, InputsData.class); - TitanOperationStatus createRelation = createCalculatedCapabilityEdge(componentInstanceVertex, compInstOriginId, capPair.getKey(), capabilityDataNode, compoInstId, minOccurrences, occurrences); - if (!createRelation.equals(TitanOperationStatus.OK)) { - return createRelation; + if (findPropertyDefRes.isRight()) { + TitanOperationStatus status = findPropertyDefRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; } + return Either.right(status); } - return TitanOperationStatus.OK; - } - - private Either createCalculatedCapabilityEdge(ComponentInstanceData componentInstanceData, String compInstOriginId, String capabilityName, CapabilityData capabilityDataNode, String componentInstanceId, - String minOccurrences, String occurrences) { - Map props = prepareEdgeCapabiltyProperites(compInstOriginId, capabilityName, componentInstanceId, minOccurrences, occurrences); - - Either createRelation = titanGenericDao.createRelation(componentInstanceData, capabilityDataNode, GraphEdgeLabels.CALCULATED_CAPABILITY, props); - if (createRelation.isRight()) { - TitanOperationStatus titanOperationStatus = createRelation.right().value(); - log.debug("Failed to create calculated capability from component instance {} to capability {}, error: {}", componentInstanceData.getUniqueId(), capabilityDataNode.getUniqueId(), titanOperationStatus); - return Either.right(titanOperationStatus); - } - return createRelation; - } - - private TitanOperationStatus createCalculatedCapabilityEdge(TitanVertex componentInstanceVertex, String compInstOriginId, String capabilityName, CapabilityData capabilityDataNode, String componentInstanceId, String minOccurrences, - String occurrences) { - Map props = prepareEdgeCapabiltyProperites(compInstOriginId, capabilityName, componentInstanceId, minOccurrences, occurrences); - - TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstanceVertex, capabilityDataNode, GraphEdgeLabels.CALCULATED_CAPABILITY, props); - if (!createRelation.equals(TitanOperationStatus.OK)) { - log.debug("Failed to create calculated capability from component instance {} to capability {}, error: {}", componentInstanceId, capabilityDataNode.getUniqueId(), createRelation); - } - return createRelation; - } - - private TitanOperationStatus createCalculatedCapabilityEdge(TitanVertex componentInstanceVertex, String compInstOriginId, String capabilityName, TitanVertex capabilityDataVertex, String componentInstanceId, String minOccurrences, - String occurrences) { - Map props = prepareEdgeCapabiltyProperites(compInstOriginId, capabilityName, componentInstanceId, minOccurrences, occurrences); - - TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstanceVertex, capabilityDataVertex, GraphEdgeLabels.CALCULATED_CAPABILITY, props); - if (!createRelation.equals(TitanOperationStatus.OK)) { - log.debug("Failed to create calculated capability from component instance {} to capability {}, error: {}", componentInstanceId, capabilityName, createRelation); - } - return createRelation; - } - - private Map prepareEdgeCapabiltyProperites(String compInstOriginId, String capabilityName, String componentInstanceId, String minOccurrences, String occurrences) { - Map props = new HashMap(); - if (capabilityName != null) - props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capabilityName); - if (compInstOriginId != null) - props.put(GraphEdgePropertiesDictionary.SOURCE.getProperty(), compInstOriginId); - if (componentInstanceId != null) { - props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), componentInstanceId); - } - props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), minOccurrences); - props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), occurrences); - return props; - } - - private Either createCalculatedRequirementEdge(ComponentInstanceData componentInstanceData, String compInstOriginId, String capabilityName, RequirementData requirementData, ComponentInstance componentInstance, - String occurrences, String minOccurrences) { - Map props = new HashMap(); - if (capabilityName != null) - props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capabilityName); - if (compInstOriginId != null) - props.put(GraphEdgePropertiesDictionary.SOURCE.getProperty(), compInstOriginId); - if (componentInstance != null) { - props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), componentInstance.getUniqueId()); - } - props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), occurrences); - props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), minOccurrences); - - Either createRelation = titanGenericDao.createRelation(componentInstanceData, requirementData, GraphEdgeLabels.CALCULATED_REQUIREMENT, props); - if (createRelation.isRight()) { - TitanOperationStatus titanOperationStatus = createRelation.right().value(); - log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", componentInstanceData.getUniqueId(), requirementData.getUniqueId(), titanOperationStatus); - return Either.right(titanOperationStatus); - } - return createRelation; - } - - private TitanOperationStatus createCalculatedRequirementEdge(TitanVertex componentInstanceVertex, String compInstOriginId, String capabilityName, TitanVertex requirementVertex, ComponentInstance componentInstance, String occurrences, - String minOccurrences) { - Map props = new HashMap(); - if (capabilityName != null) - props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capabilityName); - if (compInstOriginId != null) - props.put(GraphEdgePropertiesDictionary.SOURCE.getProperty(), compInstOriginId); - if (componentInstance != null) { - props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), componentInstance.getUniqueId()); - } - props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), occurrences); - props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), minOccurrences); - - TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstanceVertex, requirementVertex, GraphEdgeLabels.CALCULATED_REQUIREMENT, props); - if (!createRelation.equals(TitanOperationStatus.OK)) { - log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", componentInstance.getUniqueId(), capabilityName, createRelation); - return createRelation; - } - return createRelation; - } - - /** - * Make a relation between service to resource instance. - * - * @param containerCompIdData - * @param componentInstanceData - * @param logicalName - * @return - */ - private Either associateContainerCompToComponentInstance(UniqueIdData containerCompIdData, ComponentInstanceData componentInstanceData, String logicalName) { - Map properties = new HashMap(); - - properties.put(GraphPropertiesDictionary.NAME.getProperty(), logicalName); - Either createRelation = titanGenericDao.createRelation(containerCompIdData, componentInstanceData, GraphEdgeLabels.RESOURCE_INST, properties); - log.debug("After associating container component {} to resource instance {} with logical name {}. Status is {}", containerCompIdData.getUniqueId(), componentInstanceData.getUniqueId(), logicalName, createRelation); - - return createRelation; - } - - private TitanOperationStatus associateContainerCompToComponentInstance(TitanVertex containerCompVertex, TitanVertex componentInstanceVertex, String logicalName) { - Map properties = new HashMap(); - - properties.put(GraphPropertiesDictionary.NAME.getProperty(), logicalName); - TitanOperationStatus createRelation = titanGenericDao.createEdge(containerCompVertex, componentInstanceVertex, GraphEdgeLabels.RESOURCE_INST, properties); - - return createRelation; - } - - @Override - public String createComponentInstLogicalName(String instanceNumber, String componentInstanceName) { - - String logicalName = buildComponentInstanceLogicalName(instanceNumber, componentInstanceName); - - return logicalName; - } - - private String buildComponentInstanceLogicalName(String instanceNumber, String lastToken) { - return lastToken + " " + (instanceNumber == null ? 0 : instanceNumber); - } - - private ComponentInstanceData buildComponentInstanceData(ComponentInstance resourceInstance, String componentId, String logicalName) { - - String ciOriginComponentUid = resourceInstance.getComponentUid(); - - ComponentInstanceDataDefinition dataDefinition = new ComponentInstanceDataDefinition(resourceInstance); - - Long creationDate = resourceInstance.getCreationTime(); - if (creationDate == null) { - creationDate = System.currentTimeMillis(); - } - dataDefinition.setCreationTime(creationDate); - dataDefinition.setModificationTime(creationDate); - // dataDefinition.setResourceUid(resourceUid); - // String replacmentlogicalName = logicalName.replaceAll(" ", - // "_").toLowerCase(); - dataDefinition.setName(logicalName); - if (dataDefinition.getNormalizedName() == null) - dataDefinition.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(logicalName)); - dataDefinition.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(componentId, ciOriginComponentUid, dataDefinition.getNormalizedName())); - - ComponentInstanceData resourceInstanceData = new ComponentInstanceData(dataDefinition); - - return resourceInstanceData; - } - - public Either removeComponentInstanceFromComponent(NodeTypeEnum containerNodeType, String containerComponentId, String componentInstanceUid) { - - log.debug("Going to delete component instance {} under component {}", componentInstanceUid, containerComponentId); - - Either node = findResourceInstance(componentInstanceUid); - - if (node.isRight()) { - TitanOperationStatus status = node.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Remove Component Instance"); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Remove Component Instance"); - log.debug("Failed to delete component instance {}. status is {}", componentInstanceUid, status); - return Either.right(status); - } - - TitanOperationStatus isComponentInstOfComponent = verifyResourceInstanceUnderComponent(containerNodeType, containerComponentId, componentInstanceUid); - if (isComponentInstOfComponent != TitanOperationStatus.OK) { - return Either.right(isComponentInstOfComponent); - } - - TitanOperationStatus status = deleteOutgoingRelationships(containerNodeType, containerComponentId, componentInstanceUid); - if (status != TitanOperationStatus.OK) { - return Either.right(status); - } - status = deleteIncomingRelationships(containerNodeType, containerComponentId, componentInstanceUid); - if (status != TitanOperationStatus.OK) { - return Either.right(status); - } - - // delete associated properties - status = deleteAssociatedProperties(componentInstanceUid); - if (status != TitanOperationStatus.OK) { - return Either.right(status); - } - // delete associated properties - status = deleteAssociatedAttributes(componentInstanceUid); - if (status != TitanOperationStatus.OK) { - return Either.right(status); - } - - // delete associated artifacts - status = deleteAssociatedArtifacts(componentInstanceUid); - if (status != TitanOperationStatus.OK) { - return Either.right(status); - } - - // delete associated capability instances - if (containerNodeType.equals(NodeTypeEnum.Resource)) { - status = deleteAssociatedCapabilityInstances(componentInstanceUid); - if (status != TitanOperationStatus.OK) { - return Either.right(status); - } - } - - // delete associated properties - status = deleteAssociatedGroupInstances(componentInstanceUid); - if (status != TitanOperationStatus.OK) { - return Either.right(status); - } - - Either deleteRI = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), componentInstanceUid, ComponentInstanceData.class); - - if (deleteRI.isRight()) { - TitanOperationStatus deleteRiStatus = deleteRI.right().value(); - log.error("Failed to delete resource instance {}. status is {}", componentInstanceUid, deleteRiStatus); - return Either.right(deleteRiStatus); - } - - ComponentInstanceData deletedResourceInst = deleteRI.left().value(); - - ComponentInstance resourceInstance = new ComponentInstance(deletedResourceInst.getComponentInstDataDefinition()); - - return Either.left(resourceInstance); - } - - private TitanOperationStatus deleteAssociatedGroupInstances(String componentInstanceUid) { - - return this.groupInstanceOperation.deleteAllGroupInstances(componentInstanceUid); - } - - private TitanOperationStatus deleteAssociatedCapabilityInstances(String resourceInstanceId) { - TitanOperationStatus status = TitanOperationStatus.OK; - - log.debug("Before deleting all capability instances of component istance {}.", resourceInstanceId); - Either>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, - GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class); - - if (getCapabilityInstancesRes.isRight() && !getCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - status = getCapabilityInstancesRes.right().value(); - log.debug("Failed to retrieve capability Instances of resource instance {}. Status is {}", resourceInstanceId, status); - } - if (getCapabilityInstancesRes.isLeft()) { - for (ImmutablePair capabilityInstancePair : getCapabilityInstancesRes.left().value()) { - Either deleteCababilityInstanceRes = capabilityInstanceOperation.deleteCapabilityInstanceFromResourceInstance(resourceInstanceId, capabilityInstancePair.getLeft().getUniqueId()); - if (deleteCababilityInstanceRes.isRight()) { - status = deleteCababilityInstanceRes.right().value(); - } - } - } - log.debug("After deleting all capability instances of component istance {}. Status is {}", resourceInstanceId, status); - return status; - } - - private TitanOperationStatus deleteAssociatedArtifacts(String resourceInstanceUid) { - - Either>, TitanOperationStatus> artifactRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid, GraphEdgeLabels.ARTIFACT_REF, - NodeTypeEnum.ArtifactRef, ArtifactData.class); - - if (artifactRes.isRight()) { - TitanOperationStatus status = artifactRes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find artifacts of resource instance {}. status is {}", resourceInstanceUid, status); - return status; - } - } else { - - List> artifactPairs = artifactRes.left().value(); - for (ImmutablePair pair : artifactPairs) { - String uniqueId = (String) pair.left.getUniqueId(); - Either removeArifactFromGraph = artifactOperation.removeArtifactOnGraph(resourceInstanceUid, uniqueId, NodeTypeEnum.ResourceInstance, true); - if (removeArifactFromGraph.isRight()) { - TitanOperationStatus status = removeArifactFromGraph.right().value(); - log.error("Failed to delete artifact of resource instance {}. status is {}", resourceInstanceUid, status); - return status; - } - - } - } - - return TitanOperationStatus.OK; - - } - - private TitanOperationStatus deleteAssociatedProperties(String resourceInstanceUid) { - final GraphEdgeLabels edgeConectingToRI = GraphEdgeLabels.PROPERTY_VALUE; - final NodeTypeEnum elementTypeToDelete = NodeTypeEnum.PropertyValue; - return deleteAssociatedRIElements(elementTypeToDelete, edgeConectingToRI, resourceInstanceUid, () -> PropertyValueData.class); - - } - - private TitanOperationStatus deleteAssociatedAttributes(String resourceInstanceUid) { - final GraphEdgeLabels edgeConectingToRI = GraphEdgeLabels.ATTRIBUTE_VALUE; - final NodeTypeEnum elementTypeToDelete = NodeTypeEnum.AttributeValue; - return deleteAssociatedRIElements(elementTypeToDelete, edgeConectingToRI, resourceInstanceUid, () -> AttributeValueData.class); - } - - private TitanOperationStatus deleteAssociatedRIElements(NodeTypeEnum elementTypeToDelete, GraphEdgeLabels edgeConectingToRI, String resourceInstanceUid, Supplier> classGen) { - - Either>, TitanOperationStatus> elementsNodesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid, edgeConectingToRI, elementTypeToDelete, - classGen.get()); - - if (elementsNodesRes.isRight()) { - TitanOperationStatus status = elementsNodesRes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logInternalFlowError("deleteAssociatedRIElements", "Failed to find the elements of resource instance " + resourceInstanceUid + ". status is " + status, ErrorSeverity.ERROR); - return status; - } - } else { - - List> relationshipNodes = elementsNodesRes.left().value(); - if (relationshipNodes != null) { - for (ImmutablePair immutablePair : relationshipNodes) { - T elementValueDataData = immutablePair.getKey(); - Either deleteNode = titanGenericDao.deleteNode(elementValueDataData, classGen.get()); - if (deleteNode.isRight()) { - TitanOperationStatus status = deleteNode.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("deleteAssociatedRIElements", "Failed to delete element value node " + elementValueDataData + ". status is " + status, ErrorSeverity.ERROR); - return status; - } - } - } - - } - - return TitanOperationStatus.OK; - } - - /** - * delete all relationship instance nodes which has an outgoing edge to a given resource instance - * - * @param resourceInstanceUid - * @return - */ - private TitanOperationStatus deleteIncomingRelationships(NodeTypeEnum componentType, String componentId, String resourceInstanceUid) { - - Either, TitanOperationStatus> relationsForTarget = getRelationsForTarget(resourceInstanceUid); - if (relationsForTarget.isRight()) { - TitanOperationStatus status = relationsForTarget.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find the relationships of resource instance {}. status is {}", resourceInstanceUid, status); - return status; - } - } else { - List relList = relationsForTarget.left().value(); - for (RequirementCapabilityRelDef relation : relList) { - Either dissociateResourceInstances = dissociateResourceInstances(componentId, componentType, relation, true); - if (dissociateResourceInstances.isRight()) { - log.error("failed to diassociate component instance {} and component instance {} under component {}. error is {}", relation.getFromNode(), relation.getToNode(), componentId); - return TitanOperationStatus.GENERAL_ERROR; - } - } - } - return TitanOperationStatus.OK; - } - - /** - * delete all relationship instance nodes which has an incoming edge from a given resource instance - * - * @param resourceInstanceUid - * @return - */ - private TitanOperationStatus deleteOutgoingRelationships(NodeTypeEnum componentType, String componentId, String resourceInstanceUid) { - - Either, TitanOperationStatus> relationsForSource = getRelationsForSource(resourceInstanceUid); - if (relationsForSource.isRight()) { - TitanOperationStatus status = relationsForSource.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find the relationships of resource instance {}. status is {}", resourceInstanceUid, status); - return status; - } - } else { - List relList = relationsForSource.left().value(); - for (RequirementCapabilityRelDef relation : relList) { - Either dissociateResourceInstances = dissociateResourceInstances(componentId, componentType, relation, true); - if (dissociateResourceInstances.isRight()) { - log.error("failed to diassociate component instance {} and component instance {} under component {}. error is {}", relation.getFromNode(), relation.getToNode(), componentId); - return TitanOperationStatus.GENERAL_ERROR; - } - } - } - return TitanOperationStatus.OK; - } - - /** - * delete relationship instance nodes - * - * @param relationshipNodes - * @return - */ - private TitanOperationStatus deleteRelationshipNodes(List> relationshipNodes) { - - if (relationshipNodes != null) { - for (ImmutablePair immutablePair : relationshipNodes) { - RelationshipInstData relationshipTypeImplData = immutablePair.getKey(); - Either deleteNode = titanGenericDao.deleteNode(relationshipTypeImplData, RelationshipInstData.class); - if (deleteNode.isRight()) { - TitanOperationStatus status = deleteNode.right().value(); - log.error("Failed to delete relationship node {}. status is {}", relationshipTypeImplData, status); - return status; - } - } - } - - return TitanOperationStatus.OK; - } - - public Either, TitanOperationStatus> disconnectResourcesInService(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef) { - - if (requirementDef.getRelationships() == null) { - log.debug("No relation pair in request [ {} ]", requirementDef); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - - String fromResInstanceUid = requirementDef.getFromNode(); - String toResInstanceUid = requirementDef.getToNode(); - - // DE191707 - TitanOperationStatus isResourceInstOfService = verifyResourceInstanceUnderComponent(nodeType, componentId, fromResInstanceUid); - if (isResourceInstOfService != TitanOperationStatus.OK) { - return Either.right(isResourceInstOfService); - } - isResourceInstOfService = verifyResourceInstanceUnderComponent(nodeType, componentId, toResInstanceUid); - if (isResourceInstOfService != TitanOperationStatus.OK) { - return Either.right(isResourceInstOfService); - } - - List relationPairList = requirementDef.getRelationships(); - - Either riFrom = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), fromResInstanceUid); - if (riFrom.isRight()) { - log.debug("Failed to fetch component instance {}. error {}", fromResInstanceUid, riFrom.right().value()); - return Either.right(riFrom.right().value()); - } - Iterator edgeIter = riFrom.left().value().edges(Direction.OUT, GraphEdgeLabels.RELATIONSHIP_INST.getProperty()); - if (edgeIter == null) { - log.debug("No edges with label {} for owner RI {}", GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED.getProperty(), fromResInstanceUid); - return Either.right(TitanOperationStatus.NOT_FOUND); - } - List deletedRelations = new ArrayList<>(); - Set vertexToDelete = new HashSet(); - while (edgeIter.hasNext()) { - TitanEdge edge = (TitanEdge) edgeIter.next(); - String name = (String) edge.property(GraphEdgePropertiesDictionary.NAME.getProperty()).value(); - for (RequirementAndRelationshipPair relationPair : relationPairList) { - if (relationPair.getRequirement().equals(name)) { - TitanVertex inVertex = edge.inVertex(); - String requirementId = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.REQUIREMENT_ID.getProperty()); - String capabiltyId = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.CAPABILITY_ID.getProperty()); - String requirementOwnerId = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.REQUIREMENT_OWNER_ID.getProperty()); - String capabiltyOwnerId = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.CAPABILITY_OWNER_ID.getProperty()); - String relationVertexId = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - - // verify vs requirement id and owner ids. ( for - // requirements with same name) - if (requirementId.equals(relationPair.getRequirementUid()) && capabiltyId.equals(relationPair.getCapabilityUid()) && requirementOwnerId.equals(relationPair.getRequirementOwnerId()) - && capabiltyOwnerId.equals(relationPair.getCapabilityOwnerId())) { - vertexToDelete.add(relationVertexId); - } - } - } - } - log.debug("relation node with ids: {} are going to be deleted", vertexToDelete); - for (String relationVertexId : vertexToDelete) { - // remove relation vertex - Either relationNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipInst), relationVertexId, RelationshipInstData.class); - if (relationNode.isRight()) { - log.debug("Failed to delete relation node with id {}. error {}", relationVertexId, relationNode.right().value()); - return Either.right(relationNode.right().value()); - } - RelationshipInstData deletedRelation = relationNode.left().value(); - deletedRelations.add(deletedRelation); - } - if (deletedRelations.size() > 0) { - return Either.left(deletedRelations); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - @Override - public Either dissociateResourceInstances(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef, boolean inTransaction) { - - String fromResInstanceUid = requirementDef.getFromNode(); - String toResInstanceUid = requirementDef.getToNode(); - String requirement = requirementDef.getRelationships().get(0).getRequirement(); - Either result = null; - try { - - Either, TitanOperationStatus> dissociateRes = disconnectResourcesInService(componentId, nodeType, requirementDef); - if (dissociateRes.isRight()) { - TitanOperationStatus status = dissociateRes.right().value(); - log.error("Failed to dissociate resource instance {} from resource instance {} in service {}. status is {}", fromResInstanceUid, toResInstanceUid, componentId, status); - BeEcompErrorManager.getInstance().logBeDaoSystemError("dissociateComponentInstances"); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - StorageOperationStatus updateCalculatedCapReqResult = updateCalculatedCapReq(requirementDef, false); - if (!updateCalculatedCapReqResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "dissociateComponentInstances"); - BeEcompErrorManager.getInstance().logBeDaoSystemError("dissociateComponentInstances"); - log.debug("Failed to dissociate component instances. {}. status is {}", requirementDef, updateCalculatedCapReqResult); - result = Either.right(updateCalculatedCapReqResult); - return result; - } - - StorageOperationStatus status; - status = updateCustomizationUUID(requirementDef.getFromNode()); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - return result; - } - status = updateCustomizationUUID(requirementDef.getToNode()); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - return result; - } - - List relationshipInstData = dissociateRes.left().value(); - RequirementCapabilityRelDef capabilityRelDef = buildCapabilityResult(fromResInstanceUid, toResInstanceUid, requirement, relationshipInstData); - - result = Either.left(capabilityRelDef); - - return result; - - } finally { - if (false == inTransaction) { - commitOrRollback(result); - } - } - - } - - private StorageOperationStatus updateCalculatedCapReq(RequirementCapabilityRelDef capabilityRelDef, boolean associate) { - GraphEdgeLabels requirmentNewLabel = associate ? GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED : GraphEdgeLabels.CALCULATED_REQUIREMENT; - - GraphEdgeLabels requirmentCurrentLabel = associate ? GraphEdgeLabels.CALCULATED_REQUIREMENT : GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED; - - GraphEdgeLabels capabilityNewLabel = associate ? GraphEdgeLabels.CALCULATED_CAPABILITY_FULLFILLED : GraphEdgeLabels.CALCULATED_CAPABILITY; - - GraphEdgeLabels capabilityCurrentLabel = associate ? GraphEdgeLabels.CALCULATED_CAPABILITY : GraphEdgeLabels.CALCULATED_CAPABILITY_FULLFILLED; - - List relationships = capabilityRelDef.getRelationships(); - for (RequirementAndRelationshipPair pair : relationships) { - StorageOperationStatus status = updateRequirementEdges(requirmentNewLabel, requirmentCurrentLabel, pair, capabilityRelDef.getFromNode()); - if (!status.equals(StorageOperationStatus.OK)) { - return status; - } - status = updateCapabiltyEdges(capabilityNewLabel, capabilityCurrentLabel, pair, capabilityRelDef.getToNode()); - if (!status.equals(StorageOperationStatus.OK)) { - return status; - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus updateRequirementEdges(GraphEdgeLabels requirmentNewLabel, GraphEdgeLabels requirmentCurrentLabel, RequirementAndRelationshipPair pair, String requirementOwnerId) { - Either reqOwnerRI = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), requirementOwnerId); - if (reqOwnerRI.isRight()) { - log.debug("Failed to fetch requirment Owner by Id {} error {}", requirementOwnerId, reqOwnerRI.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(reqOwnerRI.right().value()); - } - Iterator edgeIter = reqOwnerRI.left().value().edges(Direction.OUT, requirmentCurrentLabel.name(), requirmentNewLabel.name()); - if (edgeIter == null) { - log.debug("No edges with label {} for owner RI {}", requirmentCurrentLabel, requirementOwnerId); - return StorageOperationStatus.GENERAL_ERROR; - } - boolean associate = requirmentNewLabel.equals(GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED) ? true : false; - while (edgeIter.hasNext()) { - TitanEdge edge = (TitanEdge) edgeIter.next(); - String name = (String) edge.property(GraphEdgePropertiesDictionary.NAME.getProperty()).value(); - if (pair.getRequirement().equals(name)) { - TitanVertex reqVertex = edge.inVertex(); - String requirementId = (String) titanGenericDao.getProperty(reqVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - // verify vs requirement id . ( for requirements with same name) - if (requirementId.equals(pair.getRequirementUid())) { - String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty()); - if (ownerIdOnEdge.equals(pair.getRequirementOwnerId())) { - String requiredOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty()); - String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - - String requiredOccurrencesNew = "0"; - String leftOccurrencesNew = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES; - if (requiredOccurrences != null) { - Integer iOccurrences = Integer.parseInt(requiredOccurrences); - if (associate) { - if (iOccurrences > 0) { - iOccurrences--; - requiredOccurrencesNew = iOccurrences.toString(); - } - } else { - String reqMinOccurrences = (String) titanGenericDao.getProperty(reqVertex, GraphPropertiesDictionary.MIN_OCCURRENCES.getProperty()); - if (reqMinOccurrences == null) { - reqMinOccurrences = RequirementDataDefinition.MIN_OCCURRENCES; - } - if (Integer.parseInt(reqMinOccurrences) > iOccurrences) { - iOccurrences++; - requiredOccurrencesNew = iOccurrences.toString(); - } - } - } - Map properties = titanGenericDao.getProperties(edge); - properties.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requiredOccurrencesNew); - - if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - Integer iOccurrences = Integer.parseInt(leftOccurrences); - if (associate) { - if (iOccurrences > 0) { - iOccurrences--; - } - } else { - iOccurrences++; - } - leftOccurrencesNew = iOccurrences.toString(); - properties.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), leftOccurrencesNew); - if ((associate && iOccurrences == 0) || (!associate && iOccurrences == 1)) { - // move edge to full filled state - TitanVertex outVertex = edge.outVertex(); - TitanEdge newEdge = outVertex.addEdge(requirmentNewLabel.getProperty(), reqVertex); - titanGenericDao.setProperties(newEdge, properties); - edge.remove(); - } else { - titanGenericDao.setProperties(edge, properties); - } - } else { - leftOccurrencesNew = leftOccurrences; - properties.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), leftOccurrencesNew); - titanGenericDao.setProperties(edge, properties); - } - break; - } - } - } - } - return StorageOperationStatus.OK; - - } - - private StorageOperationStatus updateCapabiltyEdges(GraphEdgeLabels capabiltyNewLabel, GraphEdgeLabels capabiltyCurrentLabel, RequirementAndRelationshipPair pair, String capabiltyOwnerId) { - Either capOwnerRI = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), capabiltyOwnerId); - if (capOwnerRI.isRight()) { - log.debug("Failed to fetch requirment Owner by Id {}. error {}", capabiltyOwnerId, capOwnerRI.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(capOwnerRI.right().value()); - } - Iterator edgeIter = capOwnerRI.left().value().edges(Direction.OUT, capabiltyCurrentLabel.name(), capabiltyNewLabel.name()); - if (edgeIter == null) { - log.debug("No edges with label {} for owner RI {}", capabiltyCurrentLabel, capabiltyOwnerId); - return StorageOperationStatus.GENERAL_ERROR; - } - boolean associate = capabiltyNewLabel.equals(GraphEdgeLabels.CALCULATED_CAPABILITY_FULLFILLED) ? true : false; - - while (edgeIter.hasNext()) { - TitanEdge edge = (TitanEdge) edgeIter.next(); - TitanVertex capVertex = edge.inVertex(); - // edge.property(GraphEdgePropertiesDictionary.NAME.getProperty()).value(); - - String capabiltyId = (String) titanGenericDao.getProperty(capVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - // verify vs capability id . ( for capabilty with same name) - if (capabiltyId.equals(pair.getCapabilityUid())) { - String ownerIdOnEdge = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.OWNER_ID.getProperty()); - if (ownerIdOnEdge.equals(pair.getCapabilityOwnerId())) { - - String requiredOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty()); - String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - - String requiredOccurrencesNew = "0"; - String leftOccurrencesNew = CapabilityDataDefinition.MAX_OCCURRENCES; - if (requiredOccurrences != null) { - Integer iOccurrences = Integer.parseInt(requiredOccurrences); - if (associate) { - if (iOccurrences > 0) { - iOccurrences--; - requiredOccurrencesNew = iOccurrences.toString(); - } - } else { - String reqMinOccurrences = (String) titanGenericDao.getProperty(capVertex, GraphPropertiesDictionary.MIN_OCCURRENCES.getProperty()); - if (reqMinOccurrences == null) { - reqMinOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES; - } - if (Integer.parseInt(reqMinOccurrences) > iOccurrences) { - iOccurrences++; - requiredOccurrencesNew = iOccurrences.toString(); - } - } - } - Map properties = titanGenericDao.getProperties(edge); - properties.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requiredOccurrencesNew); - - if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { - Integer iOccurrences = Integer.parseInt(leftOccurrences); - if (associate) { - if (iOccurrences > 0) { - iOccurrences--; - } - } else { - iOccurrences++; - } - leftOccurrencesNew = iOccurrences.toString(); - properties.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), leftOccurrencesNew); - if ((associate && iOccurrences == 0) || (!associate && iOccurrences == 1)) { - // move edge to full filled state - TitanVertex outVertex = edge.outVertex(); - TitanEdge newEdge = outVertex.addEdge(capabiltyNewLabel.getProperty(), capVertex); - titanGenericDao.setProperties(newEdge, properties); - edge.remove(); - } else { - titanGenericDao.setProperties(edge, properties); - } - } else { - properties.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), leftOccurrencesNew); - titanGenericDao.setProperties(edge, properties); - } - break; - } - } - } - return StorageOperationStatus.OK; - } - - @Override - public Either dissociateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef) { - - return dissociateResourceInstances(serviceId, nodeType, requirementDef, false); - } - - private RequirementCapabilityRelDef buildCapabilityResult(String fromResInstanceUid, String toResInstanceUid, String requirement, List relationshipInstDataList) { - - RequirementCapabilityRelDef capabilityRelDef = new RequirementCapabilityRelDef(); - capabilityRelDef.setFromNode(fromResInstanceUid); - capabilityRelDef.setToNode(toResInstanceUid); - List relationships = new ArrayList(); - for (RelationshipInstData relationshipInstData : relationshipInstDataList) { - RelationshipImpl relationshipImpl = new RelationshipImpl(); - relationshipImpl.setType(relationshipInstData.getType()); - RequirementAndRelationshipPair reqRel = new RequirementAndRelationshipPair(requirement, relationshipImpl); - capabilityRelDef.setRelationships(relationships); - reqRel.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId()); - reqRel.setCapabilityUid(relationshipInstData.getCapabiltyId()); - reqRel.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId()); - reqRel.setRequirementUid(relationshipInstData.getRequirementId()); - relationships.add(reqRel); - } - return capabilityRelDef; - - } - - public Either connectResourcesInService(String componentId, NodeTypeEnum nodeType, String fromResInstanceUid, String toResInstanceUid, RequirementAndRelationshipPair relationPair) { - String relationship = null; - String requirement = relationPair.getRequirement(); - if (relationPair.getRelationship() != null) { - relationship = relationPair.getRelationship().getType(); - } - - log.debug("Going to associate resource instance {} to resource instance {} under component {}. Requirement is {}.", fromResInstanceUid, toResInstanceUid, componentId, requirement); - - Either fromResourceInstDataRes = findMandatoryResourceInstData(fromResInstanceUid); - if (fromResourceInstDataRes.isRight()) { - TitanOperationStatus status = fromResourceInstDataRes.right().value(); - log.error("Failed to find resource instance {}. status is {}", fromResInstanceUid, status); - return Either.right(status); - } - ComponentInstanceData fromCI = fromResourceInstDataRes.left().value(); - ComponentInstanceData fromResourceInstanceData = fromCI; - Either toResourceInstDataRes = findMandatoryResourceInstData(toResInstanceUid); - if (toResourceInstDataRes.isRight()) { - TitanOperationStatus status = toResourceInstDataRes.right().value(); - log.error("Failed to find resource instance {}. status is {}", toResInstanceUid, status); - return Either.right(status); - } - ComponentInstanceData toCI = toResourceInstDataRes.left().value(); - ComponentInstanceData toResourceInstanceData = toCI; - // THE component NodeTypeEnum should be sent - TitanOperationStatus isResourceInstOfService = verifyResourceInstanceUnderComponent(nodeType, componentId, fromResInstanceUid); - if (isResourceInstOfService != TitanOperationStatus.OK) { - return Either.right(isResourceInstOfService); - } - isResourceInstOfService = verifyResourceInstanceUnderComponent(nodeType, componentId, toResInstanceUid); - if (isResourceInstOfService != TitanOperationStatus.OK) { - return Either.right(isResourceInstOfService); - } - - Either, TitanOperationStatus> isValidRes = validateRequirementVsCapability(fromResourceInstanceData, toResourceInstanceData, requirement, relationship, relationPair); - if (isValidRes.isRight()) { - TitanOperationStatus status = isValidRes.right().value(); - log.error("Failed to validate requirement {} between resource instance {} to resource instance {}. status is {}", requirement, fromResInstanceUid, toResInstanceUid, status); - return Either.right(status); - } - - RelationshipTypeData relationshipTypeData = isValidRes.left().value().getKey(); - String capabilityName = isValidRes.left().value().getValue(); - RelationshipInstData relationshipInstData = buildRelationshipInstData(fromResInstanceUid, requirement, relationshipTypeData, relationPair); - Either createNode = createRelationshipInstData(fromCI, relationshipInstData, relationshipTypeData, requirement); - - if (createNode.isRight()) { - return Either.right(createNode.right().value()); - } - RelationshipInstData createdRelInstData = createNode.left().value(); - Either associateResInst = associateRelationshipInstToTarget(toCI, requirement, capabilityName, createdRelInstData); - - if (associateResInst.isRight()) { - TitanOperationStatus status = associateResInst.right().value(); - log.error("Failed to associate relationship instance {} to target node {}. status is {}", createdRelInstData.getUniqueId(), toResInstanceUid, status); - return Either.right(status); - } - - return Either.left(createNode.left().value()); - } - - private TitanOperationStatus verifyResourceInstanceUnderComponent(NodeTypeEnum containerNodeType, String containerComponentId, String resInstanceUid) { - - Either, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resInstanceUid, GraphEdgeLabels.RESOURCE_INST, - containerNodeType, ComponentMetadataData.class); - - if (parentNode.isRight()) { - TitanOperationStatus status = parentNode.right().value(); - log.error("Failed to find the service associated to the resource instance {}. status is {}", resInstanceUid, status); - return status; - } - - ImmutablePair componentsRes = parentNode.left().value(); - ComponentMetadataData componentMetadataData = componentsRes.getKey(); - String uniqueId = (String) componentMetadataData.getUniqueId(); - - if (containerComponentId.equals(uniqueId)) { - return TitanOperationStatus.OK; - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeIncorrectServiceError, "Resource Instance - verifyResourceInstanceUnderComponent", containerComponentId); - BeEcompErrorManager.getInstance().logBeIncorrectComponentError("Resource Instance - verifyResourceInstanceUnderComponent", containerNodeType.getName(), containerComponentId); - log.debug("The provided component id {} is not equal to the component ({}) which associated to resource instance {}", containerComponentId, uniqueId, resInstanceUid); - return TitanOperationStatus.INVALID_ID; - } - - } - - /** - * find the resource instance node in graph. - * - * @param resInstanceUid - * @return - */ - private Either findMandatoryResourceInstData(String resInstanceUid) { - Either resStatus = findResourceInstance(resInstanceUid); - if (resStatus.isRight()) { - TitanOperationStatus status = resStatus.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - return Either.right(TitanOperationStatus.INVALID_ID); - } - return Either.right(status); - } - ComponentInstanceData riData = resStatus.left().value(); - return Either.left(riData); - } - - /** - * associate relationship instance node to the target resource instance node. - * - * @param toResInstance - * @param requirement - * @param relInstData - * @return - */ - private Either associateRelationshipInstToTarget(ComponentInstanceData toResInstance, String requirement, String capabilityName, RelationshipInstData relInstData) { - - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName); - Either createRelation = titanGenericDao.createRelation(relInstData, toResInstance, GraphEdgeLabels.CAPABILITY_NODE, props); - log.debug("After creatingrelation between relationship instance {} to target node {}", relInstData.getUniqueId(), toResInstance.getUniqueId()); - - return createRelation; - - } - - /** - * create reslationship instance node and associate the reosurce instance node to it. - * - * @param resInstance - * @param relationshipInstData - * @param relationshipTypeData - * @param requirementName - * @return - */ - private Either createRelationshipInstData(ComponentInstanceData resInstance, RelationshipInstData relationshipInstData, RelationshipTypeData relationshipTypeData, String requirementName) { - - Either createNode = titanGenericDao.createNode(relationshipInstData, RelationshipInstData.class); - if (createNode.isRight()) { - TitanOperationStatus status = createNode.right().value(); - log.error("Failed to create relationship instance node in graph. status is {}", status); - return Either.right(status); - } - - RelationshipInstData createdRelationshipInst = createNode.left().value(); - - Map properties = new HashMap(); - properties.put("name", requirementName); - Either createRelation = titanGenericDao.createRelation(resInstance, createdRelationshipInst, GraphEdgeLabels.RELATIONSHIP_INST, properties); - if (createRelation.isRight()) { - TitanOperationStatus status = createRelation.right().value(); - log.error("Failed to associate resource instance {} to relationship instance {}. status is {}", resInstance.getUniqueIdKey(), createdRelationshipInst.getUniqueId(), status); - return Either.right(status); - } - - return Either.left(createdRelationshipInst); - } - - /** - * check whether we can associate resource instances for a given requirement. - * - * 1. check the source resource instance contains the requirement - * - * 2. check the target resource instance contains a capability with the same name as the requirement - * - * @param fromResInstance - * @param toResInstance - * @param requirement - * @param relationship - * @param relationPair - * @return - */ - private Either, TitanOperationStatus> validateRequirementVsCapability(ComponentInstanceData fromResInstance, ComponentInstanceData toResInstance, String requirement, String relationship, - RequirementAndRelationshipPair relationPair) { - - String fromResourceUid = fromResInstance.getComponentInstDataDefinition().getComponentUid(); - - String toResourceUid = toResInstance.getComponentInstDataDefinition().getComponentUid(); - Either capabilityDefinitionE = capabilityOperation.getCapability(relationPair.getCapabilityUid(), true); - if (capabilityDefinitionE.isRight()) { - log.error("The capability cannot be found {}", relationPair.getCapabilityUid()); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - Either requirementDefinitionE = requirementOperation.getRequirement(relationPair.getRequirementUid()); - if (requirementDefinitionE.isRight()) { - log.error("The requirement cannot be found {}", relationPair.getRequirementUid()); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - RequirementDefinition requirementDefinition = requirementDefinitionE.left().value(); - String fetchedRequirementRelationship = requirementDefinition.getRelationship(); - - String fetchedRequirementCapability = requirementDefinition.getCapability(); - // String fetchedRequirementNodeName = requirementDefinition.getNode(); - - TitanOperationStatus status = validateAvailableRequirement(fromResInstance, relationPair); - if (!status.equals(TitanOperationStatus.OK)) { - log.error("The requirement isn't available, status {}", status); - return Either.right(status); - } - status = validateAvailableCapabilty(toResInstance, relationPair); - if (!status.equals(TitanOperationStatus.OK)) { - log.error("The capabilty isn't available, status {}", status); - return Either.right(status); - } - Either originCapabilty = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), relationPair.getCapabilityOwnerId(), ComponentInstanceData.class); - if (originCapabilty.isRight()) { - log.error("Failed to fetch the origin resource for capabilty resource instance with id {}, error {}", relationPair.getCapabilityOwnerId(), originCapabilty.right().value()); - return Either.right(originCapabilty.right().value()); - } - // String originCapabId = - // originCapabilty.left().value().getComponentInstDataDefinition().getComponentUid(); - - // List capabilitySources = new ArrayList<>(); - // TitanOperationStatus capabiltySourcesResult = - // resourceOperation.fillResourceDerivedListFromGraph(originCapabId, - // capabilitySources); - // if (!TitanOperationStatus.OK.equals(capabiltySourcesResult)) { - // log.error("Failed to fill capabilty cources for resource with id " + - // originCapabId + " , error " + capabiltySourcesResult); - // return Either.right(originCapabilty.right().value()); - // } - CapabilityDefinition capabilityDefinition = capabilityDefinitionE.left().value(); - String capabilityName = requirement; - - log.debug("The capability {} of resource {} appropriates to requirement {} on resource {}", capabilityDefinition, toResourceUid, requirement, fromResourceUid); - String capabilityType = capabilityDefinition.getType(); - - if (false == fetchedRequirementCapability.equals(capabilityType)) { - log.error("The capability type in the requirement ({}) does not equal to the capability on the resource {} ({})", fetchedRequirementCapability, toResourceUid, capabilityType); - return Either.right(TitanOperationStatus.MATCH_NOT_FOUND); - } - - // if (fetchedRequirementNodeName != null && - // !capabilitySources.contains(fetchedRequirementNodeName)) { - // log.error("The target resource instance " + toResourceUid + " is not - // of type " + fetchedRequirementNodeName); - // return Either.right(TitanOperationStatus.MATCH_NOT_FOUND); - // } - - RelationshipTypeData relationshipTypeData = new RelationshipTypeData(); - relationshipTypeData.getRelationshipTypeDataDefinition().setType(fetchedRequirementRelationship); - - ImmutablePair result = new ImmutablePair(relationshipTypeData, capabilityName); - return Either.left(result); - } - - private TitanOperationStatus validateAvailableRequirement(ComponentInstanceData fromResInstance, RequirementAndRelationshipPair relationPair) { - Either fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), fromResInstance.getUniqueId()); - if (fromRi.isRight()) { - log.debug("Failed to fetch component instance {} error {}", fromResInstance.getUniqueId(), fromRi.right().value()); - return fromRi.right().value(); - } - Iterator edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_REQUIREMENT.name()); - if (edgeIter == null || !edgeIter.hasNext()) { - log.debug("No available CALCULATED_REQUIREMENT edges. All full filled for RI {}", fromResInstance.getUniqueId()); - return TitanOperationStatus.MATCH_NOT_FOUND; - } - boolean exist = false; - while (edgeIter.hasNext()) { - Edge edge = edgeIter.next(); - TitanVertex reqVertex = (TitanVertex) edge.inVertex(); - String reqId = (String) titanGenericDao.getProperty(reqVertex, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement)); - if (reqId.equals(relationPair.getRequirementUid())) { - String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty()); - if (ownerIdOnEdge.equals(relationPair.getRequirementOwnerId())) { - String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - Integer leftIntValue = Integer.parseInt(leftOccurrences); - if (leftIntValue > 0) { - exist = true; - } - } else { - exist = true; - } - break; - } - } - } - return exist ? TitanOperationStatus.OK : TitanOperationStatus.MATCH_NOT_FOUND; - } - - private TitanOperationStatus validateAvailableCapabilty(ComponentInstanceData toResInstance, RequirementAndRelationshipPair relationPair) { - Either fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), toResInstance.getUniqueId()); - if (fromRi.isRight()) { - log.debug("Failed to fetch component instance {}. error {}", toResInstance.getUniqueId(), fromRi.right().value()); - return fromRi.right().value(); - } - Iterator edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_CAPABILITY.name()); - if (edgeIter == null || !edgeIter.hasNext()) { - log.debug("No available CALCULATED_CAPABILITY edges. All full filled for RI {}", toResInstance.getUniqueId()); - return TitanOperationStatus.MATCH_NOT_FOUND; - } - boolean exist = false; - while (edgeIter.hasNext()) { - Edge edge = edgeIter.next(); - TitanVertex reqVertex = (TitanVertex) edge.inVertex(); - String capId = (String) titanGenericDao.getProperty(reqVertex, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability)); - if (capId.equals(relationPair.getCapabilityUid())) { - String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty()); - if (ownerIdOnEdge.equals(relationPair.getCapabilityOwnerId())) { - String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { - Integer leftIntValue = Integer.parseInt(leftOccurrences); - if (leftIntValue > 0) { - exist = true; - } - } else { - exist = true; - } - break; - } - } - } - return exist ? TitanOperationStatus.OK : TitanOperationStatus.NOT_FOUND; - } - - private List> findCapabilityOfType(Map capabilities, String fetchedRequirementCapability) { - - List> result = new ArrayList>(); - - if (capabilities == null) { - return null; - } - - for (Entry entry : capabilities.entrySet()) { - CapabilityDefinition capabilityDefinition = entry.getValue(); - String type = capabilityDefinition.getType(); - if (fetchedRequirementCapability.equals(type)) { - ImmutablePair pair = new ImmutablePair(entry.getKey(), capabilityDefinition); - result.add(pair); - } - } - - return result; - } - - protected TitanOperationStatus validateTheTargetResourceInstance(String fetchedRequirementNodeName, String resourceUid) { - - if (fetchedRequirementNodeName == null) { - return TitanOperationStatus.OK; - } - - List resourcesPathList = new ArrayList(); - TitanOperationStatus status = resourceOperation.findResourcesPathRecursively(resourceUid, resourcesPathList); - if (status != TitanOperationStatus.OK) { - log.error("Failed to find the parent list of resource {}. status is {}", resourceUid, status); - return status; - } - - boolean found = false; - if (resourcesPathList != null) { - for (ResourceMetadataData resourceData : resourcesPathList) { - String resourceName = resourceData.getMetadataDataDefinition().getName(); - if (fetchedRequirementNodeName.equals(resourceName)) { - found = true; - log.debug("The resource {} is of type {}", resourceData.getUniqueId(), fetchedRequirementNodeName); - break; - } - } - } - - if (true == found) { - return TitanOperationStatus.OK; - } else { - return TitanOperationStatus.MATCH_NOT_FOUND; - } - - } - - private RelationshipInstData buildRelationshipInstData(String fromResInstanceUid, String requirement, RelationshipTypeData relationshipTypeData, RequirementAndRelationshipPair relationPair) { - - RelationshipInstData relationshipInstData = new RelationshipInstData(); - relationshipInstData.setUniqueId(UniqueIdBuilder.buildRelationsipInstInstanceUid(fromResInstanceUid, requirement)); - String type = null; - if (relationshipTypeData != null) { - type = relationshipTypeData.getRelationshipTypeDataDefinition().getType(); - } - - relationshipInstData.setType(type); - Long creationDate = System.currentTimeMillis(); - relationshipInstData.setCreationTime(creationDate); - relationshipInstData.setModificationTime(creationDate); - relationshipInstData.setCapabilityOwnerId(relationPair.getCapabilityOwnerId()); - relationshipInstData.setRequirementOwnerId(relationPair.getRequirementOwnerId()); - relationshipInstData.setCapabiltyId(relationPair.getCapabilityUid()); - relationshipInstData.setRequirementId(relationPair.getRequirementUid()); - - return relationshipInstData; - } - - private Either findResourceInstance(String resInstanceUid) { - - Either node = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resInstanceUid, ComponentInstanceData.class); - - return node; - - } - - @Override - public Either updateResourceInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceUid, ComponentInstance resourceInstance, boolean inTransaction) { - - Either result = null; - try { - - Either updateRes = updateResourceInstanceInService(serviceId, resourceInstanceUid, resourceInstance); - - if (updateRes.isRight()) { - TitanOperationStatus status = updateRes.right().value(); - log.error("Failed to update resource instance {}. status is {}", resourceInstanceUid, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - ComponentInstance value = updateRes.left().value(); - - result = Either.left(value); - - return result; - - } finally { - if (false == inTransaction) { - commitOrRollback(result); - } - } - - } - - /** - * prepare new resource instance object for update - * - * @param resourceInstance - * @param currentInst - * @return - */ - private ComponentInstance normalizeResourceInstanceForUpdate(ComponentInstance resourceInstance, ComponentInstanceData currentInst) { - - ComponentInstance instance = new ComponentInstance(); - instance.setUniqueId((String) currentInst.getUniqueId()); - Long modificationTime = resourceInstance.getModificationTime(); - if (modificationTime == null) { - modificationTime = System.currentTimeMillis(); - } - instance.setModificationTime(modificationTime); - instance.setPosX(resourceInstance.getPosX()); - instance.setPosY(resourceInstance.getPosY()); - instance.setDescription(resourceInstance.getDescription()); - instance.setName(resourceInstance.getName()); - instance.setNormalizedName(resourceInstance.getNormalizedName()); - instance.setPropertyValueCounter(resourceInstance.getPropertyValueCounter()); - instance.setAttributeValueCounter(resourceInstance.getAttributeValueCounter()); - instance.setInputValueCounter(resourceInstance.getInputValueCounter()); - - boolean isNeedGenerate = isNeedGenerateCustomizationUUID(resourceInstance, currentInst); - if (isNeedGenerate) { - generateCustomizationUUID(instance); - } else { - instance.setCustomizationUUID(resourceInstance.getCustomizationUUID()); - } - return instance; - } - - private boolean isNeedGenerateCustomizationUUID(ComponentInstance resourceInstance, ComponentInstanceData currentInst) { - return !currentInst.getComponentInstDataDefinition().getName().equals(resourceInstance.getName()); - } - - private void printDiff(ComponentInstanceData currentInst, ComponentInstance resourceInstance) { - - log.debug("The current Resource Instance details are : {}", currentInst); - log.debug("The received Resource Instance details for update are :{}", resourceInstance); - - } - - @Override - public Either updateResourceInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance) { - - return updateResourceInstance(serviceId, nodeType, resourceInstanceName, resourceInstance, false); - } - - public Either updateResourceInstanceInService(String serviceId, String resourceInstanceUid, ComponentInstance resourceInstance) { - - log.trace("Going to update resource instance {}. Properies are {}", resourceInstanceUid, resourceInstance); - Either findInstRes = findResourceInstance(resourceInstanceUid); - if (findInstRes.isRight()) { - TitanOperationStatus status = findInstRes.right().value(); - log.error("Failed to find resource instance {}. status is {}", resourceInstanceUid, status); - return Either.right(status); - } - - ComponentInstanceData currentInst = findInstRes.left().value(); - if (log.isDebugEnabled()) { - printDiff(currentInst, resourceInstance); - } - - ComponentInstance resourceInstanceForUpdate = normalizeResourceInstanceForUpdate(resourceInstance, currentInst); - - ComponentInstanceData resourceInstanceData = new ComponentInstanceData(resourceInstanceForUpdate); - - Either updateNodeRes = titanGenericDao.updateNode(resourceInstanceData, ComponentInstanceData.class); - if (updateNodeRes.isRight()) { - TitanOperationStatus status = updateNodeRes.right().value(); - log.error("Failed to update resource instance {}. status is {}", resourceInstanceUid, status); - return Either.right(status); - } - - ComponentInstanceData value = updateNodeRes.left().value(); - - ComponentInstance instance = new ComponentInstance(value.getComponentInstDataDefinition()); - - return Either.left(instance); - - } - - @Override - public Either, List>, StorageOperationStatus> getAllComponentInstances(String componentId, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, boolean inTransaction) { - - Either, List>, StorageOperationStatus> result = null; - - try { - - Either, List>, TitanOperationStatus> resInstancesOfService = getComponentInstancesOfComponent(componentId, containerNodeType, compInstNodeType); - - log.trace("After fetching resource instances of component {}. result is {}", componentId, resInstancesOfService); - if (resInstancesOfService.isRight()) { - TitanOperationStatus status = resInstancesOfService.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find resource instances of service {}. status is {}", componentId, status); - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - ImmutablePair, List> immutablePair = resInstancesOfService.left().value(); - List nodes = immutablePair.getKey(); - if (nodes == null || nodes.isEmpty()) { - return Either.right(StorageOperationStatus.NOT_FOUND); - } - - result = Either.left(immutablePair); - return result; - } finally { - if (false == inTransaction) { - commitOrRollback(result); - } - } - } - - @Override - public Either isComponentInstanceNameExist(String parentComponentId, NodeTypeEnum nodeType, String compInstId, String componentInstName) { - - Either result = null; - Either updateRes = isComponentInstanceNameExistOnGraph(parentComponentId, nodeType, compInstId, componentInstName); - - if (updateRes.isRight()) { - TitanOperationStatus status = updateRes.right().value(); - log.error("Failed to find component instance name {}. status is {}", componentInstName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - Boolean value = updateRes.left().value(); - - result = Either.left(value); - - return result; - - } - - private Either isComponentInstanceNameExistOnGraph(String parentComponentId, NodeTypeEnum parentNodeType, String compInstId, String componentInstName) { - - Either graphRes = titanGenericDao.getGraph(); - if (graphRes.isRight()) { - log.debug("Failed to retrieve graph. status is {}", graphRes); - return Either.right(graphRes.right().value()); - } - - TitanGraph titanGraph = graphRes.left().value(); - Iterable vertices = titanGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentComponentId).vertices(); - if (vertices == null || false == vertices.iterator().hasNext()) { - return Either.right(TitanOperationStatus.INVALID_ID); - } - - TitanVertex serviceVertex = vertices.iterator().next(); - TitanVertexQuery query = serviceVertex.query(); - query = query.labels(GraphEdgeLabels.RESOURCE_INST.getProperty()); - Iterable verts = query.vertices(); - if (verts == null) { - log.debug("No edges in graph for criteria"); - return Either.right(TitanOperationStatus.NOT_FOUND); - } - Iterator vIter = verts.iterator(); - while (vIter.hasNext()) { - Vertex vert = vIter.next(); - String resInstName = vert.value(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()); - if (resInstName.equals(componentInstName)) { - if (compInstId != null) {// will be null if we got here from - // create - // Update case - skipping if this is the same component - // instance we are updating, that is allowing - // update of the unchanged name on a component instance. - // This is needed to support position only update, since - // name should - // always be passed in update, and in position case, the - // name will be unchanged. - String uniqueId = vert.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - if (uniqueId.equals(compInstId)) { - continue; - } - } - return Either.left(Boolean.TRUE); - } - } - return Either.left(Boolean.FALSE); - } - - /** - * find resource instances and the relationships between the relationships of a given resource - * - * @param componentId - * @return - */ - public Either, List>, TitanOperationStatus> getComponentInstancesOfComponent(String componentId, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType) { - - if (log.isDebugEnabled()) - log.debug("Going to fetch all resource instances under component {}", componentId); - - Either componentRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(containerNodeType), componentId, ComponentMetadataData.class); - if (componentRes.isRight()) { - TitanOperationStatus status = componentRes.right().value(); - log.error("Failed to find component {}. status is {}", componentId, status); - return Either.right(status); - } - - Either>, TitanOperationStatus> resourceInstancesRes = getAllComponentInstanceFromGraph(componentId, containerNodeType, true); - if (resourceInstancesRes.isRight()) { - TitanOperationStatus status = resourceInstancesRes.right().value(); - log.debug("Resource instance was found under component {}. status is {}", componentId, status); - return Either.right(status); - } - - List resourcesResult = new ArrayList(); - List requirementsResult = new ArrayList(); - - List> resourceInstances = resourceInstancesRes.left().value(); - if (resourceInstances != null && false == resourceInstances.isEmpty()) { - Map> compInstCapabilities = new HashMap>(); - Map> compInstReq = new HashMap>(); - Map> compInstDeploymentArtifacts = new HashMap>(); - Map> compInstInformationalArtifacts = new HashMap>(); - Map compInstOriginsMap = new HashMap(); - - for (ImmutablePair immutablePair : resourceInstances) { - - ComponentInstanceData resourceInstanceData = immutablePair.getKey(); - if (log.isDebugEnabled()) - log.debug("Going to fetch the relationships of resource instance {}", resourceInstanceData); - - ComponentInstance resourceInstance = new ComponentInstance(resourceInstanceData.getComponentInstDataDefinition()); - - TitanOperationStatus status = getFullComponentInstance(compInstCapabilities, compInstReq, compInstDeploymentArtifacts, compInstOriginsMap, resourceInstance, compInstNodeType, compInstInformationalArtifacts); - if (status != TitanOperationStatus.OK) { - return Either.right(status); - } - resourcesResult.add(resourceInstance); - - Either>, TitanOperationStatus> relationshipsRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), - (String) resourceInstanceData.getUniqueId(), GraphEdgeLabels.RELATIONSHIP_INST, NodeTypeEnum.RelationshipInst, RelationshipInstData.class); - - if (relationshipsRes.isRight()) { - status = relationshipsRes.right().value(); - log.debug("After fetching all reslationships of resource instance {} under component {} . status is {}", resourceInstanceData.getUniqueId(), componentId, status); - if (status == TitanOperationStatus.NOT_FOUND) { - continue; - } else { - log.error("Failed to find relationhips of resource instance {} under component {}. status is {}", resourceInstanceData.getUniqueId(), componentId, status); - return Either.right(status); - } - } - - String sourceResourceUid = (String) resourceInstanceData.getUniqueId(); - - Map>> targetNodeToRelationship = new HashMap>>(); - - List> relationshipsImpl = relationshipsRes.left().value(); - status = populateTargetAndRelationsForGivenSource(targetNodeToRelationship, relationshipsImpl); - - if (status != TitanOperationStatus.OK) { - return Either.right(status); - } - - if (targetNodeToRelationship.isEmpty()) { - log.error("No target found for relationship instances of resource instance {}", resourceInstanceData.getUniqueId()); - return Either.right(TitanOperationStatus.INVALID_ELEMENT); - } - - buildRelationsForSource(requirementsResult, sourceResourceUid, targetNodeToRelationship); - - } - - return Either.left(new ImmutablePair, List>(resourcesResult, requirementsResult)); - } else { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - } - - private Either, TitanOperationStatus> getRelationsForSource(String resourceInstanceUid) { - Either>, TitanOperationStatus> relationshipsRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid, - GraphEdgeLabels.RELATIONSHIP_INST, NodeTypeEnum.RelationshipInst, RelationshipInstData.class); - - TitanOperationStatus status; - List requirementsResult = new ArrayList(); - - if (relationshipsRes.isRight()) { - status = relationshipsRes.right().value(); - log.debug("After fetching all reslationships of resource instance {}. status is {}", resourceInstanceUid, status); - if (status == TitanOperationStatus.NOT_FOUND) { - return Either.left(requirementsResult); - } else { - log.error("Failed to find relationhips of resource instance {}. status is {}", resourceInstanceUid, status); - return Either.right(status); - } - } - - Map>> targetNodeToRelationship = new HashMap>>(); - - List> relationshipsImpl = relationshipsRes.left().value(); - status = populateTargetAndRelationsForGivenSource(targetNodeToRelationship, relationshipsImpl); - - if (status != TitanOperationStatus.OK) { - return Either.right(status); - } - - if (targetNodeToRelationship.isEmpty()) { - log.error("No target found for relationship instances of resource instance {}", resourceInstanceUid); - return Either.right(TitanOperationStatus.INVALID_ELEMENT); - } - - buildRelationsForSource(requirementsResult, resourceInstanceUid, targetNodeToRelationship); - return Either.left(requirementsResult); - } - - private Either, TitanOperationStatus> getRelationsForTarget(String resourceInstanceUid) { - - TitanOperationStatus status; - - Either>, TitanOperationStatus> relationshipsRes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid, - GraphEdgeLabels.CAPABILITY_NODE, NodeTypeEnum.RelationshipInst, RelationshipInstData.class); - - List requirementsResult = new ArrayList(); - - if (relationshipsRes.isRight()) { - status = relationshipsRes.right().value(); - log.debug("After fetching all reslationships of resource instance {}. status is {}", resourceInstanceUid, status); - if (status == TitanOperationStatus.NOT_FOUND) { - return Either.left(requirementsResult); - } else { - log.error("Failed to find relationhips of resource instance {}. status is {}", resourceInstanceUid, status); - return Either.right(status); - } - } - - Map>> sourceNodeToRelationship = new HashMap>>(); - - List> relationshipsImpl = relationshipsRes.left().value(); - status = populateSourceAndRelationsForGivenTarget(sourceNodeToRelationship, relationshipsImpl); - - if (status != TitanOperationStatus.OK) { - return Either.right(status); - } - - if (sourceNodeToRelationship.isEmpty()) { - log.error("No target found for relationship instances of resource instance {}", resourceInstanceUid); - return Either.right(TitanOperationStatus.INVALID_ELEMENT); - } - - buildRelationsForTarget(requirementsResult, resourceInstanceUid, sourceNodeToRelationship); - return Either.left(requirementsResult); - } - - @Override - public Either getFullComponentInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType) { - Map> compInstCapabilities = new HashMap>(); - Map> compInstReq = new HashMap>(); - Map> compInstDeploymentArtifacts = new HashMap>(); - Map> compInstInformationalArtifacts = new HashMap>(); - Map compInstOrigins = new HashMap(); - - TitanOperationStatus fullResourceInstance = getFullComponentInstance(compInstCapabilities, compInstReq, compInstDeploymentArtifacts, compInstOrigins, componentInstance, compInstNodeType, compInstInformationalArtifacts); - if (!fullResourceInstance.equals(TitanOperationStatus.OK)) { - log.debug("failed to get full data of resource instance. error: {}", fullResourceInstance); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(fullResourceInstance)); - } - return Either.left(componentInstance); - } - - private TitanOperationStatus getFullComponentInstance(Map> compInstCapabilities, Map> compInstReq, - Map> compInstDeploymentArtifacts, Map compInstOrigins, ComponentInstance compInst, NodeTypeEnum compInstNodeType, - Map> compInstInformationalArtifacts) { - Component component = null; - ComponentOperation componentOperation = getComponentOperation(compInstNodeType); - String componentUid = compInst.getComponentUid(); - if (compInstOrigins.containsKey(componentUid)) { - component = compInstOrigins.get(componentUid); - } else { - Either metadataComponent = componentOperation.getMetadataComponent(componentUid, true); - if (metadataComponent.isRight()) { - log.debug("Failed to fetch the origin component for component instance, origin Id {}, error: {}", componentUid, metadataComponent.right().value()); - return TitanOperationStatus.GENERAL_ERROR; - } - component = metadataComponent.left().value(); - compInstOrigins.put(componentUid, component); - - } - String icon = component.getIcon(); - if (log.isDebugEnabled()) - log.debug("Fetch the resource instance icon from the resource itself. icon = {}", icon); - compInst.setIcon(icon); - String componentName = component.getName(); - compInst.setComponentName(componentName); - compInst.setComponentVersion(component.getVersion()); - if (component.getComponentType() == ComponentTypeEnum.RESOURCE) { - compInst.setToscaComponentName(((Resource) component).getToscaResourceName()); - } - - List componentInstances = new ArrayList<>(); - List derivedFromList = new ArrayList(); - - // For VFC/VL/CP - if (compInstNodeType == NodeTypeEnum.Resource && ((Resource) component).getResourceType() != ResourceTypeEnum.VF) { - resourceOperation.fillResourceDerivedListFromGraph(component.getUniqueId(), derivedFromList); - } else { - // Getting component instances that the origin component of this - // component instance is their container, so we can use the logic of - // getting req/cap from them - // and fill this component instance with those req/cap - Either>, TitanOperationStatus> allComponentInstanceFromGraph = getAllComponentInstanceFromGraph(componentUid, compInstNodeType, true); - if (allComponentInstanceFromGraph.isRight() && allComponentInstanceFromGraph.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Couldn't fetch component instances for component {} of type {}", componentUid, compInstNodeType); - return allComponentInstanceFromGraph.right().value(); - } - List> allCIs = allComponentInstanceFromGraph.isLeft() ? allComponentInstanceFromGraph.left().value() : new ArrayList<>(); - for (ImmutablePair entry : allCIs) { - componentInstances.add(new ComponentInstance(entry.left.getComponentInstDataDefinition())); - } - component.setComponentInstances(componentInstances); - } - - StorageOperationStatus capStatus = setCompInstCapabilitiesFromGraph(compInstCapabilities, component, compInstNodeType, compInst, derivedFromList); - if (capStatus != StorageOperationStatus.OK) { - log.debug("Failed to find capability of resource {}. status is {}", componentName, capStatus); - - } - capStatus = setCompInstRequirementsFromGraph(compInstReq, component, compInstNodeType, compInst); - if (capStatus != StorageOperationStatus.OK) { - log.debug("Failed to find requirements of resource {}. status is {}", componentName, capStatus); - - } - - capStatus = setCompInstDeploymentArtifactsFromGraph(compInstDeploymentArtifacts, componentUid, compInst); - if (capStatus != StorageOperationStatus.OK) { - log.debug("Failed to find resource deployment artifacts of resource {}. status is {}", componentName, capStatus); - - } - - capStatus = setCompInstInformationalArtifactsResourceFromGraph(compInstInformationalArtifacts, componentUid, compInst); - if (capStatus != StorageOperationStatus.OK) { - log.debug("Failed to find resource deployment artifacts of resource {}. status is {}", componentName, capStatus); - - } - - capStatus = setCompInstDeploymentArtifactsFromGraph(compInst); - if (capStatus != StorageOperationStatus.OK) { - log.debug("Failed to find resource deployment artifacts of resource instance {} . status is {}", compInst.getName(), capStatus); - } - - capStatus = setCompInstInformationaltArtifactsFromGraph(compInst); - if (capStatus != StorageOperationStatus.OK) { - log.debug("Failed to find resource informational artifacts of resource instance {} . status is {}", compInst.getName(), capStatus); - } - - capStatus = setGroupInstFromGraph(compInst); - if (capStatus != StorageOperationStatus.OK) { - log.debug("Failed to find resource groups of resource instance {} . status is {}", compInst.getName(), capStatus); - } - return TitanOperationStatus.OK; - } - - private StorageOperationStatus setCompInstInformationaltArtifactsFromGraph(ComponentInstance resourceInstance) { - Map informationalArtifacts = null; - if (resourceInstance.getArtifacts() == null) { - informationalArtifacts = new HashMap(); - } else { - informationalArtifacts = new HashMap(resourceInstance.getArtifacts()); - } - - Either, StorageOperationStatus> result = artifactOperation.getArtifacts(resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true, ArtifactGroupTypeEnum.INFORMATIONAL.getType()); - if (result.isRight()) { - StorageOperationStatus status = result.right().value(); - if (status != StorageOperationStatus.NOT_FOUND) { - return status; - } - } else { - informationalArtifacts.putAll(result.left().value()); - } - - resourceInstance.setArtifacts(informationalArtifacts); - return StorageOperationStatus.OK; - } - - private StorageOperationStatus setGroupInstFromGraph(ComponentInstance compInst) { - List groupInstances = null; - - Either, StorageOperationStatus> result = groupInstanceOperation.getAllGroupInstances(compInst.getUniqueId(), NodeTypeEnum.ResourceInstance); - if (result.isRight()) { - StorageOperationStatus status = result.right().value(); - if (status != StorageOperationStatus.NOT_FOUND) { - return status; - } else { - - return StorageOperationStatus.OK; - } - } - - groupInstances = result.left().value(); - compInst.setGroupInstances(groupInstances); - - return StorageOperationStatus.OK; - } - - private StorageOperationStatus setCompInstInformationalArtifactsResourceFromGraph(Map> resourcesInformationalArtifacts, String componentUid, ComponentInstance resourceInstance) { - - if (resourcesInformationalArtifacts.containsKey(componentUid)) { - resourceInstance.setArtifacts(resourcesInformationalArtifacts.get(componentUid)); - return StorageOperationStatus.OK; - } - - Either, StorageOperationStatus> result = artifactOperation.getArtifacts(componentUid, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.INFORMATIONAL.getType()); - if (result.isRight()) { - StorageOperationStatus status = result.right().value(); - if (status != StorageOperationStatus.NOT_FOUND) { - return status; - } else { - return StorageOperationStatus.OK; - } - } - Map artifacts = result.left().value(); - if (!artifacts.isEmpty()) { - Map tempArtifacts = new HashMap<>(artifacts); - for (Entry artifact : artifacts.entrySet()) { - if (!artifact.getValue().checkEsIdExist()) { - tempArtifacts.remove(artifact.getKey()); - } - } - resourceInstance.setArtifacts(tempArtifacts); - resourcesInformationalArtifacts.put(componentUid, tempArtifacts); - } - - return StorageOperationStatus.OK; - - } - - protected StorageOperationStatus setCompInstDeploymentArtifactsFromGraph(ComponentInstance resourceInstance) { - - Map deploymentArtifacts = null; - if (resourceInstance.getDeploymentArtifacts() == null) { - deploymentArtifacts = new HashMap(); - } else { - deploymentArtifacts = new HashMap(resourceInstance.getDeploymentArtifacts()); - } - - Either, StorageOperationStatus> result = artifactOperation.getArtifacts(resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true, ArtifactGroupTypeEnum.DEPLOYMENT.getType()); - if (result.isRight()) { - StorageOperationStatus status = result.right().value(); - if (status != StorageOperationStatus.NOT_FOUND) { - return status; - } else { - resourceInstance.setDeploymentArtifacts(deploymentArtifacts); - return StorageOperationStatus.OK; - } - } - - Map artifacts = result.left().value(); - if ((artifacts != null) && !artifacts.isEmpty()) { - for (ArtifactDefinition artifact : artifacts.values()) { - if (artifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) { - Either, StorageOperationStatus> heatParamsForEnv = artifactOperation.getHeatParamsForEnv(artifact); - if (heatParamsForEnv.isRight()) { - log.debug("failed to get heat parameters values for heat artifact {}", artifact.getUniqueId()); - return heatParamsForEnv.right().value(); - } else { - artifact.setListHeatParameters(heatParamsForEnv.left().value()); - } - } - } - - // add resource instance artifacts to the artifacts inherited from - // resource - deploymentArtifacts.putAll(artifacts); - resourceInstance.setDeploymentArtifacts(deploymentArtifacts); - } - - return StorageOperationStatus.OK; - - } - - private Either>, TitanOperationStatus> getAllComponentInstanceFromGraph(String componentId, NodeTypeEnum containerNodeType, boolean withEdges) { - if (log.isDebugEnabled()) - log.debug("Going to fetch all resource instances nodes in graph associate to component {}", componentId); - Either>, TitanOperationStatus> resourceInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(containerNodeType), componentId, GraphEdgeLabels.RESOURCE_INST, - NodeTypeEnum.ResourceInstance, ComponentInstanceData.class, withEdges); - if (log.isDebugEnabled()) - log.debug("After fetching all component instances under component {}", componentId); - - if (resourceInstancesRes.isLeft()) { - printAllResourceInstancesNames(resourceInstancesRes); - } - return resourceInstancesRes; - } - - private void printAllResourceInstancesNames(Either>, TitanOperationStatus> resourceInstancesRes) { - if (log.isTraceEnabled()) { - StringBuilder builder = new StringBuilder(); - builder.append("Result is "); - List> listResData = resourceInstancesRes.left().value(); - for (ImmutablePair resInstPair : listResData) { - ComponentInstanceData resdata = resInstPair.getLeft(); - builder.append(resdata.getName()).append(", "); - } - log.trace(builder.toString()); - } - } - - private TitanOperationStatus populateTargetAndRelationsForGivenSource(Map>> targetNodeToRelationship, List> relationshipsImpl) { - if (relationshipsImpl != null && false == relationshipsImpl.isEmpty()) { - for (ImmutablePair pair : relationshipsImpl) { - RelationshipInstData relationshipInstData = pair.getKey(); - - GraphEdge requirementEdge = pair.getValue(); - String requirementName = (String) requirementEdge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty()); - - Either, TitanOperationStatus> targetNodeRes = titanGenericDao.getChild(relationshipInstData.getUniqueIdKey(), relationshipInstData.getUniqueId(), GraphEdgeLabels.CAPABILITY_NODE, - NodeTypeEnum.ResourceInstance, ComponentInstanceData.class); - - if (targetNodeRes.isRight()) { - TitanOperationStatus status = targetNodeRes.right().value(); - log.error("Failed to find the target node of relationship inst {}. status is {}", relationshipInstData, status); - return status; - } - - addRelationshipInstToTargetMap(targetNodeToRelationship, relationshipInstData, requirementName, targetNodeRes); - - } - } - - return TitanOperationStatus.OK; - } - - private TitanOperationStatus populateSourceAndRelationsForGivenTarget(Map>> sourceNodeToRelationship, List> relationshipsImpl) { - if (relationshipsImpl != null && false == relationshipsImpl.isEmpty()) { - for (ImmutablePair pair : relationshipsImpl) { - RelationshipInstData relationshipInstData = pair.getKey(); - - GraphEdge requirementEdge = pair.getValue(); - String requirementName = (String) requirementEdge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty()); - - Either, TitanOperationStatus> sourceNodeRes = titanGenericDao.getParentNode(relationshipInstData.getUniqueIdKey(), relationshipInstData.getUniqueId(), GraphEdgeLabels.RELATIONSHIP_INST, - NodeTypeEnum.ResourceInstance, ComponentInstanceData.class); - - if (sourceNodeRes.isRight()) { - TitanOperationStatus status = sourceNodeRes.right().value(); - log.error("Failed to find the source node of relationship inst {}. status is {}", relationshipInstData, status); - return status; - } - - addRelationshipInstToTargetMap(sourceNodeToRelationship, relationshipInstData, requirementName, sourceNodeRes); - - } - } - - return TitanOperationStatus.OK; - } - - private void buildRelationsForSource(List requirementsResult, String sourceResourceUid, Map>> targetNodeToRelationship) { - for (Entry>> targetToRel : targetNodeToRelationship.entrySet()) { - RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef(); - requirementCapabilityRelDef.setFromNode(sourceResourceUid); - String targetUid = targetToRel.getKey(); - requirementCapabilityRelDef.setToNode(targetUid); - - List relationships = new ArrayList(); - - populateRelationships(targetToRel, relationships); - requirementCapabilityRelDef.setRelationships(relationships); - - requirementsResult.add(requirementCapabilityRelDef); - } - } - - private void buildRelationsForTarget(List requirementsResult, String targetResourceUid, Map>> sourceNodeToRelationship) { - for (Entry>> sourceToRel : sourceNodeToRelationship.entrySet()) { - RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef(); - requirementCapabilityRelDef.setToNode(targetResourceUid); - String sourceUid = sourceToRel.getKey(); - requirementCapabilityRelDef.setFromNode(sourceUid); - List relationships = new ArrayList(); - - populateRelationships(sourceToRel, relationships); - requirementCapabilityRelDef.setRelationships(relationships); - - requirementsResult.add(requirementCapabilityRelDef); - } - } - - private void addRelationshipInstToTargetMap(Map>> targetNodeToRelationship, RelationshipInstData relationshipInstData, String requirementName, - Either, TitanOperationStatus> targetNodeRes) { - - ImmutablePair targetResourcePair = targetNodeRes.left().value(); - ComponentInstanceData targetResourceData = targetResourcePair.getKey(); - - GraphEdge edge = targetResourcePair.right; - if (edge.getEdgeType().equals(GraphEdgeLabels.RELATIONSHIP_INST)) { - requirementName = (String) edge.getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty()); - } - - String targetResourceUid = (String) targetResourceData.getUniqueId(); - List> requirementRelationshipPair = targetNodeToRelationship.get(targetResourceUid); - if (requirementRelationshipPair == null) { - requirementRelationshipPair = new ArrayList>(); - targetNodeToRelationship.put(targetResourceUid, requirementRelationshipPair); - } - ImmutablePair reqRelationshipPair = new ImmutablePair(requirementName, relationshipInstData); - requirementRelationshipPair.add(reqRelationshipPair); - } - - private void populateRelationships(Entry>> targetToRel, List relationships) { - - List> values = targetToRel.getValue(); - for (ImmutablePair value : values) { - String reqName = value.getKey(); - RelationshipInstData relationshipInstData = value.getValue(); - RelationshipImpl relationshipImpl = new RelationshipImpl(); - relationshipImpl.setType(relationshipInstData.getType()); - RequirementAndRelationshipPair pair = new RequirementAndRelationshipPair(reqName, relationshipImpl); - pair.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId()); - pair.setCapabilityUid(relationshipInstData.getCapabiltyId()); - pair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId()); - pair.setRequirementUid(relationshipInstData.getRequirementId()); - pair.setId(relationshipInstData.getUniqueId()); - relationships.add(pair); - } - } - - /** - * FOR TEST ONLY - * - * @param resourceOperation - */ - public void setResourceOperation(ResourceOperation resourceOperation) { - this.resourceOperation = resourceOperation; - } - - @Override - public Either associateResourceInstances(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean inTransaction, boolean isClone) { - - Either result = null; - try { - Either multiRequirements = associateResourceInstancesMultiRequirements(componentId, nodeType, relation, isClone); - if (multiRequirements.isRight()) { - TitanOperationStatus status = multiRequirements.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "associateComponentInstances"); - BeEcompErrorManager.getInstance().logBeDaoSystemError("associateComponentInstances"); - log.debug("Failed to associate component instances {}. status is {}", relation, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - StorageOperationStatus updateCalculatedCapReqResult = updateCalculatedCapReq(relation, true); - if (!updateCalculatedCapReqResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "associateComponentInstances"); - BeEcompErrorManager.getInstance().logBeDaoSystemError("associateComponentInstances"); - log.debug("Failed to associate component instances. {}. status is {}", relation, updateCalculatedCapReqResult); - result = Either.right(updateCalculatedCapReqResult); - return result; - } - result = Either.left(multiRequirements.left().value()); - - return result; - - } finally { - if (false == inTransaction) { - commitOrRollback(result); - } - } - } - - private Either associateResourceInstancesMultiRequirements(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean isClone) { - - String fromNode = relation.getFromNode(); - String toNode = relation.getToNode(); - List relationships = relation.getRelationships(); - if (relationships == null || relationships.isEmpty()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedAddingResourceInstanceError, "AssociateResourceInstances - missing relationship", fromNode, componentId); - BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId); - log.debug("No requirement definition sent in order to set the relation between {} to {}", fromNode, toNode); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - - List relationshipsResult = new ArrayList(); - for (RequirementAndRelationshipPair immutablePair : relationships) { - String requirement = immutablePair.getRequirement(); - - Either associateRes = connectResourcesInService(componentId, nodeType, fromNode, toNode, immutablePair); - - if (associateRes.isRight()) { - TitanOperationStatus status = associateRes.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedAddingResourceInstanceError, "AssociateResourceInstances", fromNode, componentId); - BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId); - log.debug("Failed to associate resource instance {} to resource instance {}. status is {}", fromNode, toNode, status); - return Either.right(status); - } - - RelationshipInstData relationshipInstData = associateRes.left().value(); - RelationshipImpl relationshipImplResult = new RelationshipImpl(); - relationshipImplResult.setType(relationshipInstData.getType()); - RequirementAndRelationshipPair requirementAndRelationshipPair = new RequirementAndRelationshipPair(requirement, relationshipImplResult); - requirementAndRelationshipPair.setCapability(immutablePair.getCapability()); - requirementAndRelationshipPair.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId()); - requirementAndRelationshipPair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId()); - requirementAndRelationshipPair.setCapabilityUid(immutablePair.getCapabilityUid()); - requirementAndRelationshipPair.setRequirementUid(immutablePair.getRequirementUid()); - relationshipsResult.add(requirementAndRelationshipPair); - if (!isClone) { - log.trace("update customization UUID for from CI {} and to CI {}", relation.getFromNode(), relation.getToNode()); - StorageOperationStatus status; - status = updateCustomizationUUID(relation.getFromNode()); - if (status != StorageOperationStatus.OK) { - return Either.right(TitanOperationStatus.GENERAL_ERROR); - } - status = updateCustomizationUUID(relation.getToNode()); - if (status != StorageOperationStatus.OK) { - return Either.right(TitanOperationStatus.GENERAL_ERROR); - } - } - - } - - RequirementCapabilityRelDef capabilityRelDef = new RequirementCapabilityRelDef(); - capabilityRelDef.setFromNode(fromNode); - capabilityRelDef.setToNode(toNode); - capabilityRelDef.setRelationships(relationshipsResult); - - return Either.left(capabilityRelDef); - } - - @Override - public Either associateResourceInstances(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation) { - return associateResourceInstances(componentId, nodeType, relation, false, false); - } - - @Override - public Either, StorageOperationStatus> deleteAllComponentInstances(String containerComponentId, NodeTypeEnum containerNodeType, boolean inTransaction) { - - Either, StorageOperationStatus> result = null; - try { - Either, TitanOperationStatus> multiRequirements = deleteAllComponentInstancesInternal(containerComponentId, containerNodeType); - if (multiRequirements.isRight()) { - TitanOperationStatus status = multiRequirements.right().value(); - if (multiRequirements.right().value() != TitanOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "deleteAllResourceInstances - missing relationship"); - BeEcompErrorManager.getInstance().logBeSystemError("deleteAllResourceInstances - missing relationship"); - } - log.debug("Failed to delete resource instances of service {}. status is {}", containerComponentId, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - - } - - result = Either.left(multiRequirements.left().value()); - - return result; - - } finally { - if (false == inTransaction) { - commitOrRollback(result); - } - } - - } - - @Override - public Either, StorageOperationStatus> deleteAllComponentInstances(String containerComponentId, NodeTypeEnum nodeType) { - return deleteAllComponentInstances(containerComponentId, nodeType, false); - } - - public Either, TitanOperationStatus> deleteAllComponentInstancesInternal(String componentId, NodeTypeEnum nodeType) { - - log.debug("Going to delete all resource instances and their relatioships from service {}", componentId); - - Either>, TitanOperationStatus> resourceInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.RESOURCE_INST, - NodeTypeEnum.ResourceInstance, ComponentInstanceData.class); - - if (resourceInstancesRes.isRight()) { - TitanOperationStatus status = resourceInstancesRes.right().value(); - log.debug("After fetching all resource instances of service {}. status is {}", componentId, status); - return Either.right(status); - } - - List result = new ArrayList(); - List> listOfResInstances = resourceInstancesRes.left().value(); - for (ImmutablePair resInstance : listOfResInstances) { - ComponentInstanceData resourceInstanceData = resInstance.getKey(); - String resourceInstUid = resourceInstanceData.getUniqueId(); - Either removeResourceInstanceRes = removeComponentInstanceFromComponent(nodeType, componentId, resourceInstUid); - log.debug("After removing resource instance {}. Result is {}", resourceInstUid, removeResourceInstanceRes); - if (removeResourceInstanceRes.isRight()) { - TitanOperationStatus status = removeResourceInstanceRes.right().value(); - log.error("After removing resource instance {}. status is {}", resourceInstUid, status); - return Either.right(status); - } - ComponentInstance resourceInstance = removeResourceInstanceRes.left().value(); - result.add(resourceInstance); - } - - log.debug("The following resource instances was deleted from service {} : {}", componentId, result); - - return Either.left(result); - } - - public Either, Map>, StorageOperationStatus> cloneAllComponentInstancesFromContainerComponent(String componentIdFrom, Component component, NodeTypeEnum containerNodeType, - NodeTypeEnum compInstNodeType, LifecycleStateEnum targetLifecycle, Map> inputsValuesMap) { - - List list = new ArrayList(); - Map oldCompInstToNew = new HashMap<>(); - - ImmutablePair, Map> result = new ImmutablePair, Map>(list, oldCompInstToNew); - - Either, List>, StorageOperationStatus> allResourceInstances = getAllComponentInstances(componentIdFrom, containerNodeType, compInstNodeType, true); - - if (allResourceInstances.isRight()) { - StorageOperationStatus status = allResourceInstances.right().value(); - if (status.equals(StorageOperationStatus.NOT_FOUND)) { - - return Either.left(result); - } else { - log.error("failed to get all resource instances for service {}. status={}", componentIdFrom, status); - return Either.right(status); - } - } - - List riList = allResourceInstances.left().value().left; - Map riMapper = new HashMap<>(); - int instanceNumber = 0; - for (ComponentInstance ri : riList) { - instanceNumber++; - String origRiUniqueID = ri.getUniqueId(); - Either createResourceInstance = createComponentInstance(component.getUniqueId(), containerNodeType, String.valueOf(instanceNumber), false, ri, compInstNodeType, true, true); - if (createResourceInstance.isRight()) { - StorageOperationStatus status = createResourceInstance.right().value(); - log.error("failed to clone resource instance {}. status ={}", origRiUniqueID, status); - return Either.right(status); - } - ComponentInstance createdInstance = createResourceInstance.left().value(); - riMapper.put(origRiUniqueID, createdInstance); - StorageOperationStatus associateArtifactsToResource = cloneResourceInstanceArtifacts(createdInstance, ri, targetLifecycle); - if (associateArtifactsToResource != StorageOperationStatus.OK) { - log.debug("failed to clone resource instance {} artifacts. error {} ", ri.getNormalizedName(), associateArtifactsToResource.name()); - return Either.right(associateArtifactsToResource); - } - - StorageOperationStatus associatePropertyValuesToResource = cloneResourceInstancePropertyValues(createdInstance, ri); - if (associatePropertyValuesToResource != StorageOperationStatus.OK) { - log.debug("failed to clone resource instance {} property values. error {} ", ri.getNormalizedName(), associatePropertyValuesToResource.name()); - return Either.right(associatePropertyValuesToResource); - } - - StorageOperationStatus associateAttributeValuesToResource = cloneResourceInstanceAttributeValues(createdInstance, ri); - if (associateAttributeValuesToResource != StorageOperationStatus.OK) { - log.debug("failed to clone resource instance {} attribute values. error {} ", ri.getNormalizedName(), associateAttributeValuesToResource.name()); - return Either.right(associateAttributeValuesToResource); - } - - StorageOperationStatus associateInputValuesToResource = cloneResourceInstanceInputsValues(createdInstance, ri, component, inputsValuesMap); - if (associateInputValuesToResource != StorageOperationStatus.OK) { - log.debug("failed to clone resource instance {} property values. error {} ", ri.getNormalizedName(), associatePropertyValuesToResource.name()); - return Either.right(associatePropertyValuesToResource); - } - - list.add(createdInstance); - oldCompInstToNew.put(origRiUniqueID, createdInstance.getUniqueId()); - } - - List relationsList = allResourceInstances.left().value().right; - for (RequirementCapabilityRelDef relation : relationsList) { - String origFrom = relation.getFromNode(); - String origTo = relation.getToNode(); - relation.setFromNode(riMapper.get(origFrom).getUniqueId()); - relation.setToNode(riMapper.get(origTo).getUniqueId()); - List relationships = relation.getRelationships(); - for (RequirementAndRelationshipPair pair : relationships) { - // for all atomic resource instances need to update to relevant - // new ri ids - String capOwnerId = pair.getCapabilityOwnerId(); - String reqOwnerId = pair.getRequirementOwnerId(); - if (isAtomicComponentInstance(riMapper.get(origFrom))) { - reqOwnerId = riMapper.get(reqOwnerId).getUniqueId(); - } - if (isAtomicComponentInstance(riMapper.get(origTo))) { - capOwnerId = riMapper.get(capOwnerId).getUniqueId(); - } - pair.setRequirementOwnerId(reqOwnerId); - pair.setCapabilityOwnerId(capOwnerId); - } - - Either associateInstances = associateResourceInstances(component.getUniqueId(), containerNodeType, relation, true, true); - if (associateInstances.isRight()) { - StorageOperationStatus status = associateInstances.right().value(); - log.error("failed to assosiate resource instance {} and resource instance {}. status ={}", relation.getFromNode(), relation.getToNode(), status); - return Either.right(status); - } - } - - return Either.left(result); - } - - public Either, Map>, StorageOperationStatus> cloneAllComponentInstancesFromContainerComponent(String componentIdFrom, String componentIdTo, NodeTypeEnum containerNodeType, - NodeTypeEnum compInstNodeType, LifecycleStateEnum targetLifecycle, TitanVertex metadataVertex, Resource prevResource, Resource newResource, Map> inputsPropMap) { - - List list = new ArrayList(); - Map oldCompInstToNew = new HashMap<>(); - - ImmutablePair, Map> result = new ImmutablePair, Map>(list, oldCompInstToNew); - - List riList = prevResource.getComponentInstances(); - Map riMapper = new HashMap<>(); - int instanceNumber = 0; - long timeProperties = 0; - if (riList != null) { - for (ComponentInstance ri : riList) { - instanceNumber++; - String origRiUniqueID = ri.getUniqueId(); - Either createResourceInstance = createComponentInstance(componentIdTo, containerNodeType, String.valueOf(instanceNumber), false, ri, compInstNodeType, true, true, metadataVertex); - if (createResourceInstance.isRight()) { - StorageOperationStatus status = createResourceInstance.right().value(); - log.error("failed to clone resource instance {}. status ={}", origRiUniqueID, status); - return Either.right(status); - } - TitanVertex createdInstance = createResourceInstance.left().value(); - String createdInstanceId = (String) titanGenericDao.getProperty(createdInstance, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - - StorageOperationStatus associateArtifactsToResource = cloneResourceInstanceArtifacts(createdInstance, ri, targetLifecycle); - if (associateArtifactsToResource != StorageOperationStatus.OK) { - log.debug("failed to clone resource instance {} artifacts. error {} ", ri.getNormalizedName(), associateArtifactsToResource.name()); - return Either.right(associateArtifactsToResource); - } - - long start = System.currentTimeMillis(); - StorageOperationStatus associatePropertyValuesToResource = cloneResourceInstancePropertyValues(createdInstance, ri, inputsPropMap, newResource); - if (associatePropertyValuesToResource != StorageOperationStatus.OK) { - log.debug("failed to clone resource instance {} property values. error {} ", ri.getNormalizedName(), associatePropertyValuesToResource.name()); - return Either.right(associatePropertyValuesToResource); - } - long end = System.currentTimeMillis(); - timeProperties += (end - start); - - StorageOperationStatus associateAttributeValuesToResource = cloneResourceInstanceAttributeValues(createdInstance, ri, createdInstanceId); - if (associateAttributeValuesToResource != StorageOperationStatus.OK) { - log.debug("failed to clone resource instance {} attribute values. error {} ", ri.getNormalizedName(), associateAttributeValuesToResource.name()); - return Either.right(associateAttributeValuesToResource); - } - - StorageOperationStatus associateInputValuesToResource = cloneResourceInstanceInputsValues(createdInstance, ri, createdInstanceId, newResource, null); - if (associateInputValuesToResource != StorageOperationStatus.OK) { - log.debug("failed to clone resource instance {} property values. error {} ", ri.getNormalizedName(), associatePropertyValuesToResource.name()); - return Either.right(associatePropertyValuesToResource); - } - Map properties = titanGenericDao.getProperties(createdInstance); - ComponentInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.ResourceInstance.getName(), GraphElementTypeEnum.Node, properties, ComponentInstanceData.class); - ComponentInstance createdResourceInstance = new ComponentInstance(createdComponentInstance.getComponentInstDataDefinition()); - riMapper.put(origRiUniqueID, createdResourceInstance); - - list.add(createdResourceInstance); - oldCompInstToNew.put(origRiUniqueID, createdResourceInstance.getUniqueId()); - } - } - log.info("*********** total properties in ms {}", timeProperties); - - // List relationsList = - // instanceRelationPair.right; - List relationsList = prevResource.getComponentInstancesRelations(); - if (relationsList != null) { - for (RequirementCapabilityRelDef relation : relationsList) { - String origFrom = relation.getFromNode(); - String origTo = relation.getToNode(); - relation.setFromNode(riMapper.get(origFrom).getUniqueId()); - relation.setToNode(riMapper.get(origTo).getUniqueId()); - List relationships = relation.getRelationships(); - for (RequirementAndRelationshipPair pair : relationships) { - // for all atomic resource instances need to update to - // relevant - // new ri ids - String capOwnerId = pair.getCapabilityOwnerId(); - String reqOwnerId = pair.getRequirementOwnerId(); - if (isAtomicComponentInstance(riMapper.get(origFrom))) { - reqOwnerId = riMapper.get(reqOwnerId).getUniqueId(); - } - if (isAtomicComponentInstance(riMapper.get(origTo))) { - capOwnerId = riMapper.get(capOwnerId).getUniqueId(); - } - pair.setRequirementOwnerId(reqOwnerId); - pair.setCapabilityOwnerId(capOwnerId); - } - - Either associateInstances = associateResourceInstances(componentIdTo, containerNodeType, relation, true, true); - if (associateInstances.isRight()) { - StorageOperationStatus status = associateInstances.right().value(); - log.error("failed to assosiate resource instance {} and resource instance {}. status ={}", relation.getFromNode(), relation.getToNode(), status); - return Either.right(status); - } - } - } - return Either.left(result); - } - - private boolean isAtomicComponentInstance(ComponentInstance componentInstance) { - OriginTypeEnum originType = componentInstance.getOriginType(); - if (originType == OriginTypeEnum.VFC || originType == OriginTypeEnum.VFCMT || originType == OriginTypeEnum.VL || originType == OriginTypeEnum.CP) { - return true; - } - return false; - } - - private StorageOperationStatus cloneResourceInstanceArtifacts(ComponentInstance toResourceInstance, ComponentInstance fromResourceInstance, LifecycleStateEnum targetLifecycle) { - - Either, StorageOperationStatus> getArtifactsOfRI = artifactOperation.getArtifacts(fromResourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true); - if (getArtifactsOfRI.isRight()) { - StorageOperationStatus status = getArtifactsOfRI.right().value(); - if (status.equals(StorageOperationStatus.NOT_FOUND)) { - status = StorageOperationStatus.OK; - } - return status; - } - - Map artifacts = getArtifactsOfRI.left().value(); - List groupInstancesFrom = fromResourceInstance.getGroupInstances(); - List groupInstancesTo = toResourceInstance.getGroupInstances(); - Map> groupsInstanceArtifact = new HashMap>(); - for (Entry entry : artifacts.entrySet()) { - - ArtifactDefinition artifactDefinition = entry.getValue(); - String generatedFromIdArtifactUid = artifactDefinition.getGeneratedFromId(); - - // US687135 Do not Add VF_MODULES_METADATA when checking out - if (ArtifactTypeEnum.VF_MODULES_METADATA.getType().equals(artifactDefinition.getArtifactType())) { - // The artifact of type VF_MODULES_METADATA should not be cloned - // unless we are changing the state to certified. - if (targetLifecycle != null && targetLifecycle != LifecycleStateEnum.CERTIFIED) { - continue; - } - } - Either addArifactToResource = Either.left(artifactDefinition); - - addArifactToResource = artifactOperation.addArifactToComponent(artifactDefinition, toResourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, false, true); - - if (addArifactToResource.isRight()) { - return addArifactToResource.right().value(); - } - - if (groupInstancesTo != null) { - for (GroupInstance groupInstanceTo : groupInstancesTo) { - Optional op = groupInstanceTo.getArtifacts().stream().filter(p -> p.equals(generatedFromIdArtifactUid)).findAny(); - if (op.isPresent()) { - - List artifactsUid = null; - if (groupsInstanceArtifact.containsKey(groupInstanceTo.getUniqueId())) { - artifactsUid = groupsInstanceArtifact.get(groupInstanceTo.getUniqueId()); - } else { - artifactsUid = new ArrayList(); - } - artifactsUid.add(addArifactToResource.left().value().getUniqueId()); - groupsInstanceArtifact.put(groupInstanceTo.getUniqueId(), artifactsUid); - break; - } - } - - } - } - if (groupsInstanceArtifact != null && !groupsInstanceArtifact.isEmpty()) { - for (Map.Entry> groupArtifact : groupsInstanceArtifact.entrySet()) { - groupInstanceOperation.associateArtifactsToGroupInstance(groupArtifact.getKey(), groupArtifact.getValue()); - } - } - Either, StorageOperationStatus> groupInstanceStatus = groupInstanceOperation.getAllGroupInstances(toResourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance); - if (groupInstanceStatus.isRight()) { - log.debug("failed to get groupinstance for component inatance {}", toResourceInstance.getUniqueId()); - return groupInstanceStatus.right().value(); - } - toResourceInstance.setGroupInstances(groupInstanceStatus.left().value()); - toResourceInstance.setDeploymentArtifacts(artifacts); - return StorageOperationStatus.OK; - } - - private StorageOperationStatus cloneResourceInstanceArtifacts(TitanVertex toResourceInstance, ComponentInstance fromResourceInstance, LifecycleStateEnum targetLifecycle) { - - Either, StorageOperationStatus> getArtifactsOfRI = artifactOperation.getArtifactsVertecies(fromResourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true); - if (getArtifactsOfRI.isRight()) { - StorageOperationStatus status = getArtifactsOfRI.right().value(); - if (status.equals(StorageOperationStatus.NOT_FOUND)) { - status = StorageOperationStatus.OK; - } - return status; - } - - Map artifacts = getArtifactsOfRI.left().value(); - for (Entry entry : artifacts.entrySet()) { - - TitanVertex artifactVertex = entry.getValue(); - // US687135 Do not Add VF_MODULES_METADATA when checking out - String artifactType = (String) titanGenericDao.getProperty(artifactVertex, GraphPropertiesDictionary.ARTIFACT_TYPE.getProperty()); - String label = (String) titanGenericDao.getProperty(artifactVertex, GraphPropertiesDictionary.ARTIFACT_LABEL.getProperty()); - if (ArtifactTypeEnum.VF_MODULES_METADATA.getType().equals(artifactType)) { - // The artifact of type VF_MODULES_METADATA should not be cloned - // unless we are changing the state to certified. - if (targetLifecycle != null && targetLifecycle != LifecycleStateEnum.CERTIFIED) { - continue; - } - } - - StorageOperationStatus addArifactToResource = artifactOperation.addArifactToComponent(artifactVertex, toResourceInstance, label); - - if (!addArifactToResource.equals(StorageOperationStatus.OK)) { - return addArifactToResource; - } - } - // toResourceInstance.setDeploymentArtifacts(artifacts); - return StorageOperationStatus.OK; - } - - public Either increaseAndGetResourceInstanceSpecificCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, boolean inTransaction) { - - Either result = null; - try { - - Either graphResult = titanGenericDao.getGraph(); - if (graphResult.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); - return result; - } - Either 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 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(); - } - } - } - - } - - public Either increaseAndGetResourceInstanceSpecificCounter(TitanVertex resourceInstanceVertex, GraphPropertiesDictionary counterType) { - - Either result = null; - - VertexProperty vertexProperty = resourceInstanceVertex.property(counterType.getProperty()); - Integer counter = 0; - if (vertexProperty.isPresent()) { - if (vertexProperty.value() != null) { - counter = (Integer) vertexProperty.value(); - } - } - counter++; - resourceInstanceVertex.property(counterType.getProperty(), counter); - - result = Either.left(counter); - return result; - - } - - @Override - public Either, StorageOperationStatus> getAllComponentInstancesNames(String serviceId, NodeTypeEnum nodeType, boolean inTransaction) { - - Either, StorageOperationStatus> result = null; - - try { - - Either, TitanOperationStatus> resInstancesOfService = getComponentInstancesNameOfService(serviceId, nodeType); - - log.debug("After fetching resource instances of service {}. result is {}", serviceId, resInstancesOfService); - if (resInstancesOfService.isRight()) { - TitanOperationStatus status = resInstancesOfService.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find resource instances of service {}. status is {}", serviceId, status); - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - List names = resInstancesOfService.left().value(); - - if (names == null || names.isEmpty()) { - return Either.right(StorageOperationStatus.NOT_FOUND); - } - - result = Either.left(names); - - } finally { - if (false == inTransaction) { - commitOrRollback(result); - } - } - return result; - } - - private Either, TitanOperationStatus> getComponentInstancesNameOfService(String serviceId, NodeTypeEnum nodeType) { - - List resourcesInstanseName = new ArrayList(); - Either>, TitanOperationStatus> resourceInstancesRes = getAllComponentInstanceFromGraph(serviceId, nodeType, false); - if (resourceInstancesRes.isRight()) { - TitanOperationStatus status = resourceInstancesRes.right().value(); - log.debug("Resource instance was found under service {}. status is {}", serviceId, status); - return Either.right(status); - } - - List> resourceInstances = resourceInstancesRes.left().value(); - if (resourceInstances != null && false == resourceInstances.isEmpty()) { - - for (ImmutablePair immutablePair : resourceInstances) { - ComponentInstanceData resourceInstanceData = immutablePair.getKey(); - log.debug("Going to fetch the relationships of resource instance {}", resourceInstanceData); - resourcesInstanseName.add(resourceInstanceData.getComponentInstDataDefinition().getName()); - - } - } - - return Either.left(resourcesInstanseName); - } - - @Override - public Either, StorageOperationStatus> getAllComponentInstancesNames(String componentId, NodeTypeEnum nodeType) { - - return getAllComponentInstancesNames(componentId, nodeType, false); - } - - @Override - public Either getResourceInstanceById(String resourceId) { - Either resourceInstanceData = findResourceInstance(resourceId); - - if (resourceInstanceData.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceInstanceData.right().value())); - } - - return Either.left(new ComponentInstance(resourceInstanceData.left().value().getComponentInstDataDefinition())); - - } - - private StorageOperationStatus setCompInstDeploymentArtifactsFromGraph(Map> resourcesArtifacts, String uniqueId, ComponentInstance resourceInstance) { - - if (resourcesArtifacts.containsKey(uniqueId)) { - resourceInstance.setDeploymentArtifacts(resourcesArtifacts.get(uniqueId)); - return StorageOperationStatus.OK; - } - - Either, StorageOperationStatus> result = artifactOperation.getArtifacts(uniqueId, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT.getType()); - if (result.isRight()) { - StorageOperationStatus status = result.right().value(); - if (status != StorageOperationStatus.NOT_FOUND) { - return status; - } else { - return StorageOperationStatus.OK; - } - } - Map artifacts = result.left().value(); - if (!artifacts.isEmpty()) { - Map tempArtifacts = new HashMap(artifacts); - for (Entry artifact : artifacts.entrySet()) { - if (!artifact.getValue().checkEsIdExist()) { - tempArtifacts.remove(artifact.getKey()); - } - } - resourceInstance.setDeploymentArtifacts(tempArtifacts); - resourcesArtifacts.put(uniqueId, tempArtifacts); - } - - return StorageOperationStatus.OK; - - } - - private StorageOperationStatus setCompInstCapabilitiesFromGraph(Map> resourcesCapabilities, Component component, NodeTypeEnum compInstType, ComponentInstance resourceInstance, - List respourceDerivedList) { - - StorageOperationStatus status; - ComponentOperation componentOperation = getComponentOperation(compInstType); - Either>, TitanOperationStatus> eitherCapabilities = componentOperation.getCapabilities(component, compInstType, true); - if (eitherCapabilities.isLeft()) { - status = StorageOperationStatus.OK; - Map> capabilities = eitherCapabilities.left().value(); - if (capabilities != null && !capabilities.isEmpty()) { - capabilities.forEach((type, list) -> { - if (list != null && !list.isEmpty()) { - list.forEach((capability) -> { - // We want to set ownerId only for instances coming - // from atomic resources, otherwise we don't want - // to overwrite the existing ownerId of underlying - // component instances - if (isAtomicResource(component)) { - capability.setOwnerId(resourceInstance.getUniqueId()); - capability.setOwnerName(resourceInstance.getName()); - capability.setCapabilitySources(respourceDerivedList); - } - }); - } - }); - resourceInstance.setCapabilities(capabilities); - } - } else { - status = StorageOperationStatus.GENERAL_ERROR; - } - return status; - - } - - private StorageOperationStatus setCompInstRequirementsFromGraph(Map> resourcesReq, Component component, NodeTypeEnum compInstType, ComponentInstance resourceInstance) { - StorageOperationStatus status; - ComponentOperation componentOperation = getComponentOperation(compInstType); - Either>, TitanOperationStatus> eitherCapabilities = componentOperation.getRequirements(component, compInstType, true); - if (eitherCapabilities.isLeft()) { - status = StorageOperationStatus.OK; - Map> requirements = eitherCapabilities.left().value(); - if (requirements != null && !requirements.isEmpty()) { - // We want to set ownerId only for instances coming from atomic - // resources, otherwise we don't want - // to overwrite the existing ownerId of underlying component - // instances - if (isAtomicResource(component)) { - requirements.forEach((type, list) -> { - if (list != null && !list.isEmpty()) { - list.forEach((requirement) -> { - requirement.setOwnerId(resourceInstance.getUniqueId()); - requirement.setOwnerName(resourceInstance.getName()); - }); - } - }); - } - resourceInstance.setRequirements(requirements); - } - } else { - status = StorageOperationStatus.GENERAL_ERROR; - } - return status; - } - - @Override - public Either>, TitanOperationStatus> getCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) { - DataNodeCollector collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, - CapabilityData.class); - - return getDataFromGraph(collector); - } - - @Override - public Either>, TitanOperationStatus> getRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) { - - DataNodeCollector collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_REQUIREMENT, NodeTypeEnum.Requirement, - RequirementData.class); - - return getDataFromGraph(collector); - - } - - @Override - public Either>, TitanOperationStatus> getFulfilledCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) { - DataNodeCollector collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_CAPABILITY_FULLFILLED, NodeTypeEnum.Capability, - CapabilityData.class); - - return getDataFromGraph(collector); - } - - @Override - public Either>, TitanOperationStatus> getFulfilledRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) { - - DataNodeCollector collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED, NodeTypeEnum.Requirement, - RequirementData.class); - - return getDataFromGraph(collector); - - } - - public Either isAvailableRequirement(ComponentInstance fromResInstance, RequirementAndRelationshipPair relationPair) { - Either fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), fromResInstance.getUniqueId()); - if (fromRi.isRight()) { - log.debug("Failed to fetch component instance {} error {}", fromResInstance.getUniqueId(), fromRi.right().value()); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - Iterator edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_REQUIREMENT.name()); - if (edgeIter == null || !edgeIter.hasNext()) { - log.debug("No available CALCULATED_REQUIREMENT edges. All full filled for RI {}", fromResInstance.getUniqueId()); - return Either.left(false); - } - boolean exist = false; - while (edgeIter.hasNext()) { - Edge edge = edgeIter.next(); - TitanVertex reqVertex = (TitanVertex) edge.inVertex(); - String reqId = (String) titanGenericDao.getProperty(reqVertex, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement)); - if (reqId.equals(relationPair.getRequirementUid())) { - String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty()); - if (ownerIdOnEdge.equals(relationPair.getRequirementOwnerId())) { - String leftOccurrences = (String) edge.value(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - Integer leftIntValue = Integer.parseInt(leftOccurrences); - if (leftIntValue > 0) { - exist = true; - } - } else { - exist = true; - } - break; - } - } - } - return Either.left(exist); - } - - public Either isAvailableCapabilty(ComponentInstance toResInstance, RequirementAndRelationshipPair relationPair) { - Either fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), toResInstance.getUniqueId()); - if (fromRi.isRight()) { - log.debug("Failed to fetch component instance {} error {}", toResInstance.getUniqueId(), fromRi.right().value()); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - Iterator edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_CAPABILITY.name()); - if (edgeIter == null || !edgeIter.hasNext()) { - log.debug("No available CALCULATED_CAPABILITY edges. All full filled for RI {}", toResInstance.getUniqueId()); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - boolean exist = false; - while (edgeIter.hasNext()) { - Edge edge = edgeIter.next(); - TitanVertex reqVertex = (TitanVertex) edge.inVertex(); - String capId = (String) titanGenericDao.getProperty(reqVertex, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability)); - if (capId.equals(relationPair.getCapabilityUid())) { - String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty()); - if (ownerIdOnEdge.equals(relationPair.getCapabilityOwnerId())) { - String leftOccurrences = (String) edge.value(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { - Integer leftIntValue = Integer.parseInt(leftOccurrences); - if (leftIntValue > 0) { - exist = true; - } - } else { - exist = true; - } - break; - } - } - } - return Either.left(exist); - } - - interface DataNodeCollector { - Either>, TitanOperationStatus> getDataNodes(); - } - - public Either>, TitanOperationStatus> getDataFromGraph(DataNodeCollector dataCollector) { - Either>, TitanOperationStatus> eitherRet; - - Either>, TitanOperationStatus> childrenNodes = dataCollector.getDataNodes(); - - if (childrenNodes.isLeft()) { - List> collectedData = childrenNodes.left().value().stream().map(element -> new ImmutablePair(element.getLeft(), element.getRight())).collect(Collectors.toList()); - eitherRet = Either.left(collectedData); - } else { - eitherRet = Either.right(childrenNodes.right().value()); - } - return eitherRet; - } - - public ComponentOperation getComponentOperation(NodeTypeEnum componentType) { - if (NodeTypeEnum.Service == componentType) { - return serviceOperation; - } else if (NodeTypeEnum.Resource == componentType) { - return resourceOperation; - } - return null; - } - - private boolean isAtomicResource(Component component) { - // true if component is of type VL/CP/VFC - boolean isFromAtomicResource = (component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() != ResourceTypeEnum.VF); - return isFromAtomicResource; - } - - private StorageOperationStatus cloneResourceInstanceAttributeValues(ComponentInstance createdInstance, ComponentInstance resourceInstance) { - Wrapper storageStatusWrapper = new Wrapper<>(); - Wrapper> compInstanceAttList = new Wrapper<>(); - - findAllAttributesOfResourceInstance(resourceInstance, compInstanceAttList, storageStatusWrapper); - - if (storageStatusWrapper.isEmpty()) { - validateListNotEmpty(storageStatusWrapper, compInstanceAttList.getInnerElement()); - } - - if (storageStatusWrapper.isEmpty()) { - List attributesOnInstance = compInstanceAttList.getInnerElement(); - for (int i = 0; i < attributesOnInstance.size() && storageStatusWrapper.isEmpty(); i++) { - cloneSingleAttributeOnResourceInstance(createdInstance, attributesOnInstance.get(i), storageStatusWrapper); - } - } - - StorageOperationStatus result = storageStatusWrapper.isEmpty() ? StorageOperationStatus.OK : storageStatusWrapper.getInnerElement(); - return result; - - } - - private StorageOperationStatus cloneResourceInstanceAttributeValues(TitanVertex createdInstanceVertex, ComponentInstance resourceInstance, String instanceId) { - Wrapper storageStatusWrapper = new Wrapper<>(); - Wrapper> compInstanceAttList = new Wrapper<>(); - - findAllAttributesOfResourceInstance(resourceInstance, compInstanceAttList, storageStatusWrapper); - - if (storageStatusWrapper.isEmpty()) { - validateListNotEmpty(storageStatusWrapper, compInstanceAttList.getInnerElement()); - } - - if (storageStatusWrapper.isEmpty()) { - List attributesOnInstance = compInstanceAttList.getInnerElement(); - for (int i = 0; i < attributesOnInstance.size() && storageStatusWrapper.isEmpty(); i++) { - StorageOperationStatus result = cloneSingleAttributeOnResourceInstance(createdInstanceVertex, attributesOnInstance.get(i), instanceId); - if (result != StorageOperationStatus.OK) { - log.trace("Failed to clone attribute for instance {} error {}", instanceId, result); - return result; - } - } - } - - StorageOperationStatus result = storageStatusWrapper.isEmpty() ? StorageOperationStatus.OK : storageStatusWrapper.getInnerElement(); - return result; - - } - - private void validateListNotEmpty(Wrapper storageStatusWrapper, List attributesOnInstance) { - if (attributesOnInstance == null || attributesOnInstance.isEmpty() == true) { - storageStatusWrapper.setInnerElement(StorageOperationStatus.OK); - } - } - - private void findAllAttributesOfResourceInstance(ComponentInstance resourceInstance, Wrapper> compInstanceAttList, Wrapper storageStatusWrapper) { - - Either, TitanOperationStatus> allAttributes = attributeOperation.getAllAttributesOfResourceInstance(resourceInstance); - if (allAttributes.isRight()) { - TitanOperationStatus status = allAttributes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - storageStatusWrapper.setInnerElement(storageStatus); - } else { - compInstanceAttList.setInnerElement(allAttributes.left().value()); - } - } - - private void cloneSingleAttributeOnResourceInstance(ComponentInstance createdInstance, ComponentInstanceProperty attribute, Wrapper storageStatusWrapper) { - // Only if valueUniqueId is not empty, then its belongs to the - // instance - if (attribute.getValueUniqueUid() != null) { - attribute.setValueUniqueUid(null); - Either counterRes = increaseAndGetResourceInstanceSpecificCounter(createdInstance.getUniqueId(), GraphPropertiesDictionary.ATTRIBUTE_COUNTER, true); - if (counterRes.isRight()) { - storageStatusWrapper.setInnerElement(counterRes.right().value()); - } else { - Either addAttributeToResourceInstance = addAttributeToResourceInstance(attribute, createdInstance.getUniqueId(), counterRes.left().value()); - - if (addAttributeToResourceInstance.isRight()) { - TitanOperationStatus status = addAttributeToResourceInstance.right().value(); - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - storageStatusWrapper.setInnerElement(storageStatus); - } - } - } - - } - - private StorageOperationStatus cloneSingleAttributeOnResourceInstance(TitanVertex createdInstanceVertex, ComponentInstanceProperty attribute, String instanceId) { - // Only if valueUniqueId is not empty, then its belongs to the - // instance - if (attribute.getValueUniqueUid() != null) { - attribute.setValueUniqueUid(null); - Either counterRes = increaseAndGetResourceInstanceSpecificCounter(createdInstanceVertex, GraphPropertiesDictionary.ATTRIBUTE_COUNTER); - if (counterRes.isRight()) { - return counterRes.right().value(); - } else { - Either addAttributeToResourceInstance = addAttributeToResourceInstance(attribute, instanceId, counterRes.left().value()); - - if (addAttributeToResourceInstance.isRight()) { - TitanOperationStatus status = addAttributeToResourceInstance.right().value(); - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - return storageStatus; - } - } - } - return StorageOperationStatus.OK; - - } - - private void connectAttValueDataToComponentInstanceData(Wrapper errorWrapper, ComponentInstanceData compIns, AttributeValueData attValueData) { - - Either 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 connectInputValueDataToComponentInstanceData(Wrapper errorWrapper, ComponentInstanceData compIns, InputValueData attValueData) { - - Either createRelResult = titanGenericDao.createRelation(compIns, attValueData, GraphEdgeLabels.INPUT_VALUE, null); - - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - errorWrapper.setInnerElement(operationStatus); - BeEcompErrorManager.getInstance().logInternalFlowError("connectInputValueDataToComponentInstanceData", - "Failed to associate resource instance " + compIns.getUniqueId() + " input value " + attValueData.getUniqueId() + " in graph. status is " + operationStatus, ErrorSeverity.ERROR); - } - } - - private void connectAttValueDataToAttData(Wrapper errorWrapper, AttributeData attData, AttributeValueData attValueData) { - - Either 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 connectInputValueDataToInputData(Wrapper errorWrapper, InputsData attData, InputValueData attValueData) { - - Either createRelResult = titanGenericDao.createRelation(attValueData, attData, GraphEdgeLabels.INPUT_IMPL, null); - - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("connectInputValueDataToInputData", "Failed to associate input value " + attValueData.getUniqueId() + " to input " + attData.getUniqueId() + " in graph. status is " + operationStatus, - ErrorSeverity.ERROR); - - errorWrapper.setInnerElement(operationStatus); - } - } - - private void createAttributeValueDataNode(ComponentInstanceProperty attributeInstanceProperty, Integer index, Wrapper errorWrapper, ComponentInstanceData resourceInstanceData, - Wrapper 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 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 void createInputValueDataNode(ComponentInstanceInput inputInstanceProperty, Integer index, Wrapper errorWrapper, ComponentInstanceData resourceInstanceData, Wrapper attValueDataWrapper) { - * String valueUniqueUid = inputInstanceProperty.getValueUniqueUid(); if (valueUniqueUid == null) { - * - * String attValueDatauniqueId = UniqueIdBuilder.buildResourceInstanceInputValueUid(resourceInstanceData. getUniqueId(), index); AttributeValueData attributeValueData = buildAttributeValueDataFromComponentInstanceAttribute( inputInstanceProperty, - * attValueDatauniqueId); - * - * log.debug("Before adding attribute value to graph {}", attributeValueData); Either 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 InputValueData buildAttributeValueDataFromComponentInstanceAttribute(ComponentInstanceInput resourceInstanceInput, String uniqueId) { - InputValueData inputValueData = new InputValueData(); - inputValueData.setUniqueId(uniqueId); - inputValueData.setHidden(resourceInstanceInput.isHidden()); - inputValueData.setValue(resourceInstanceInput.getValue()); - inputValueData.setType(resourceInstanceInput.getType()); - long currentTimeMillis = System.currentTimeMillis(); - inputValueData.setCreationTime(currentTimeMillis); - inputValueData.setModificationTime(currentTimeMillis); - return inputValueData; - } - - private StorageOperationStatus cloneResourceInstancePropertyValues(ComponentInstance toResourceInstance, ComponentInstance fromResourceInstance) { - - Either, TitanOperationStatus> allProperties = propertyOperation.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(fromResourceInstance.getUniqueId()); - if (allProperties.isRight()) { - TitanOperationStatus status = allProperties.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - return storageStatus; - } - - List propertiesOnInstance = allProperties.left().value(); - if (propertiesOnInstance == null || propertiesOnInstance.isEmpty() == true) { - return StorageOperationStatus.OK; - } - - for (ComponentInstanceProperty property : propertiesOnInstance) { - - // Only if valueUniqueId is not empty, then its belongs to the - // instance - if (property.getValueUniqueUid() != null) { - property.setValueUniqueUid(null); - List rules = property.getRules(); - if (rules != null) { - for (PropertyRule propertyRule : rules) { - propertyRule.replaceFirstToken(toResourceInstance.getUniqueId()); - } - } - - } else { - continue; - } - - String resourceInstanceId = toResourceInstance.getUniqueId(); - - Either counterRes = this.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.PROPERTY_COUNTER, true); - - if (counterRes.isRight()) { - log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property); - StorageOperationStatus status = counterRes.right().value(); - return status; - } - Integer index = counterRes.left().value(); - - Either addPropertyToResourceInstance = this.addPropertyToResourceInstance(property, toResourceInstance.getUniqueId(), false, index); - - if (addPropertyToResourceInstance.isRight()) { - TitanOperationStatus status = addPropertyToResourceInstance.right().value(); - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - return storageStatus; - } - } - - return StorageOperationStatus.OK; - } - - private StorageOperationStatus cloneResourceInstancePropertyValues(TitanVertex toResourceInstance, ComponentInstance fromResourceInstance, Map> inputsPropMap, Resource newResource) { - - String riId = (String) titanGenericDao.getProperty(toResourceInstance, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - Either, TitanOperationStatus> allProperties = propertyOperation.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(fromResourceInstance.getUniqueId()); - List newInputs = newResource.getInputs(); - // - if (allProperties.isRight()) { - TitanOperationStatus status = allProperties.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - return storageStatus; - } - - List propertiesOnInstance = allProperties.left().value(); - if (propertiesOnInstance == null || propertiesOnInstance.isEmpty() == true) { - return StorageOperationStatus.OK; - } - - for (ComponentInstanceProperty property : propertiesOnInstance) { - - // Only if valueUniqueId is not empty, then its belongs to the - // instance - if (property.getValueUniqueUid() != null) { - property.setValueUniqueUid(null); - List rules = property.getRules(); - if (rules != null) { - for (PropertyRule propertyRule : rules) { - propertyRule.replaceFirstToken(riId); - } - } - - } else { - continue; - } - - String resourceInstanceId = riId; - - Either counterRes = this.increaseAndGetResourceInstanceSpecificCounter(toResourceInstance, GraphPropertiesDictionary.PROPERTY_COUNTER); - - if (counterRes.isRight()) { - log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property); - StorageOperationStatus status = counterRes.right().value(); - return status; - } - Integer index = counterRes.left().value(); - - Either addPropertyToResourceInstance = this.addPropertyToResourceInstance(property, toResourceInstance, false, index, resourceInstanceId); - - if (addPropertyToResourceInstance.isRight() && addPropertyToResourceInstance.right().value() != TitanOperationStatus.OK) { - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyToResourceInstance.right().value()); - return storageStatus; - } - if (addPropertyToResourceInstance.isLeft()) { - ComponentInstanceProperty newProp = addPropertyToResourceInstance.left().value(); - Set inputsKey = inputsPropMap.keySet(); - String inputToAssName = null; - GetInputValueDataDefinition getInputInfo = null; - for (String inputName : inputsKey) { - List propsList = inputsPropMap.get(inputName); - Optional op = propsList.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); - if (op.isPresent()) { - ComponentInstanceProperty inpProp = op.get(); - getInputInfo = new GetInputValueDataDefinition(); - getInputInfo.setPropName(inpProp.getName()); - getInputInfo.setInputName(inputName); - inputToAssName = inputName; - break; - } - - } - if (inputToAssName != null) { - for (InputDefinition input1 : newInputs) { - if (input1.getName().equals(inputToAssName)) { - this.inputOperation.associatePropertyToInput(riId, input1.getUniqueId(), newProp, getInputInfo); - break; - } - } - } - - } - } - - return StorageOperationStatus.OK; - } - - private StorageOperationStatus cloneResourceInstanceInputsValues(ComponentInstance toResourceInstance, ComponentInstance fromResourceInstance, Component comonentTo, Map> inputsValuesMap) { - - Either, TitanOperationStatus> allProperties = inputOperation.getAllInputsOfResourceInstanceOnlyInputDefId(fromResourceInstance.getUniqueId()); - if (allProperties.isRight()) { - TitanOperationStatus status = allProperties.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - return storageStatus; - } - - List propertiesOnInstance = allProperties.left().value(); - if (propertiesOnInstance == null || propertiesOnInstance.isEmpty() == true) { - return StorageOperationStatus.OK; - } - List newInputs = comonentTo.getInputs(); - - for (ComponentInstanceInput property : propertiesOnInstance) { - - List inputToAss = new ArrayList(); - if (newInputs != null && !inputsValuesMap.isEmpty()) { - - Set inputsName = inputsValuesMap.keySet(); - for (String name : inputsName) { - List inputsValue = inputsValuesMap.get(name); - if (inputsValue != null) { - Optional op = inputsValue.stream().filter(p -> p.getValueUniqueUid().equals(property.getValueUniqueUid())).findAny(); - if (op.isPresent()) { - Optional optional = newInputs.stream().filter(e -> e.getName().equals(name)).findAny(); - if (optional.isPresent()) { - inputToAss.add(optional.get()); - } - } - } - } - } - - // Only if valueUniqueId is not empty, then its belongs to the - // instance - if (property.getValueUniqueUid() != null) { - property.setValueUniqueUid(null); - List rules = property.getRules(); - if (rules != null) { - for (PropertyRule propertyRule : rules) { - propertyRule.replaceFirstToken(toResourceInstance.getUniqueId()); - } - } - - } else { - continue; - } - - String resourceInstanceId = toResourceInstance.getUniqueId(); - - Either counterRes = this.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true); - - if (counterRes.isRight()) { - log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property); - StorageOperationStatus status = counterRes.right().value(); - return status; - } - Integer index = counterRes.left().value(); - - Either addPropertyToResourceInstance = this.addInputToResourceInstance(property, toResourceInstance.getUniqueId(), index); - - if (addPropertyToResourceInstance.isRight()) { - TitanOperationStatus status = addPropertyToResourceInstance.right().value(); - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - return storageStatus; - } - - for (InputDefinition input : inputToAss) { - Map props = new HashMap(); - props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), input.getName()); - props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), toResourceInstance.getUniqueId()); - - GraphNode inputData = new UniqueIdData(NodeTypeEnum.Input, input.getUniqueId()); - GraphNode propertyData = new UniqueIdData(NodeTypeEnum.InputValue, addPropertyToResourceInstance.left().value().getUniqueId()); - - Either addPropRefResult = titanGenericDao.createRelation(inputData, propertyData, GraphEdgeLabels.GET_INPUT, props); - - if (addPropRefResult.isRight()) { - TitanOperationStatus status = addPropRefResult.right().value(); - log.debug("Failed to associate input {} to input value {} in graph. Status is {}", input.getUniqueId(), propertyData.getUniqueId(), status); - - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } - } - - return StorageOperationStatus.OK; - } - - private StorageOperationStatus cloneResourceInstanceInputsValues(TitanVertex toResourceInstanceVertex, ComponentInstance fromResourceInstance, String instanceId, Resource newResource, Map> inputsValuesMap) { - - Either, TitanOperationStatus> allProperties = inputOperation.getAllInputsOfResourceInstanceOnlyInputDefId(fromResourceInstance.getUniqueId()); - if (allProperties.isRight()) { - TitanOperationStatus status = allProperties.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - return storageStatus; - } - - List propertiesOnInstance = allProperties.left().value(); - if (propertiesOnInstance == null || propertiesOnInstance.isEmpty() == true) { - return StorageOperationStatus.OK; - } - - for (ComponentInstanceInput property : propertiesOnInstance) { - - // Only if valueUniqueId is not empty, then its belongs to the - // instance - if (property.getValueUniqueUid() != null) { - property.setValueUniqueUid(null); - List rules = property.getRules(); - if (rules != null) { - for (PropertyRule propertyRule : rules) { - propertyRule.replaceFirstToken(instanceId); - } - } - - } else { - continue; - } - - String resourceInstanceId = instanceId; - - Either counterRes = this.increaseAndGetResourceInstanceSpecificCounter(toResourceInstanceVertex, GraphPropertiesDictionary.INPUT_COUNTER); - - if (counterRes.isRight()) { - log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property); - StorageOperationStatus status = counterRes.right().value(); - return status; - } - Integer index = counterRes.left().value(); - - Either addPropertyToResourceInstance = this.addInputToResourceInstance(property, resourceInstanceId, index); - - if (addPropertyToResourceInstance.isRight()) { - TitanOperationStatus status = addPropertyToResourceInstance.right().value(); - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - return storageStatus; - } - } - - return StorageOperationStatus.OK; - } - - public Either updatePropertyValueInResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean inTransaction) { - - Either result = null; - - try { - // TODO: verify validUniqueId exists - Either eitherStatus = this.updatePropertyOfResourceInstance(resourceInstanceProperty, resourceInstanceId, true); - - 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 = propertyOperation.buildResourceInstanceProperty(propertyValueData, resourceInstanceProperty); - - log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); - - Either findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(resourceInstanceProperty.getPath(), propertyValueData.getUniqueId(), resourceInstanceProperty.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(); - } - } - } - - } - - private static final class UpdateDataContainer { - final Wrapper valueDataWrapper; - final Wrapper dataWrapper; - final GraphEdgeLabels graphEdge; - final Supplier> someDataClassGen; - final Supplier> someValueDataClassGen; - final NodeTypeEnum nodeType; - final NodeTypeEnum nodeTypeValue; - - private UpdateDataContainer(GraphEdgeLabels graphEdge, Supplier> someDataClassGen, Supplier> 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 getValueDataWrapper() { - return valueDataWrapper; - } - - public Wrapper getDataWrapper() { - return dataWrapper; - } - - public GraphEdgeLabels getGraphEdge() { - return graphEdge; - } - - public Supplier> getSomeDataClassGen() { - return someDataClassGen; - } - - public Supplier> getSomeValueDataClassGen() { - return someValueDataClassGen; - } - - public NodeTypeEnum getNodeType() { - return nodeType; - } - - public NodeTypeEnum getNodeTypeValue() { - return nodeTypeValue; - } - } - - @Override - public Either createOrUpdateAttributeOfResourceInstance(ComponentInstanceProperty attributeInstanceProperty, String resourceInstanceId) { - Either result; - // Create - if (attributeInstanceProperty.getValueUniqueUid() == null) { - Either counterRes = increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, true); - if (counterRes.isRight()) { - BeEcompErrorManager.getInstance().logInternalFlowError("createOrUpdateAttributeOfResourceInstance", "Failed to get AttributeValueData Counter", ErrorSeverity.ERROR); - result = Either.right(TitanOperationStatus.GENERAL_ERROR); - - } else { - result = addAttributeToResourceInstance(attributeInstanceProperty, resourceInstanceId, counterRes.left().value()); - } - } - // Update - else { - result = updateAttributeOfResourceInstance(attributeInstanceProperty, resourceInstanceId); - } - return result; - } - - /** - * update value of attribute on resource instance - * - * @param resourceInstanceAttribute - * @param resourceInstanceId - * @return - */ - private Either updateAttributeOfResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId) { - - Either result = null; - Wrapper errorWrapper = new Wrapper<>(); - UpdateDataContainer 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 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 addAttributeToResourceInstance(ComponentInstanceProperty attributeInstanceProperty, String resourceInstanceId, Integer index) { - Wrapper errorWrapper = new Wrapper<>(); - Wrapper compInsWrapper = new Wrapper<>(); - Wrapper attDataWrapper = new Wrapper<>(); - Wrapper 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()); - } - - } - - /** - * update value of attribute on resource instance - * - * @param resourceInstanceProerty - * @param resourceInstanceId - * @return - */ - public Either updatePropertyOfResourceInstance(ComponentInstanceProperty resourceInstanceProerty, String resourceInstanceId, boolean isValidate) { - - Wrapper errorWrapper = new Wrapper<>(); - UpdateDataContainer updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.PROPERTY_IMPL, (() -> PropertyData.class), (() -> PropertyValueData.class), NodeTypeEnum.Property, - NodeTypeEnum.PropertyValue); - - preUpdateElementOfResourceInstanceValidations(updateDataContainer, resourceInstanceProerty, resourceInstanceId, errorWrapper); - if (!errorWrapper.isEmpty()) { - return Either.right(errorWrapper.getInnerElement()); - } - - else { - String value = resourceInstanceProerty.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, 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 isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, isValidate, 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 pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProerty.getRules(), innerType, allDataTypes.left().value(), isValidate); - if (pair.getRight() != null && pair.getRight() == false) { - BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProerty.getName(), propertyType); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - propertyOperation.updateRulesInPropertyValue(propertyValueData, resourceInstanceProerty, resourceInstanceId); - - Either 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()); - } - } - - } - - /** - * update value of attribute on resource instance - * - * @param resourceInstanceProerty - * @param resourceInstanceId - * @return - */ - public Either updateInputOfResourceInstance(ComponentInstanceInput resourceInstanceProerty, String resourceInstanceId) { - - Wrapper errorWrapper = new Wrapper<>(); - UpdateDataContainer updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.INPUT_IMPL, (() -> PropertyData.class), (() -> InputValueData.class), NodeTypeEnum.Input, NodeTypeEnum.InputValue); - - preUpdateElementOfResourceInstanceValidations(updateDataContainer, resourceInstanceProerty, resourceInstanceId, errorWrapper); - if (!errorWrapper.isEmpty()) { - return Either.right(errorWrapper.getInnerElement()); - } - - else { - String value = resourceInstanceProerty.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, 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 isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value()); - * - * String newValue = value; if (isValid.isRight()) { Boolean res = isValid.right().value(); if (res == false) { return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } } else { Object object = isValid.left().value(); if (object != - * null) { newValue = object.toString(); } } InputValueData propertyValueData = updateDataContainer.getValueDataWrapper().getInnerElement(); log.debug("Going to update property value from " + propertyValueData.getValue() + " to " + - * newValue); propertyValueData.setValue(newValue); - * - * ImmutablePair pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProerty.getRules(), innerType, allDataTypes.left().value()); if (pair.getRight() != null && pair.getRight() == false) { - * BeEcompErrorManager.getInstance(). logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProerty.getName(), propertyType); return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } - * propertyOperation.updateRulesInPropertyValue(propertyValueData, resourceInstanceProerty, resourceInstanceId); - * - * Either 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()); } - */ - } - return null; - - } - - private void preUpdateElementOfResourceInstanceValidations(UpdateDataContainer updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, - String resourceInstanceId, Wrapper 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 void validateElementConnectedToInstance(UpdateDataContainer updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, - Wrapper errorWrapper) { - Either, 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 void validateElementConnectedToComponentInstanceExist(UpdateDataContainer updateDataContainer, - IComponentInstanceConnectedElement resourceInstanceProerty, Wrapper errorWrapper) { - String valueUniqueUid = resourceInstanceProerty.getValueUniqueUid(); - if (valueUniqueUid == null) { - errorWrapper.setInnerElement(TitanOperationStatus.INVALID_ID); - } else { - Either 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 void validateElementConnectedToComponentExist(UpdateDataContainer updateDataContainer, - IComponentInstanceConnectedElement resourceInstanceElementConnected, Wrapper errorWrapper) { - String uniqueId = resourceInstanceElementConnected.getUniqueId(); - Either 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 errorWrapper) { - validateRIExist(resourceInstanceId, null, errorWrapper); - } - - private void validateRIExist(String resourceInstanceId, Wrapper compInsDataWrapper, Wrapper errorWrapper) { - validateElementExistInGraph(resourceInstanceId, NodeTypeEnum.ResourceInstance, () -> ComponentInstanceData.class, compInsDataWrapper, errorWrapper); - } - - public void validateElementExistInGraph(String elementUniqueId, NodeTypeEnum elementNodeType, Supplier> elementClassGen, Wrapper elementDataWrapper, - Wrapper errorWrapper) { - Either 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 resourceInstanceProperty - * @param resourceInstanceId - * @param index - * @return - */ - public Either addPropertyToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isValidate, Integer index) { - - Either 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 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 isPropertyValueExists = propertyOperation.findPropertyValue(resourceInstanceId, propertyId); - if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) { - log.debug("The property {} already added to the resource instance {}", propertyId, resourceInstanceId); - resourceInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight()); - Either updatePropertyOfResourceInstance = updatePropertyOfResourceInstance(resourceInstanceProperty, resourceInstanceId, isValidate); - 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 innerType = null; - - PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition(); - String propertyType = propDataDef.getType(); - String value = resourceInstanceProperty.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, 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 isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, isValidate, 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 pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProperty.getRules(), innerType, allDataTypes.left().value(), isValidate); - log.debug("After validateAndUpdateRules. pair = {}", pair); - if (pair.getRight() != null && pair.getRight() == false) { - BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProperty.getName(), propertyType); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - propertyOperation.addRulesToNewPropertyValue(propertyValueData, resourceInstanceProperty, resourceInstanceId); - - log.debug("Before adding property value to graph {}", propertyValueData); - Either 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 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 {}", resourceInstanceId, uniqueId, operationStatus); - return Either.right(operationStatus); - } - - return Either.left(propertyValueData); - } else { - log.error("property value already exists."); - return Either.right(TitanOperationStatus.ALREADY_EXIST); - } - - } - - public Either addPropertyToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, TitanVertex resourceInstanceVertex, boolean isValidate, Integer index, String resourceInstanceId) { - - String propertyId = resourceInstanceProperty.getUniqueId(); - Either 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(); - - ImmutablePair isPropertyValueExists = propertyOperation.findPropertyValue(resourceInstanceId, propertyId); - if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) { - log.trace("The property {} already added to the resource instance {}", propertyId, resourceInstanceId); - resourceInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight()); - Either updatePropertyOfResourceInstance = updatePropertyOfResourceInstance(resourceInstanceProperty, resourceInstanceId, isValidate); - if (updatePropertyOfResourceInstance.isRight()) { - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR); - return Either.right(updatePropertyOfResourceInstance.right().value()); - } - return Either.right(TitanOperationStatus.OK); - } - - if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { - log.trace("After finding property value of {} on componenet instance {}", propertyId, resourceInstanceId); - return Either.right(isPropertyValueExists.getLeft()); - } - - String innerType = null; - - PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition(); - String propertyType = propDataDef.getType(); - String value = resourceInstanceProperty.getValue(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = propDataDef.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - innerType = propDef.getType(); - } - - log.trace("Before validateAndUpdatePropertyValue"); - Either, 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 isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes.left().value()); - log.trace("After validateAndUpdatePropertyValue. isValid = {}", isValid); - - String newValue = value; - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - - String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(resourceInstanceId, index); - PropertyValueData propertyValueData = new PropertyValueData(); - propertyValueData.setUniqueId(uniqueId); - propertyValueData.setValue(newValue); - - log.trace("Before validateAndUpdateRules"); - ImmutablePair pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProperty.getRules(), innerType, allDataTypes.left().value(), isValidate); - log.debug("After validateAndUpdateRules. pair = {} ", pair); - if (pair.getRight() != null && pair.getRight() == false) { - BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProperty.getName(), propertyType); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - propertyOperation.addRulesToNewPropertyValue(propertyValueData, resourceInstanceProperty, resourceInstanceId); - - log.trace("Before adding property value to graph {}", propertyValueData); - Either createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class); - log.trace("After adding property value to graph {}", propertyValueData); - - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - return Either.right(operationStatus); - } - propertyValueData = createNodeResult.left().value(); - - Either createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null); - - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus); - return Either.right(operationStatus); - } - - TitanOperationStatus edgeResult = titanGenericDao.createEdge(resourceInstanceVertex, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null); - - if (edgeResult != TitanOperationStatus.OK) { - log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, edgeResult); - return Either.right(edgeResult); - } - - ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, resourceInstanceProperty); - log.debug("The returned ResourceInstanceProperty is {} ", propertyValueResult); - - return Either.left(propertyValueResult); - } else { - log.debug("property value already exists."); - return Either.right(TitanOperationStatus.ALREADY_EXIST); - } - - } - - /** - * add property to resource instance - * - * @param resourceInstanceProperty - * @param resourceInstanceId - * @param index - * @return - */ - public Either addInputToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index) { - - Either 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 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 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 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, 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 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 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 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 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); - - } - - // inputOperation.associatePropertyToInput(resourceInstanceId, - // resourceInstanceInput.getInputId(), propertyValueData, - // resourceInstanceInput.getName()); - - return Either.left(createNodeResult.left().value()); - } else { - log.error("property value already exists."); - return Either.right(TitanOperationStatus.ALREADY_EXIST); - } - - } - - @Override - public Either addAttributeValueToResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction) { - Either result = null; - - try { - - Either 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 = attributeOperation.buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute); - log.debug("The returned ResourceInstanceAttribute is {}", attributeValueResult); - - result = Either.left(attributeValueResult); - return result; - } - } - - finally { - handleTransactionCommitRollback(inTransaction, result); - } - } - - @Override - public Either updateAttributeValueInResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, boolean inTransaction) { - - Either result = null; - - try { - Either 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 = attributeOperation.buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute); - log.debug("The returned ResourceInstanceAttribute is {}", attributeValueResult); - - result = Either.left(attributeValueResult); - return result; - } - } - - finally { - handleTransactionCommitRollback(inTransaction, result); - } - - } - - @Override - public Either addPropertyValueToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index, boolean inTransaction) { - return addPropertyValueToResourceInstance(resourceInstanceProperty, resourceInstanceId, true, index, inTransaction); - } - - @Override - public Either addPropertyValueToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isValidate, Integer index, boolean inTransaction) { - - /// #RULES SUPPORT - /// Ignore rules received from client till support - resourceInstanceProperty.setRules(null); - /// - /// - - Either result = null; - - try { - - Either eitherStatus = addPropertyToResourceInstance(resourceInstanceProperty, resourceInstanceId, isValidate, 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 = propertyOperation.buildResourceInstanceProperty(propertyValueData, resourceInstanceProperty); - log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); - - Either findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(resourceInstanceProperty.getPath(), resourceInstanceProperty.getUniqueId(), resourceInstanceProperty.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 addInputValueToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index, boolean inTransaction) { - - /// #RULES SUPPORT - /// Ignore rules received from client till support - resourceInstanceInput.setRules(null); - /// - /// - - Either result = null; - - try { - - Either 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 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(); - } - } - } - - } - - public Either, TitanOperationStatus> getComponentInstancesProperties(List resourceInstances, Map> alreadyProcessedResources, - Map> resourceInstancesProperties, Map> processedInstances, List path) { - - List result = new ArrayList<>(); - - for (ComponentInstance componentInstance : resourceInstances) { - - path.add(componentInstance.getUniqueId()); - - Either, TitanOperationStatus> componentInstancesProperties = getComponentInstanceProperties(componentInstance, alreadyProcessedResources, resourceInstancesProperties, processedInstances, path); - if (componentInstancesProperties.isRight()) { - TitanOperationStatus status = componentInstancesProperties.right().value(); - if (status != TitanOperationStatus.OK) { - return Either.right(status); - } - } - - List compInstancePropertyList = componentInstancesProperties.left().value(); - if (compInstancePropertyList != null) { - result.addAll(compInstancePropertyList); - } - - String uniqueId = componentInstance.getUniqueId(); - if (false == processedInstances.containsKey(uniqueId)) { - processedInstances.put(uniqueId, new ImmutablePair(componentInstance, path.size())); - } - path.remove(path.size() - 1); - - } - - return Either.left(result); - } - - //US831698 - public Either, StorageOperationStatus> getComponentInstancesPropertiesAndValuesFromGraph(ComponentInstance resourceInstance) { - - Map> alreadyProcessedResources = new HashMap<>(); - Map> alreadyProcessedInstances = new HashMap<>(); - Map> processedInstances = new HashMap<>(); - Map> resourceInstancesProperties = new HashMap<>(); - - List path = new ArrayList<>(); - path.add(resourceInstance.getUniqueId()); - Either, TitanOperationStatus> componentInstanceProperties = getComponentInstanceProperties(resourceInstance, alreadyProcessedResources, alreadyProcessedInstances, processedInstances, path); - - if (componentInstanceProperties.isRight()) { - StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(componentInstanceProperties.right().value()); - return Either.right(convertTitanStatusToStorageStatus); - } - - List listOfProps = componentInstanceProperties.left().value(); - resourceInstancesProperties.put(resourceInstance.getUniqueId(), listOfProps); - - processedInstances.put(resourceInstance.getUniqueId(), new ImmutablePair(resourceInstance, path.size())); - path.remove(path.size() - 1); - - Either>, TitanOperationStatus> findAllPropertiesValuesOnInstances = findAllPropertyValueOnInstances(processedInstances); - // 1. check status - if (findAllPropertiesValuesOnInstances.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findAllPropertiesValuesOnInstances.right().value())); - } - - propertyOperation.updatePropertiesByPropertyValues(resourceInstancesProperties, findAllPropertiesValuesOnInstances.left().value()); - - return Either.left(resourceInstancesProperties.get(resourceInstance.getUniqueId())); - } - - public Either, TitanOperationStatus> getComponentInstanceProperties(ComponentInstance resourceInstance, Map> alreadyProcessedResources, - Map> alreadyProcessedInstances, Map> processedInstances, List path) { - - // 1. Go over each instance - // 1.1 get all properties of from the parents of the instance - // 1.2 get all updated properties - // 1.3 find all instances included in the parent of this instance and - // run this method on them. - if (log.isDebugEnabled()) - log.debug("Going to update properties of resource instance {}", resourceInstance.getUniqueId()); - String resourceUid = resourceInstance.getComponentUid(); - - List properties = alreadyProcessedResources.get(resourceUid); - if (properties == null) { - properties = new ArrayList<>(); - TitanOperationStatus findAllRes = propertyOperation.findAllResourcePropertiesRecursively(resourceUid, properties); - if (findAllRes != TitanOperationStatus.OK) { - return Either.right(findAllRes); - } - alreadyProcessedResources.put(resourceUid, properties); - } - - if (log.isDebugEnabled()) - log.debug("After getting properties of resource {} . Number of properties is {}", resourceUid, (properties == null ? 0 : properties.size())); - List resourceInstancePropertyList = new ArrayList<>(); - if (false == properties.isEmpty()) { - - // TODO: WE MAY HAVE INDIRECT PROPERTY VALUE ALSO IN CASE NO - // PROPERTY ON THIS COMPONENT - - // String resourceInstanceUid = resourceInstance.getUniqueId(); - - for (PropertyDefinition propertyDefinition : properties) { - - String defaultValue = propertyDefinition.getDefaultValue(); - String value = defaultValue; - String valueUid = null; - - // String propertyId = propertyDefinition.getUniqueId(); - - ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty(propertyDefinition, value, valueUid); - - resourceInstanceProperty.setPath(cloneList(path)); - - // TODO: currently ignore constraints since they are not inuse - // and cause to error in convertion to object. - resourceInstanceProperty.setConstraints(null); - - resourceInstancePropertyList.add(resourceInstanceProperty); - - } - } - - OriginTypeEnum originType = resourceInstance.getOriginType(); - - Either, TitanOperationStatus> findInstancesUnderParentOfInstance = findInstancesUnderParentOfInstance(originType, resourceUid); - - if (findInstancesUnderParentOfInstance.isRight()) { - TitanOperationStatus status = findInstancesUnderParentOfInstance.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - return Either.right(status); - } - } else { - List listOfInstances = findInstancesUnderParentOfInstance.left().value(); - Either, TitanOperationStatus> componentInstancesProperties = getComponentInstancesProperties(listOfInstances, alreadyProcessedResources, alreadyProcessedInstances, processedInstances, path); - if (componentInstancesProperties.isRight()) { - TitanOperationStatus status = componentInstancesProperties.right().value(); - if (status != TitanOperationStatus.OK) { - return Either.right(status); - } - } - List currentList = componentInstancesProperties.left().value(); - if (currentList != null) { - resourceInstancePropertyList.addAll(currentList); - } - } - - return Either.left(resourceInstancePropertyList); - } - - public Either, TitanOperationStatus> findInstancesUnderParentOfInstance(OriginTypeEnum originType, String resourceUid) { - - NodeTypeEnum containerNodeType = null; - NodeTypeEnum compInstNodeType = null; - - switch (originType) { - - case VF: - containerNodeType = NodeTypeEnum.Resource; - compInstNodeType = NodeTypeEnum.Resource; - break; - case SERVICE: - containerNodeType = NodeTypeEnum.Service; - compInstNodeType = NodeTypeEnum.Resource; - break; - case PRODUCT: - containerNodeType = NodeTypeEnum.Product; - compInstNodeType = NodeTypeEnum.Service; - break; - case VFC: - case VFCMT: - case VL: - case CP: - break; - default: - break; - } - - if (containerNodeType == null || compInstNodeType == null) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - Either, List>, TitanOperationStatus> componentInstancesOfComponent = this.getComponentInstancesOfComponent(resourceUid, containerNodeType, compInstNodeType); - - if (componentInstancesOfComponent.isRight()) { - TitanOperationStatus status = componentInstancesOfComponent.right().value(); - log.debug("After getting instances of {} from type {}. Status is {}", resourceUid, originType, status); - return Either.right(status); - } else { - List listOfInstances = componentInstancesOfComponent.left().value().getLeft(); - if (log.isDebugEnabled()) { - String msg = "After getting instances of {} from type {} {}."; - log.debug(msg, resourceUid, originType, (listOfInstances != null ? listOfInstances.size() : 0)); - if (log.isTraceEnabled()) - log.trace(msg, resourceUid, originType, listOfInstances); - } - return Either.left(listOfInstances); - } - - } - - private List cloneList(List list) { - - if (list == null) { - return null; - } - - List clonedList = new ArrayList(); - clonedList.addAll(list); - - return clonedList; - } - - public Either>, TitanOperationStatus> findAllPropertyValueOnInstances(Map> processedInstances) { - - if (processedInstances == null) { - return Either.right(TitanOperationStatus.OK); - } - - Set>> entrySet = processedInstances.entrySet(); + String valueUniqueUid = resourceInstanceInput.getValueUniqueUid(); + if (valueUniqueUid == null) { - Map> propertyToInstanceValue = new HashMap<>(); + InputsData propertyData = findPropertyDefRes.left().value(); - for (Entry> entry : entrySet) { + ComponentInstanceData resourceInstanceData = findResInstanceRes.left().value(); - String compInstUniqueId = entry.getKey(); + ImmutablePair 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 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()); + */ + } - ImmutablePair pair = entry.getValue(); + if (isInputValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { + log.debug("After finding input value of {} on componenet instance {}", propertyId, resourceInstanceId); + return Either.right(isInputValueExists.getLeft()); + } - ComponentInstance componentInstance = pair.getLeft(); + String innerType = null; - Either, TitanOperationStatus> propeprtyValueOnCIResult = findPropertyValueOnComponentInstance(componentInstance); + PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition(); + String propertyType = propDataDef.getType(); + String value = resourceInstanceInput.getValue(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - if (propeprtyValueOnCIResult.isRight()) { - TitanOperationStatus status = propeprtyValueOnCIResult.right().value(); - if (status != TitanOperationStatus.OK) { - return Either.right(status); + 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); } - continue; + innerType = propDef.getType(); } - List propertyValuesOnCI = propeprtyValueOnCIResult.left().value(); - if (propertyValuesOnCI != null) { - for (ComponentInstanceProperty instanceProperty : propertyValuesOnCI) { - boolean result = addPropertyValue(compInstUniqueId, instanceProperty, propertyToInstanceValue); - if (!result) { - return Either.right(TitanOperationStatus.ALREADY_EXIST); - } - } + log.debug("Before validateAndUpdatePropertyValue"); + Either, 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); - return Either.left(propertyToInstanceValue); - } + log.debug("Before validateAndUpdateRules"); + ImmutablePair 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); - private boolean addPropertyValue(String compInstUniqueId, ComponentInstanceProperty instanceProperty, Map> propertyToInstanceValue) { + log.debug("Before adding property value to graph {}", propertyValueData); + Either createNodeResult = titanGenericDao.createNode(propertyValueData, InputValueData.class); + log.debug("After adding property value to graph {}", propertyValueData); - String propertyUid = instanceProperty.getUniqueId(); + if (createNodeResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + return Either.right(operationStatus); + } - Map map = propertyToInstanceValue.get(propertyUid); - if (map == null) { - map = new HashMap<>(); - propertyToInstanceValue.put(propertyUid, map); - } + Either createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.INPUT_IMPL, null); - ComponentInstanceProperty putIfAbsent = map.putIfAbsent(compInstUniqueId, instanceProperty); - if (putIfAbsent != null) { - BeEcompErrorManager.getInstance().logInternalUnexpectedError("find property value", "Found 2 values on the same instance", ErrorSeverity.ERROR); - return false; - } + 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); + } - return true; + Map properties1 = new HashMap(); - } + properties1.put(GraphEdgePropertiesDictionary.NAME.getProperty(), resourceInstanceData.getComponentInstDataDefinition().getName()); + properties1.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), resourceInstanceData.getComponentInstDataDefinition().getUniqueId()); - private boolean addInputValue(String compInstUniqueId, ComponentInstanceInput instanceProperty, Map> propertyToInstanceValue) { + createRelResult = titanGenericDao.createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.INPUT_VALUE, properties1); - String propertyUid = instanceProperty.getUniqueId(); + 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); - Map map = propertyToInstanceValue.get(propertyUid); - if (map == null) { - map = new HashMap<>(); - propertyToInstanceValue.put(propertyUid, map); - } + } - ComponentInstanceInput putIfAbsent = map.putIfAbsent(compInstUniqueId, instanceProperty); - if (putIfAbsent != null) { - BeEcompErrorManager.getInstance().logInternalUnexpectedError("find property value", "Found 2 values on the same instance", ErrorSeverity.ERROR); - return false; + return Either.left(createNodeResult.left().value()); + } else { + log.error("property value already exists."); + return Either.right(TitanOperationStatus.ALREADY_EXIST); } - return true; - } - private Either, TitanOperationStatus> findPropertyValueOnComponentInstance(ComponentInstance componentInstance) { - String resourceInstanceUid = componentInstance.getUniqueId(); - OriginTypeEnum originType = componentInstance.getOriginType(); - - NodeTypeEnum instanceNodeType = findInstanceNodeTypeEnumFromOriginType(originType); + @Override + public Either addAttributeValueToResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction) { + Either result = null; - Either, TitanOperationStatus> propertyValuesResult = propertyOperation.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceUid, instanceNodeType); + try { - log.debug("After fetching property under resource instance {}", resourceInstanceUid); - if (propertyValuesResult.isRight()) { - TitanOperationStatus status = propertyValuesResult.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - return Either.right(status); - } - return Either.right(TitanOperationStatus.OK); - } + Either eitherStatus = this.addAttributeToResourceInstance(resourceInstanceAttribute, resourceInstanceId, index); - return Either.left(propertyValuesResult.left().value()); + 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); - private NodeTypeEnum findInstanceNodeTypeEnumFromOriginType(OriginTypeEnum originType) { - NodeTypeEnum nodeType = NodeTypeEnum.ResourceInstance; - switch (originType) { - case SERVICE: - nodeType = NodeTypeEnum.ResourceInstance; - break; - default: - break; + result = Either.left(attributeValueResult); + return result; + } } - return nodeType; - } - - /** - * add capability property values to resource instance - * - * @param resourceInstanceId - * @param capability - * @param isNewlyCreatedResourceInstance - * @return - */ - public Either>, TitanOperationStatus> addCapabilityPropertyValuesToResourceInstance(String resourceInstanceId, CapabilityDefinition capability, boolean isNewlyCreatedResourceInstance) { - log.debug("Before adding capability property values to resource instance {}.", resourceInstanceId); - TitanOperationStatus error = null; - - Either>, TitanOperationStatus> addCapInstWithPropertiesRes = capabilityInstanceOperation.createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(resourceInstanceId, - capability.getUniqueId(), capability.getName(), capability.getProperties(), !isNewlyCreatedResourceInstance); - if (addCapInstWithPropertiesRes.isRight()) { - error = addCapInstWithPropertiesRes.right().value(); - log.debug("Failed to assotiate capability instance to resource instance {}. status is {}", resourceInstanceId, error); - } - log.debug("After adding capability property values to resource instance {}. Status is {}", resourceInstanceId, error); - if (error == null) { - return Either.left(addCapInstWithPropertiesRes.left().value()); + finally { + handleTransactionCommitRollback(inTransaction, result); } - return Either.right(error); } - public TitanOperationStatus addCapabilityPropertyValuesToResourceInstance(TitanVertex resourceInstanceVertex, String resourceInstanceId, CapabilityDefinition capability, boolean isNewlyCreatedResourceInstance) { - log.trace("Before adding capability property values to resource instance {}.", resourceInstanceId); - TitanOperationStatus error = TitanOperationStatus.OK; - - TitanOperationStatus addCapInstWithPropertiesRes = capabilityInstanceOperation.createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(resourceInstanceVertex, resourceInstanceId, capability.getUniqueId(), - capability.getName(), capability.getProperties(), !isNewlyCreatedResourceInstance); - if (addCapInstWithPropertiesRes != TitanOperationStatus.OK) { - error = addCapInstWithPropertiesRes; - log.debug("Failed to assotiate capability instance to resource instance {} . status is {}", resourceInstanceId, error); - } - log.debug("After adding capability property values to resource instance {}. Status is {}", resourceInstanceId, error); - - return error; + private ComponentInstanceProperty buildResourceInstanceAttribute(AttributeValueData attributeValueData, ComponentInstanceProperty resourceInstanceAttribute) { + Boolean hidden = attributeValueData.isHidden(); + String uid = attributeValueData.getUniqueId(); + return new ComponentInstanceProperty(hidden, resourceInstanceAttribute, uid); } - /** - * update capability property values of capability - * - * @param resourceInstanceId - * @param capabilityId - * @param propertyValues - * @return - */ - public Either, TitanOperationStatus> updateCapabilityPropertyValuesOfResourceInstance(String resourceInstanceId, String capabilityId, List propertyValues) { - log.debug("Before updating property values of capability {} of resource instance {}.", capabilityId, resourceInstanceId); - TitanOperationStatus error = null; - Either, TitanOperationStatus> updateCapabilityPropertyValuesRes = capabilityInstanceOperation.updateCapabilityPropertyValues(resourceInstanceId, capabilityId, propertyValues); - if (updateCapabilityPropertyValuesRes.isRight()) { - error = updateCapabilityPropertyValuesRes.right().value(); - log.debug("Failed to update property values of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error); - } - log.debug("After updating property values of capability {} of resource instance {}. Status is {}", capabilityId, resourceInstanceId, error); - if (error == null) { - return Either.left(updateCapabilityPropertyValuesRes.left().value()); - } - return Either.right(error); - } + @Override + public Either updateAttributeValueInResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, boolean inTransaction) { - /** - * delete property values of capability from resource instance - * - * @param capabilityId - * @param resourceInstanceId - * @return - */ - public Either deletePropertyValuesOfCapabilityFromResourceInstance(String capabilityId, String resourceInstanceId) { - log.debug("Before deleting property values of capability {} from resource instance {}.", capabilityId, resourceInstanceId); - TitanOperationStatus error = null; - Either deleteCapInstWithPropertiesRes = null; - Either getCapInstByCapabilityRes = capabilityInstanceOperation.getCapabilityInstanceOfCapabilityOfResourceInstance(resourceInstanceId, capabilityId); - if (getCapInstByCapabilityRes.isRight()) { - error = getCapInstByCapabilityRes.right().value(); - log.debug("Failed to retrieve capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error); - } - if (error == null) { - String capabilityInstanceId = getCapInstByCapabilityRes.left().value().getUniqueId(); - deleteCapInstWithPropertiesRes = capabilityInstanceOperation.deleteCapabilityInstanceFromResourceInstance(resourceInstanceId, capabilityInstanceId); - if (deleteCapInstWithPropertiesRes.isRight()) { - error = deleteCapInstWithPropertiesRes.right().value(); - log.debug("Failed to delete capability instance {} to resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); - } - } - log.debug("After deleting property values of capability {} from resource instance {}. Status is {}", capabilityId, resourceInstanceId, error); - if (error == null) { - return Either.left(deleteCapInstWithPropertiesRes.left().value()); - } - return Either.right(error); - } + Either result = null; - /** - * clone capability instances of resource instance - * - * @param createdComponentInstance - * @param resourceInstance - * @return - */ - private Either, List>, TitanOperationStatus> cloneCapabilityInstancesOfResourceInstance(ComponentInstanceData createdComponentInstance, ComponentInstance resourceInstance) { - TitanOperationStatus error = null; - String resourceInstanceId = resourceInstance.getUniqueId(); - log.debug("Before cloning of capability instances of resource instance {}.", resourceInstanceId); + try { + Either eitherAttributeValue = updateAttributeOfResourceInstance(resourceInstanceAttribute, resourceInstanceId); - Map, List> result = new HashMap<>(); - Either>, TitanOperationStatus> cloneAssociateCIWithPropertyValuesRes; - Either>, TitanOperationStatus> getAllCapabilityInstancesRes = capabilityInstanceOperation.getAllCapabilityInstancesOfResourceInstance(resourceInstanceId); - if (getAllCapabilityInstancesRes.isRight() && !getAllCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - error = getAllCapabilityInstancesRes.right().value(); - log.debug("Failed to get capability instances of component instance {}. status is {}", resourceInstanceId, error); - } - if (getAllCapabilityInstancesRes.isLeft()) { - List> capabilityInstances = getAllCapabilityInstancesRes.left().value(); - Map> allCapabilitiesMap = resourceInstance.getCapabilities(); - List allCapabilitiesList = new ArrayList<>(); - for (List curList : allCapabilitiesMap.values()) { - allCapabilitiesList.addAll(curList); - } - Map capabilities = allCapabilitiesList.stream().collect(Collectors.toMap(CapabilityDefinition::getUniqueId, Function.identity())); - String propertyName = GraphPropertiesDictionary.CAPABILITY_ID.getProperty(); - for (ImmutablePair capabilityInstPair : capabilityInstances) { - String capabilityId = (String) capabilityInstPair.getRight().getProperties().get(propertyName); - CapabilityDefinition relatedCapability = capabilities.get(capabilityId); - cloneAssociateCIWithPropertyValuesRes = capabilityInstanceOperation.cloneAssociateCapabilityInstanceWithPropertyValues(createdComponentInstance, relatedCapability, capabilityInstPair); - if (cloneAssociateCIWithPropertyValuesRes.isRight()) { - error = cloneAssociateCIWithPropertyValuesRes.right().value(); - log.debug("Failed to clone capability instances {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), resourceInstanceId, error); - break; - } else { - result.put(new ImmutablePair(cloneAssociateCIWithPropertyValuesRes.left().value().getLeft(), capabilityInstPair.getRight()), cloneAssociateCIWithPropertyValuesRes.left().value().getRight()); - } - } - } - log.debug("After cloning of capability instance of resource instance {}. Status is {}", resourceInstanceId, error); - if (error == null) { - return Either.left(result); - } - return Either.right(error); - } + 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(); - private Either>, TitanOperationStatus> cloneCapabilityInstancesOfResourceInstance(TitanVertex componentInstanceVertex, ComponentInstance resourceInstance) { - TitanOperationStatus error = null; - String resourceInstanceId = resourceInstance.getUniqueId(); - log.debug("Before cloning of capability instances of resource instance {}.", resourceInstanceId); + ComponentInstanceProperty attributeValueResult = buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute); + log.debug("The returned ResourceInstanceAttribute is {}", attributeValueResult); - Either cloneAssociateCIWithPropertyValuesRes = null; - Either>, TitanOperationStatus> getAllCapabilityInstancesRes = capabilityInstanceOperation.getAllCapabilityInstancesOfResourceInstance(resourceInstanceId); - if (getAllCapabilityInstancesRes.isRight() && getAllCapabilityInstancesRes.right().value() != TitanOperationStatus.NOT_FOUND) { - error = getAllCapabilityInstancesRes.right().value(); - log.debug("Failed to get capability instances of component instance {}. status is {}", resourceInstanceId, error); - } - List> list = new ArrayList<>(); - if (getAllCapabilityInstancesRes.isLeft()) { - List> capabilityInstances = getAllCapabilityInstancesRes.left().value(); - Map> allCapabilitiesMap = resourceInstance.getCapabilities(); - List allCapabilitiesList = new ArrayList<>(); - for (List curList : allCapabilitiesMap.values()) { - allCapabilitiesList.addAll(curList); - } - Map capabilities = allCapabilitiesList.stream().collect(Collectors.toMap(CapabilityDefinition::getUniqueId, Function.identity())); - String propertyName = GraphPropertiesDictionary.CAPABILITY_ID.getProperty(); - for (ImmutablePair capabilityInstPair : capabilityInstances) { - String capabilityId = (String) capabilityInstPair.getRight().getProperties().get(propertyName); - CapabilityDefinition relatedCapability = capabilities.get(capabilityId); - cloneAssociateCIWithPropertyValuesRes = capabilityInstanceOperation.cloneAssociateCapabilityInstanceWithPropertyValues(componentInstanceVertex, relatedCapability, capabilityInstPair); - if (cloneAssociateCIWithPropertyValuesRes.isRight()) { - error = cloneAssociateCIWithPropertyValuesRes.right().value(); - log.debug("Failed to clone capability instances {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), resourceInstanceId, error); - break; - } else { - list.add(new ImmutablePair(cloneAssociateCIWithPropertyValuesRes.left().value(), capabilityInstPair.right)); - } + result = Either.left(attributeValueResult); + return result; } } - log.debug("After cloning of capability instance of resource instance {}. Status is {}", resourceInstanceId, error); - if (error == null) { - return Either.left(list); + + finally { + handleTransactionCommitRollback(inTransaction, result); } - return Either.right(error); + } - public Either, StorageOperationStatus> getAllComponentInstancesMetadataOnly(String componentId, NodeTypeEnum containerNodeType) { + @Override + public Either addInputValueToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index, boolean inTransaction) { + + /// #RULES SUPPORT + /// Ignore rules received from client till support + resourceInstanceInput.setRules(null); + /// + /// - List componentInstancesResult = new ArrayList(); - Either, StorageOperationStatus> result = Either.left(componentInstancesResult); + Either result = null; - Either>, TitanOperationStatus> resourceInstancesRes = getAllComponentInstanceFromGraph(componentId, containerNodeType, false); + try { - if (resourceInstancesRes.isRight()) { + Either eitherStatus = addInputToResourceInstance(resourceInstanceInput, resourceInstanceId, index); - if (log.isDebugEnabled()) { - log.debug("Resource instance was found under service {} . status is {} ", componentId, resourceInstancesRes.right().value()); - } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceInstancesRes.right().value())); - } + 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(); - List> resourceInstances = resourceInstancesRes.left().value(); - if (resourceInstances != null && false == resourceInstances.isEmpty()) { + ComponentInstanceInput propertyValueResult = inputOperation.buildResourceInstanceInput(propertyValueData, resourceInstanceInput); + log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); - for (ImmutablePair immutablePair : resourceInstances) { - ComponentInstanceData resourceInstanceData = immutablePair.getKey(); - if (log.isDebugEnabled()) { - log.debug("Going to fetch the relationships of resource instance {}", resourceInstanceData); + Either findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(resourceInstanceInput.getPath(), resourceInstanceInput.getUniqueId(), resourceInstanceInput.getDefaultValue()); + if (findDefaultValue.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())); + return result; } - componentInstancesResult.add(new ComponentInstance(resourceInstanceData.getComponentInstDataDefinition())); + String defaultValue = findDefaultValue.left().value(); + propertyValueResult.setDefaultValue(defaultValue); + log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); + result = Either.left(propertyValueResult); + return result; } } - return result; - } - - public Either, TitanOperationStatus> updateCapDefPropertyValues(ComponentInstance componentInstance, List capabilityDefList) { - String componentInstanceId = componentInstance.getUniqueId(); - log.debug("Before updating property values of capabilities of component istance {}.", componentInstanceId); - TitanOperationStatus error = null; - NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentInstance.getOriginType().getInstanceType().trim()); - - log.debug("Before getting all capability instances of component istance {}.", componentInstanceId); - Either>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), componentInstanceId, GraphEdgeLabels.CAPABILITY_INST, - NodeTypeEnum.CapabilityInst, CapabilityInstData.class); - if (getCapabilityInstancesRes.isRight() && !getCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - error = getCapabilityInstancesRes.right().value(); - log.debug("Failed to retrieve capability Instances of resource instance {}. Status is {}", componentInstance.getName(), error); - } - log.debug("After getting all capability instances of component istance {}. Status is {}", componentInstanceId, error); - Map> overridedCapabilitiesHM = new HashMap<>(); - if (getCapabilityInstancesRes.isLeft()) { - List> capabilityInstDataPair = getCapabilityInstancesRes.left().value(); - - for (ImmutablePair curCapabilityPair : capabilityInstDataPair) { - CapabilityInstData curCapabilityInst = curCapabilityPair.getLeft(); - String curCapInstUid = curCapabilityInst.getUniqueId(); - - log.debug("Before getting all property values of capability instance {} of component istance {}.", curCapInstUid, componentInstanceId); - Either>, TitanOperationStatus> getOverridedPropertyValuesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curCapabilityInst.getLabel())), - curCapInstUid, GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class); - if (getOverridedPropertyValuesRes.isRight()) { - error = getOverridedPropertyValuesRes.right().value(); - log.debug("Failed to retrieve property values of capability instance {}. Status is {}", curCapInstUid, error); - } else { - log.debug("After getting all property values of capability instance {} of component istance {}. Status is {}", curCapInstUid, componentInstanceId, error); - Map overridedPropertyValuesHM = new HashMap<>(); - List> overridedPropertyValues = getOverridedPropertyValuesRes.left().value(); - for (ImmutablePair curPropertyValuePair : overridedPropertyValues) { - PropertyValueData curPropertyValue = curPropertyValuePair.getLeft(); - String propertyValueUid = curPropertyValue.getUniqueId(); - log.debug("Before getting property related to property value {} of capability instance {} of component istance {}.", propertyValueUid, curCapInstUid, componentInstanceId); - Either, TitanOperationStatus> getPropertyDataRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curPropertyValue.getLabel())), propertyValueUid, - GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class); - if (getPropertyDataRes.isRight()) { - error = getOverridedPropertyValuesRes.right().value(); - log.debug("Failed to retrieve property of property value {} Status is {}", propertyValueUid, error); - } - log.debug("After getting property related to property value {} of capability instance {} of component istance {}. Status is {}", propertyValueUid, curCapInstUid, componentInstanceId, error); - PropertyData propertyData = getPropertyDataRes.left().value().getLeft(); - overridedPropertyValuesHM.put((String) propertyData.getUniqueId(), curPropertyValue); - } - overridedCapabilitiesHM.put((String) curCapabilityPair.getRight().getProperties().get(GraphPropertiesDictionary.CAPABILITY_ID.getProperty()), overridedPropertyValuesHM); + 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(); } } } - if (error == null && !overridedCapabilitiesHM.isEmpty()) { - updateCapabilityPropertyValues(componentInstance.getCapabilities(), capabilityDefList, overridedCapabilitiesHM); - } - log.debug("After updating property values of capabilities of component istance {}. Status is {}", componentInstanceId, error); - if (error == null) { - return Either.left(capabilityDefList); - } - return Either.right(error); - } - private void updateCapabilityPropertyValues(Map> capabilitiesOfRI, List capabilitiesOfContainer, Map> overridedCapabilitiesHM) { - - capabilitiesOfContainer.stream().filter(capability -> overridedCapabilitiesHM.containsKey(capability.getUniqueId())).forEach(capability -> { - boolean updateProperties = false; - for (ComponentInstanceProperty property : capability.getProperties()) { - if (overridedCapabilitiesHM.get(capability.getUniqueId()).containsKey(property.getUniqueId())) { - property.setValue(overridedCapabilitiesHM.get(capability.getUniqueId()).get(property.getUniqueId()).getValue()); - property.setValueUniqueUid(overridedCapabilitiesHM.get(capability.getUniqueId()).get(property.getUniqueId()).getUniqueId()); - updateProperties = true; - } - } - if (updateProperties) { - capabilitiesOfRI.get(capability.getType()).get(0).setProperties(capability.getProperties()); - } - }); } @Override @@ -6059,13 +676,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo return null; } - public Either, StorageOperationStatus> fetchCIEnvArtifacts(String componentInstanceId) { - Either, StorageOperationStatus> result = artifactOperation.getArtifacts(componentInstanceId, NodeTypeEnum.ResourceInstance, true, ArtifactGroupTypeEnum.DEPLOYMENT.getType()); - if (result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND) - return Either.right(StorageOperationStatus.OK); - return result; - } - @Override public StorageOperationStatus updateCustomizationUUID(String componentInstanceId) { Either vertexByProperty = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId); @@ -6080,75 +690,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo return StorageOperationStatus.OK; } - private Either handleGroupInstanceNameLogic(TitanVertex ciVertex, GroupInstance groupInstance, String componentInstanceId, String componentInstanceName, String groupName) { - - groupInstance.setGroupName(groupName); - - String logicalName = groupInstanceOperation.createGroupInstLogicalName(componentInstanceName, groupName); - - Boolean eitherValidation = validateGroupInstanceName(logicalName, groupInstance, true); - if (!eitherValidation) { - return Either.right(false); - } - // groupInstance.setName(logicalName); - return Either.left(logicalName); - } - - private Boolean validateGroupInstanceName(String groupInstanceName, GroupInstance groupInstance, boolean isCreate) { - - if (!ValidationUtils.validateStringNotEmpty(groupInstanceName)) { - return false; - } - groupInstance.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(groupInstanceName)); - if (!isCreate) { - if (!ValidationUtils.validateResourceInstanceNameLength(groupInstanceName)) { - return false; - } - if (!ValidationUtils.validateResourceInstanceName(groupInstanceName)) { - return false; - } - } - - return true; - - } - // Evg: need to be public for reuse code in migration - public Either createGroupInstance(TitanVertex ciVertex, GroupDefinition groupDefinition, ComponentInstance componentInstance) { - // create VFC instance on VF - GroupInstance groupInstance = null; - - boolean isCreateName = false; - List groupInstances = componentInstance.getGroupInstances(); - if (groupInstances != null && !groupInstances.isEmpty()) { - Optional op = groupInstances.stream().filter(p -> p.getGroupUid().equals(groupDefinition.getUniqueId())).findAny(); - if (op.isPresent()) { - groupInstance = op.get(); - - } - } - if (groupInstance == null) { - groupInstance = new GroupInstance(); - groupInstance.setGroupUid(groupDefinition.getUniqueId()); - - groupInstance.setArtifacts(groupDefinition.getArtifacts()); - Either handleNameLogic = handleGroupInstanceNameLogic(ciVertex, groupInstance, componentInstance.getUniqueId(), componentInstance.getNormalizedName(), groupDefinition.getName()); - if (handleNameLogic.isRight() && !handleNameLogic.right().value()) { - - if (handleNameLogic.isRight()) { - log.debug("failed to create logical name gor group instance {}", groupInstance.getName()); - return Either.right(StorageOperationStatus.INVALID_ID); - - } - } - isCreateName = true; - // groupInstance.setName(handleNameLogic.left().value()); - - } - - return groupInstanceOperation.createGroupInstance(ciVertex, componentInstance.getUniqueId(), groupInstance, isCreateName); - - } - @Override public Either updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java deleted file mode 100644 index 9d9814efcb..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java +++ /dev/null @@ -1,2964 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import java.time.Duration; -import java.time.Instant; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.function.Function; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.ImmutableTriple; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.graph.GraphElementFactory; -import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; -import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; -import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; -import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint; -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.QueryType; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanGraphClient; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.category.GroupingDataDefinition; -import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; -import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.AdditionalInformationDefinition; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; -import org.openecomp.sdc.be.model.cache.ComponentCache; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.category.GroupingDefinition; -import org.openecomp.sdc.be.model.category.SubCategoryDefinition; -import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation; -import org.openecomp.sdc.be.model.operations.api.IArtifactOperation; -import org.openecomp.sdc.be.model.operations.api.ICapabilityOperation; -import org.openecomp.sdc.be.model.operations.api.IElementOperation; -import org.openecomp.sdc.be.model.operations.api.IRequirementOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator; -import org.openecomp.sdc.be.resources.data.ArtifactData; -import org.openecomp.sdc.be.resources.data.CapabilityData; -import org.openecomp.sdc.be.resources.data.ComponentMetadataData; -import org.openecomp.sdc.be.resources.data.ProductMetadataData; -import org.openecomp.sdc.be.resources.data.RequirementData; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import org.openecomp.sdc.be.resources.data.ServiceMetadataData; -import org.openecomp.sdc.be.resources.data.TagData; -import org.openecomp.sdc.be.resources.data.UniqueIdData; -import org.openecomp.sdc.be.resources.data.UserData; -import org.openecomp.sdc.be.resources.data.category.CategoryData; -import org.openecomp.sdc.be.resources.data.category.GroupingData; -import org.openecomp.sdc.be.resources.data.category.SubCategoryData; -import org.openecomp.sdc.be.utils.CommonBeUtils; -import org.openecomp.sdc.be.workers.Job; -import org.openecomp.sdc.be.workers.Manager; -import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; -import org.openecomp.sdc.common.util.StreamUtils; -import org.openecomp.sdc.common.util.ValidationUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; - -import com.google.common.collect.ImmutableSet; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanGraphQuery; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; - -public abstract class ComponentOperation { - private static Logger log = LoggerFactory.getLogger(ComponentOperation.class.getName()); - - @Autowired - protected TitanGenericDao titanGenericDao; - - @Autowired - protected IArtifactOperation artifactOperation; - - @Autowired - protected IElementOperation elementOperation; - - @Autowired - protected ICapabilityOperation capabilityOperation; - - @Autowired - protected IRequirementOperation requirementOperation; - - @Autowired - protected ComponentInstanceOperation componentInstanceOperation; - - @Autowired - private PropertyOperation propertyOperation; - - @Autowired - protected InputsOperation inputOperation; - - @Autowired - protected IAdditionalInformationOperation additionalInformationOperation; - - @Autowired - protected GroupOperation groupOperation; - - @Autowired - protected InputsOperation inputsOperation; - - @Autowired - protected ApplicationDataTypeCache applicationDataTypeCache; - - @Autowired - private ComponentCache componentCache; - - @Autowired - private ToscaDefinitionPathCalculator toscaDefinitionPathCalculator; - - private static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1"); - - protected Gson prettyJson = new GsonBuilder().setPrettyPrinting().create(); - - protected Either, StorageOperationStatus> createNewTagsList(List tags) { - - List existingTags = new ArrayList(); - List tagsToCreate = new ArrayList(); - Either, TitanOperationStatus> either = titanGenericDao.getAll(NodeTypeEnum.Tag, TagData.class); - - if ((either.isRight()) && (either.right().value() != TitanOperationStatus.NOT_FOUND)) { - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } else if (either.isLeft()) { - existingTags = either.left().value(); - } - - for (String tagName : tags) { - TagData tag = new TagData(tagName); - if ((existingTags == null) || (!existingTags.contains(tag))) { - tagsToCreate.add(tag); - } - } - return Either.left(tagsToCreate); - - } - - protected StorageOperationStatus createTagNodesOnGraph(List tagsToCreate) { - StorageOperationStatus result = StorageOperationStatus.OK; - // In order to avoid duplicate tags - tagsToCreate = ImmutableSet.copyOf(tagsToCreate).asList(); - if (tagsToCreate != null && false == tagsToCreate.isEmpty()) { - for (TagData tagData : tagsToCreate) { - log.debug("Before creating tag {}" , tagData); - Either createTagResult = titanGenericDao.createNode(tagData, TagData.class); - if (createTagResult.isRight()) { - TitanOperationStatus status = createTagResult.right().value(); - log.error("Cannot create {} in the graph. status is {}", tagData, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - - } - log.debug("After creating tag {}", tagData); - } - } - return result; - } - - public Either getLatestComponentByUuid(NodeTypeEnum nodeType, String uuid) { - Either getComponentResult = null; - Either latestComponentMetadataRes = getLatestComponentMetadataByUuid(nodeType, uuid, false); - if (latestComponentMetadataRes.isRight()) { - getComponentResult = Either.right(latestComponentMetadataRes.right().value()); - } - if (getComponentResult == null) { - ComponentMetadataData latestVersion = latestComponentMetadataRes.left().value(); - String id = latestVersion.getMetadataDataDefinition().getUniqueId(); - Either component = getComponent(id, false); - if (component.isRight()) { - log.debug("Couldn't fetch component with type {} and id {}, error: {}", nodeType, id, component.right().value()); - getComponentResult = Either.right(component.right().value()); - } else { - getComponentResult = Either.left(component.left().value()); - } - } - return getComponentResult; - } - - public Either getLatestComponentMetadataByUuid(NodeTypeEnum nodeType, String uuid, boolean inTransaction) { - - Either getComponentResult = null; - List latestVersionList = null; - ComponentMetadataData latestVersion = null; - - Map propertiesToMatch = new HashMap(); - propertiesToMatch.put(GraphPropertiesDictionary.UUID.getProperty(), uuid); - propertiesToMatch.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - try{ - Either, TitanOperationStatus> getComponentEither = titanGenericDao.getByCriteria(nodeType, propertiesToMatch, ComponentMetadataData.class); - if (getComponentEither.isRight()) { - log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", nodeType, uuid, getComponentEither.right().value()); - getComponentResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentEither.right().value())); - - } - if (getComponentResult == null) { - latestVersionList = getComponentEither.left().value(); - if (latestVersionList.isEmpty()) { - log.debug("Component with type {} and uuid {} was not found", nodeType, uuid); - getComponentResult = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - if (getComponentResult == null) { - latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0) - : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get(); - getComponentResult = Either.left(latestVersion); - } - } catch (Exception e){ - log.debug("Failed to get latest component metadata with type {} by uuid {}. ", nodeType.getName(), uuid, e); - }finally { - if (!inTransaction) { - titanGenericDao.commit(); - } - } - return getComponentResult; - } - - public Either getComponentByLabelAndId(String uniqueId, NodeTypeEnum nodeType, Class clazz) { - - Map propertiesToMatch = new HashMap(); - propertiesToMatch.put(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId); - Either, TitanOperationStatus> getResponse = titanGenericDao.getByCriteria(nodeType, propertiesToMatch, clazz); - if (getResponse.isRight()) { - log.debug("Couldn't fetch component with type {} and unique id {}, error: {}", nodeType, uniqueId, getResponse.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value())); - - } - List serviceDataList = getResponse.left().value(); - if (serviceDataList.isEmpty()) { - log.debug("Component with type {} and unique id {} was not found", nodeType, uniqueId); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - T serviceData = serviceDataList.get(0); - return Either.left(serviceData); - } - - /** - * - * @param component - * @param uniqueId - * @param nodeType - * @return - */ - protected TitanOperationStatus setComponentCreatorFromGraph(Component component, String uniqueId, NodeTypeEnum nodeType) { - Either, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.CREATOR, NodeTypeEnum.User, UserData.class); - if (parentNode.isRight()) { - return parentNode.right().value(); - } - - ImmutablePair value = parentNode.left().value(); - if (log.isDebugEnabled()) - log.debug("Found parent node {}", value); - UserData userData = value.getKey(); - if (log.isDebugEnabled()) - log.debug("Build resource : set creator userId to {}", userData.getUserId()); - String fullName = buildFullName(userData); - if (log.isDebugEnabled()) - log.debug("Build resource : set last modifier full name to {} ", fullName); - component.setCreatorUserId(userData.getUserId()); - component.setCreatorFullName(fullName); - - return TitanOperationStatus.OK; - } - - protected TitanOperationStatus setComponentLastModifierFromGraph(Component component, String uniqueId, NodeTypeEnum nodeType) { - - Either, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.LAST_MODIFIER, NodeTypeEnum.User, UserData.class); - if (parentNode.isRight()) { - return parentNode.right().value(); - } - - ImmutablePair value = parentNode.left().value(); - if (log.isDebugEnabled()) - log.debug("Found parent node {}", value); - UserData userData = value.getKey(); - - if (log.isDebugEnabled()) - log.debug("Build resource : set last modifier userId to {}", userData.getUserId()); - String fullName = buildFullName(userData); - if (log.isDebugEnabled()) - log.debug("Build resource : set last modifier full name to {}", fullName); - component.setLastUpdaterUserId(userData.getUserId()); - component.setLastUpdaterFullName(fullName); - - return TitanOperationStatus.OK; - } - - /** - * - * @param userData - * @return - */ - protected String buildFullName(UserData userData) { - - String fullName = userData.getFirstName(); - if (fullName == null) { - fullName = ""; - } else { - fullName = fullName + " "; - } - String lastName = userData.getLastName(); - if (lastName != null) { - fullName += lastName; - } - return fullName; - } - - protected Either findUser(String userId) { - String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User); - Either findUser = titanGenericDao.getNode(key, userId, UserData.class); - return findUser; - } - - protected Either findUserVertex(String userId) { - String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User); - return titanGenericDao.getVertexByProperty(key, userId); - } - - protected Either findGrouping(NodeTypeEnum nodeType, String groupingId) { - String key = UniqueIdBuilder.getKeyByNodeType(nodeType); - Either findGrouping = titanGenericDao.getNode(key, groupingId, GroupingData.class); - return findGrouping; - } - - protected Either findSubCategory(NodeTypeEnum nodeType, String subCategoryId) { - String key = UniqueIdBuilder.getKeyByNodeType(nodeType); - Either findSubCategory = titanGenericDao.getNode(key, subCategoryId, SubCategoryData.class); - return findSubCategory; - } - - protected Either findCategory(NodeTypeEnum nodeType, String categoryId) { - String key = UniqueIdBuilder.getKeyByNodeType(nodeType); - Either findCategory = titanGenericDao.getNode(key, categoryId, CategoryData.class); - return findCategory; - } - - protected TitanOperationStatus associateMetadataToComponent(ComponentMetadataData componentData, UserData userData, UserData updater, CategoryData categoryData, List derivedResources) { - - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.STATE.getProperty(), componentData.getMetadataDataDefinition().getState()); - Either result = titanGenericDao.createRelation(updater, componentData, GraphEdgeLabels.STATE, props); - log.debug("After associating user {} to component {}. Edge type is {}" , updater, componentData.getUniqueId(), GraphEdgeLabels.STATE); - if (result.isRight()) { - return result.right().value(); - } - - result = titanGenericDao.createRelation(updater, componentData, GraphEdgeLabels.LAST_MODIFIER, null); - log.debug("After associating user {} to component {}. Edge type is {}", updater, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER); - if (result.isRight()) { - log.error("Failed to associate user {} to component {}. Edge type is {}", updater, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER); - return result.right().value(); - } - - result = titanGenericDao.createRelation(userData, componentData, GraphEdgeLabels.CREATOR, null); - log.debug("After associating user {} to component {}. Edge type is {}" , userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR); - if (result.isRight()) { - log.error("Failed to associate user {} to component {}. Edge type is {}", userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR); - return result.right().value(); - } - - if (derivedResources != null) { - for (ResourceMetadataData derivedResource : derivedResources) { - log.debug("After associating component {} to parent component {}. Edge type is {}" ,componentData.getUniqueId(), derivedResource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM); - result = titanGenericDao.createRelation(componentData, derivedResource, GraphEdgeLabels.DERIVED_FROM, null); - if (result.isRight()) { - log.error("Failed to associate user {} to component {}. Edge type is {}", userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR); - return result.right().value(); - } - } - } - - if (categoryData != null) { - result = titanGenericDao.createRelation(componentData, categoryData, GraphEdgeLabels.CATEGORY, null); - log.debug("After associating component {} to category {}. Edge type is {}", componentData.getUniqueId(), categoryData, GraphEdgeLabels.CATEGORY); - if (result.isRight()) { - log.error("Faield to associate component {} to category {}. Edge type is {}", componentData.getUniqueId(), categoryData, GraphEdgeLabels.CATEGORY); - return result.right().value(); - } - } - - return TitanOperationStatus.OK; - } - - protected StorageOperationStatus associateArtifactsToComponent(NodeTypeEnum nodeType, ComponentMetadataData componentData, Map artifacts) { - - if (artifacts != null) { - for (Entry entry : artifacts.entrySet()) { - - ArtifactDefinition artifactDefinition = entry.getValue(); - Either addArifactToResource = Either.left(artifactDefinition); - addArifactToResource = artifactOperation.addArifactToComponent(artifactDefinition, (String) componentData.getUniqueId(), nodeType, false, true); - if (addArifactToResource.isRight()) { - return addArifactToResource.right().value(); - } - } - } - return StorageOperationStatus.OK; - - } - - protected Either validateResourceNameUniqueness(String name, Map hasProps, Map hasNotProps, TitanGenericDao titanGenericDao) { - if (hasProps == null) { - hasProps = new HashMap(); - } - String normalizedName = ValidationUtils.normaliseComponentName(name); - hasProps.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName); - - Either, TitanOperationStatus> resources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, hasProps, hasNotProps, ResourceMetadataData.class); - if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("failed to get resources from graph with property name: {}", name); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value())); - } - List resourceList = (resources.isLeft() ? resources.left().value() : null); - if (resourceList != null && resourceList.size() > 0) { - if (log.isDebugEnabled()) { - StringBuilder builder = new StringBuilder(); - for (ResourceMetadataData resourceData : resourceList) { - builder.append(resourceData.getUniqueId() + "|"); - } - log.debug("resources with property name:{} exists in graph. found {}",name, builder.toString()); - } - return Either.left(false); - } else { - log.debug("resources with property name:{} does not exists in graph", name); - return Either.left(true); - } - - } - - protected Either validateServiceNameUniqueness(String name, TitanGenericDao titanGenericDao) { - Map properties = new HashMap<>(); - String normalizedName = ValidationUtils.normaliseComponentName(name); - properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName); - - Either, TitanOperationStatus> services = titanGenericDao.getByCriteria(NodeTypeEnum.Service, properties, ServiceMetadataData.class); - if (services.isRight() && services.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("failed to get services from graph with property name: {}" , name); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(services.right().value())); - } - List serviceList = (services.isLeft() ? services.left().value() : null); - if (serviceList != null && serviceList.size() > 0) { - if (log.isDebugEnabled()) { - StringBuilder builder = new StringBuilder(); - for (ServiceMetadataData serviceData : serviceList) { - builder.append(serviceData.getUniqueId() + "|"); - } - log.debug("Service with property name:{} exists in graph. found {}" , name, builder.toString()); - } - - return Either.left(false); - } else { - log.debug("Service with property name:{} does not exists in graph", name); - return Either.left(true); - } - } - - protected Either validateToscaResourceNameUniqueness(String name, TitanGenericDao titanGenericDao) { - Map properties = new HashMap<>(); - - properties.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), name); - - Either, TitanOperationStatus> resources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, properties, ResourceMetadataData.class); - if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("failed to get resources from graph with property name: {}" , name); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value())); - } - List resourceList = (resources.isLeft() ? resources.left().value() : null); - if (resourceList != null && resourceList.size() > 0) { - if (log.isDebugEnabled()) { - StringBuilder builder = new StringBuilder(); - for (ResourceMetadataData resourceData : resourceList) { - builder.append(resourceData.getUniqueId() + "|"); - } - log.debug("resources with property name:{} exists in graph. found {}" , name, builder.toString()); - } - return Either.left(false); - } else { - log.debug("resources with property name:{} does not exists in graph", name); - return Either.left(true); - } - - } - - protected Either validateComponentNameUniqueness(String name, TitanGenericDao titanGenericDao, NodeTypeEnum type) { - Map properties = new HashMap<>(); - String normalizedName = ValidationUtils.normaliseComponentName(name); - properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName); - - Either, TitanOperationStatus> components = titanGenericDao.getByCriteria(type, properties, ComponentMetadataData.class); - if (components.isRight() && components.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("failed to get components from graph with property name: {}" , name); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(components.right().value())); - } - List componentList = (components.isLeft() ? components.left().value() : null); - if (componentList != null && componentList.size() > 0) { - if (log.isDebugEnabled()) { - StringBuilder builder = new StringBuilder(); - for (ComponentMetadataData componentData : componentList) { - builder.append(componentData.getUniqueId() + "|"); - } - log.debug("Component with property name:{} exists in graph. found {}" , name, builder.toString()); - } - - return Either.left(false); - } else { - log.debug("Component with property name:{} does not exists in graph", name); - return Either.left(true); - } - } - - protected StorageOperationStatus setArtifactFromGraph(String uniqueId, Component component, NodeTypeEnum type, IArtifactOperation artifactOperation) { - StorageOperationStatus result = StorageOperationStatus.OK; - Either, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(uniqueId, type, true); - if (artifacts.isRight()) { - result = artifacts.right().value(); - } else { - // component.setArtifacts(artifacts.left().value()); - createSpecificArtifactList(component, artifacts.left().value()); - } - return result; - } - - protected Component createSpecificArtifactList(Component component, Map artifacts) { - - if (artifacts != null) { - Map deploymentArtifacts = new HashMap<>(); - Map serviceApiArtifacts = new HashMap<>(); - Map toscaArtifacts = new HashMap<>(); - - Set> specificet = new HashSet<>(); - - for (Entry entry : artifacts.entrySet()) { - ArtifactDefinition artifact = entry.getValue(); - ArtifactGroupTypeEnum artifactGroupType = artifact.getArtifactGroupType(); - if (artifactGroupType == null) { - artifactGroupType = ArtifactGroupTypeEnum.INFORMATIONAL; - } - - switch (artifactGroupType) { - case DEPLOYMENT: - deploymentArtifacts.put(artifact.getArtifactLabel(), artifact); - specificet.add(entry); - break; - case SERVICE_API: - serviceApiArtifacts.put(artifact.getArtifactLabel(), artifact); - specificet.add(entry); - break; - case TOSCA: - toscaArtifacts.put(artifact.getArtifactLabel(), artifact); - specificet.add(entry); - break; - default: - break; - } - - } - artifacts.entrySet().removeAll(specificet); - - component.setSpecificComponetTypeArtifacts(serviceApiArtifacts); - component.setDeploymentArtifacts(deploymentArtifacts); - component.setToscaArtifacts(toscaArtifacts); - component.setArtifacts(artifacts); - } - return component; - } - - private Either, StorageOperationStatus> collectComponents(TitanGraph graph, NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class clazz, ResourceTypeEnum resourceType) { - List components = new ArrayList<>(); - Either>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(categoryType), categoryUid, GraphEdgeLabels.CATEGORY, neededType, clazz); - if (parentNodes.isLeft()) { - for (ImmutablePair component : parentNodes.left().value()) { - ComponentMetadataDataDefinition componentData = component.getLeft().getMetadataDataDefinition(); - Boolean isHighest = componentData.isHighestVersion(); - boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, componentData); - - if (isHighest && isMatchingResourceType) { - Either result = getLightComponent(componentData.getUniqueId(), true); - if (result.isRight()) { - return Either.right(result.right().value()); - } - components.add(result.left().value()); - } - } - } - return Either.left(components); - } - - private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType, - ComponentMetadataDataDefinition componentData) { - - boolean isMatching; - if (componentType == NodeTypeEnum.Resource) { - if (resourceType == null) { - isMatching = true; - } else { - isMatching = resourceType == ((ResourceMetadataDataDefinition)componentData).getResourceType(); - } - } else { - isMatching = true; - } - return isMatching; - } - - protected Either, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction, - Class clazz, ResourceTypeEnum resourceType) { - try { - Either graph = titanGenericDao.getGraph(); - if (graph.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); - - } - return collectComponents(graph.left().value(), neededType, categoryUid, categoryType, clazz, resourceType); - - } finally { - if (false == inTransaction) { - titanGenericDao.commit(); - } - } - } - - protected Either, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction, - Class clazz, ResourceTypeEnum resourceType) { - List components = new ArrayList<>(); - try { - Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class; - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); - Either, TitanOperationStatus> getCategory = titanGenericDao.getByCriteria(categoryType, props, categoryClazz); - if (getCategory.isRight()) { - return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); - } - Either graph = titanGenericDao.getGraph(); - if (graph.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); - - } - for (GraphNode category : getCategory.left().value()) { - Either, StorageOperationStatus> result = collectComponents(graph.left().value(), neededType, (String) category.getUniqueId(), categoryType, clazz, resourceType); - if (result.isRight()) { - return result; - } - components.addAll(result.left().value()); - } - - return Either.left(components); - } finally { - if (false == inTransaction) { - titanGenericDao.commit(); - } - } - } - - Either, StorageOperationStatus> getFilteredComponents(Map filters, boolean inTransaction, NodeTypeEnum neededType) { - return null; - } - - protected Either, StorageOperationStatus> getFollowedComponent(String userId, Set lifecycleStates, Set lastStateStates, boolean inTransaction, TitanGenericDao titanGenericDao, - NodeTypeEnum neededType) { - - Either, StorageOperationStatus> result = null; - - try { - Either graph = titanGenericDao.getGraph(); - if (graph.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); - return result; - } - Iterable users; - - if (userId == null) { - // get all users by label - // for Tester and Admin retrieve all users - - // users = - // graph.left().value().getVertices(GraphPropertiesDictionary.LABEL.getProperty(), - // NodeTypeEnum.User.getName()); - users = graph.left().value().query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()).vertices(); - - } else { - // for Designer retrieve specific user - String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User); - users = graph.left().value().query().has(key, userId).vertices(); - } - Iterator userIterator = users.iterator(); - - List components = new ArrayList<>(); - while (userIterator.hasNext()) { - Vertex vertexUser = userIterator.next(); - - // get all resource with current state - Iterator iterator = vertexUser.edges(Direction.OUT, GraphEdgeLabels.STATE.getProperty()); - - List componentsPerUser = fetchComponents(lifecycleStates, iterator, neededType, inTransaction); - - HashSet ids = new HashSet(); - - if (componentsPerUser != null) { - for (Component comp : componentsPerUser) { - ids.add(comp.getUniqueId()); - components.add(comp); - } - } - - if (lastStateStates != null && !lastStateStates.isEmpty()) { - // get all resource with last state - iterator = vertexUser.edges(Direction.OUT, GraphEdgeLabels.LAST_STATE.getProperty()); - boolean isFirst; - componentsPerUser = fetchComponents(lastStateStates, iterator, neededType, inTransaction); - if (componentsPerUser != null) { - for (Component comp : componentsPerUser) { - isFirst = true; - - if (ids.contains(comp.getUniqueId())) { - isFirst = false; - } - if (isFirst == true) { - components.add(comp); - } - - } - } - } - - } // whlile users - - result = Either.left(components); - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - titanGenericDao.rollback(); - } else { - titanGenericDao.commit(); - } - } - } - - } - - private List fetchComponents(Set lifecycleStates, Iterator iterator, NodeTypeEnum neededType, boolean inTransaction) { - List components = new ArrayList<>(); - while (iterator.hasNext()) { - Edge edge = iterator.next(); - - String stateStr = edge.value(GraphEdgePropertiesDictionary.STATE.getProperty()); - LifecycleStateEnum state = LifecycleStateEnum.findState(stateStr); - if (state == null) { - log.debug("not supported STATE for element {}" , stateStr); - continue; - } - if (lifecycleStates != null && lifecycleStates.contains(state)) { - Vertex vertexComponent = edge.inVertex(); - - Boolean isHighest = vertexComponent.value(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()); - if (isHighest) { - - String nodeTypeStr = vertexComponent.value(GraphPropertiesDictionary.LABEL.getProperty()); - // get only latest versions - NodeTypeEnum nodeType = NodeTypeEnum.getByName(nodeTypeStr); - - if (nodeType == null) { - log.debug("missing node label for vertex {}", vertexComponent); - continue; - } - - if (neededType.equals(nodeType)) { - switch (nodeType) { - case Service: - handleNode(components, vertexComponent, nodeType, inTransaction); - break; - case Resource: - Boolean isAbtract = vertexComponent.value(GraphPropertiesDictionary.IS_ABSTRACT.getProperty()); - if (false == isAbtract) { - handleNode(components, vertexComponent, nodeType, inTransaction); - } // if not abstract - break; - case Product: - handleNode(components, vertexComponent, nodeType, inTransaction); - break; - default: - log.debug("not supported node type {}", nodeType); - break; - }// case - } // needed type - } - } // if - } // while resources - return components; - } - - protected void handleNode(List components, Vertex vertexComponent, NodeTypeEnum nodeType, boolean inTransaction) { - String id; - - id = vertexComponent.value(UniqueIdBuilder.getKeyByNodeType(nodeType)); - if (id != null) { - Either component = getLightComponent(id, inTransaction); - if (component.isRight()) { - log.debug("Failed to get component for id = {} error : {} skip resource", id, component.right().value()); - } else { - components.add(component.left().value()); - } - } else { - - Map properties = this.titanGenericDao.getProperties(vertexComponent); - log.debug("missing resource unique id for node with properties {}", properties); - } - } - - /** - * - * @param component - * @param inTransaction - * @param titanGenericDao - * @param clazz - * @return - */ - public Either updateComponent(Component component, boolean inTransaction, TitanGenericDao titanGenericDao, Class clazz, NodeTypeEnum type) { - - ComponentParametersView componentParametersView = new ComponentParametersView(); - return updateComponentFilterResult(component, inTransaction, titanGenericDao, clazz, type, componentParametersView); - - } - - private Either generateAndUpdateToscaFileName(String componentType, String componentName, String componentId, NodeTypeEnum type, ArtifactDefinition artifactInfo) { - Map getConfig = (Map) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts().entrySet().stream() - .filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel())) - .findAny() - .get() - .getValue(); - artifactInfo.setArtifactName(componentType + "-" + componentName + getConfig.get("artifactName")); - return artifactOperation.updateToscaArtifactNameOnGraph(artifactInfo, artifactInfo.getUniqueId(), type, componentId); - } - - protected StorageOperationStatus moveCategoryEdge(Component component, ComponentMetadataData componentData, CategoryDefinition newCategory, NodeTypeEnum type) { - - StorageOperationStatus result = StorageOperationStatus.OK; - - GraphRelation categoryRelation = new GraphRelation(); - categoryRelation.setType(GraphEdgeLabels.CATEGORY.getProperty()); - RelationEndPoint relationEndPoint = new RelationEndPoint(type, UniqueIdBuilder.getKeyByNodeType(type), component.getUniqueId()); - categoryRelation.setFrom(relationEndPoint); - Either deleteOutgoingRelation = titanGenericDao.deleteOutgoingRelation(categoryRelation); - if (deleteOutgoingRelation.isRight()) { - log.error("Failed to delete category from component {}. Edge type is {}", componentData.getUniqueId(), GraphEdgeLabels.CATEGORY); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteOutgoingRelation.right().value()); - return result; - } - - log.debug("After removing edge from graph {}", deleteOutgoingRelation); - - NodeTypeEnum categoryType; - if (NodeTypeEnum.Service.name().equalsIgnoreCase(type.name())) { - categoryType = NodeTypeEnum.ServiceCategory; - } else { - categoryType = NodeTypeEnum.ResourceCategory; - } - Either categoryResult = elementOperation.getNewCategoryData(newCategory.getName(), NodeTypeEnum.ServiceNewCategory, CategoryData.class); - if (categoryResult.isRight()) { - StorageOperationStatus status = categoryResult.right().value(); - log.error("Cannot find category {} in the graph. status is {}", newCategory.getName(), status); - return status; - } - - CategoryData categoryData = categoryResult.left().value(); - Either createRelation = titanGenericDao.createRelation(componentData, categoryData, GraphEdgeLabels.CATEGORY, null); - log.debug("After associating category {} to component {}. Edge type is {}", categoryData, componentData.getUniqueId(), GraphEdgeLabels.CATEGORY); - if (createRelation.isRight()) { - log.error("Failed to associate category {} to component {}. Edge type is {}", categoryData, componentData.getUniqueId(), GraphEdgeLabels.CATEGORY); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value()); - return result; - } - - return result; - } - - private StorageOperationStatus moveLastModifierEdge(Component component, ComponentMetadataData componentData, UserData modifierUserData, NodeTypeEnum type) { - - StorageOperationStatus result = StorageOperationStatus.OK; - - GraphRelation lastModifierRelation = new GraphRelation(); - lastModifierRelation.setType(GraphEdgeLabels.LAST_MODIFIER.getProperty()); - RelationEndPoint relationEndPoint = new RelationEndPoint(type, UniqueIdBuilder.getKeyByNodeType(type), component.getUniqueId()); - lastModifierRelation.setTo(relationEndPoint); - Either deleteIncomingRelation = titanGenericDao.deleteIncomingRelation(lastModifierRelation); - if (deleteIncomingRelation.isRight()) { - log.error("Failed to delete user from component {}. Edge type is {}", componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteIncomingRelation.right().value()); - return result; - } - - Either createRelation = titanGenericDao.createRelation(modifierUserData, componentData, GraphEdgeLabels.LAST_MODIFIER, null); - log.debug("After associating user {} to component {}. Edge type is {}", modifierUserData, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER); - if (createRelation.isRight()) { - log.error("Failed to associate user {} to component {}. Edge type is {}", modifierUserData, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value()); - return result; - } - return result; - } - - protected abstract ComponentMetadataData getMetaDataFromComponent(Component component); - - public abstract Either getComponent(String id, boolean inTransaction); - - public abstract Either getComponent(String id, ComponentParametersView componentParametersView, boolean inTrasnaction); - - protected abstract Either getComponentByNameAndVersion(String name, String version, Map additionalParams, boolean inTransaction); - - public abstract Either getLightComponent(String id, boolean inTransaction); - - public abstract Either, StorageOperationStatus> getFilteredComponents(Map filters, boolean inTransaction); - - abstract Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData); - - abstract TitanOperationStatus setComponentCategoriesFromGraph(Component component); - - protected abstract Either getMetadataComponent(String id, boolean inTransaction); - - protected abstract Either updateComponent(T component, boolean inTransaction); - - protected abstract Either updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterParametersView); - - public abstract Either deleteComponent(String id, boolean inTransaction); - - public Either cloneComponent(T other, String version, boolean inTransaction) { - return cloneComponent(other, version, null, inTransaction); - } - - public abstract Either cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction); - - public abstract Component getDefaultComponent(); - - public abstract boolean isComponentExist(String componentId); - - public abstract Either validateComponentNameExists(String componentName); - - public abstract Either isComponentInUse(String componentId); - - protected Either isComponentInUse(String componentId, NodeTypeEnum nodeType) { - - Either relationByCriteria = titanGenericDao.getIncomingRelationByCriteria(new UniqueIdData(nodeType, componentId), GraphEdgeLabels.INSTANCE_OF, null); - if (relationByCriteria.isRight() && !relationByCriteria.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - log.debug("failed to check relations for component node. id = {}, type = {}, error = {}", componentId, nodeType, relationByCriteria.right().value().name()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(relationByCriteria.right().value())); - } - - if (relationByCriteria.isLeft()) { - // component is in use - return Either.left(true); - } else { - return Either.left(false); - } - - } - - public abstract Either, StorageOperationStatus> getAllComponentsMarkedForDeletion(); - - protected Either, StorageOperationStatus> getAllComponentsMarkedForDeletion(NodeTypeEnum nodeType) { - - List componentIdsToDelete = new ArrayList(); - // get all components marked for delete - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.IS_DELETED.getProperty(), true); - - Either, TitanOperationStatus> componentsToDelete = titanGenericDao.getByCriteria(nodeType, props, ComponentMetadataData.class); - - if (componentsToDelete.isRight()) { - TitanOperationStatus error = componentsToDelete.right().value(); - if (error.equals(TitanOperationStatus.NOT_FOUND)) { - log.trace("no components to delete"); - return Either.left(componentIdsToDelete); - } else { - log.info("failed to find components to delete. error : {}", error.name()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - } - - } - for (ComponentMetadataData resourceData : componentsToDelete.left().value()) { - componentIdsToDelete.add(resourceData.getMetadataDataDefinition().getUniqueId()); - } - return Either.left(componentIdsToDelete); - } - - protected Either, TitanOperationStatus> __getLastVersion(NodeTypeEnum type, Map props, Class clazz) { - try { - - Either graph = titanGenericDao.getGraph(); - if (graph.isRight()) { - return Either.right(graph.right().value()); - } - - TitanGraph tGraph = graph.left().value(); - TitanGraphQuery query = tGraph.query(); - query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), type.getName()); - - if (props != null && !props.isEmpty()) { - for (Map.Entry entry : props.entrySet()) { - query = query.hasNot(entry.getKey(), entry.getValue()); - } - } - query.has(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - - Iterable vertices = query.vertices(); - - if (vertices == null) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - Iterator iterator = vertices.iterator(); - List result = new ArrayList(); - - while (iterator.hasNext()) { - Vertex vertex = iterator.next(); - - Map newProp = titanGenericDao.getProperties(vertex); - T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node, newProp, clazz); - result.add(element); - } - if (result.size() == 0) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - log.debug("No nodes in graph for criteria : from type = {} and properties = {}", type, props); - return Either.left(result); - } catch (Exception e) { - log.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - } - - protected Either, TitanOperationStatus> getLastVersion(NodeTypeEnum type, Map hasNotProps, Class clazz) { - return getLastVersion(type, null, hasNotProps, clazz); - } - - protected Either, TitanOperationStatus> getLastVersion(NodeTypeEnum type, Map hasProps, Map hasNotProps, Class clazz) { - - Map props = new HashMap<>(); - - if (hasProps != null) { - props.putAll(hasProps); - } - props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - - Either, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(type, props, hasNotProps, clazz); - - return byCriteria; - - } - - public Either, StorageOperationStatus> getComponentCatalogData(NodeTypeEnum type, Map propertiesToMatch, Class clazz1, Class clazz2, boolean inTransaction) { - log.debug("Start getComponentCatalogData for type: {}", type.name()); - Set result = new HashSet(); - Either, TitanOperationStatus> lastVersionNodes = getLastVersion(type, propertiesToMatch, clazz2); - Either, StorageOperationStatus> last = retrieveComponentsFromNodes(lastVersionNodes, inTransaction); - if (last.isLeft() && last.left().value() != null) { - result.addAll(last.left().value()); - } - if (type == NodeTypeEnum.Resource) { - propertiesToMatch.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), false); - } - Either, TitanOperationStatus> componentsNodes = titanGenericDao.getByCriteria(type, propertiesToMatch, clazz2); - Either, StorageOperationStatus> certified = retrieveComponentsFromNodes(componentsNodes, inTransaction); - if (certified.isLeft() && certified.left().value() != null) { - result.addAll(certified.left().value()); - } - return Either.left(result); - - } - - protected Either, StorageOperationStatus> retrieveComponentsFromNodes(Either, TitanOperationStatus> componentsNodes, boolean inTransaction) { - Set result = new HashSet(); - if (componentsNodes.isRight()) { - // in case of NOT_FOUND from Titan client return to UI empty list - if (componentsNodes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - log.debug("No components were found"); - } else { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentsNodes.right().value())); - } - } else { - List componentDataList = componentsNodes.left().value(); - for (S componentData : componentDataList) { - // Either component = - // getComponent((String) componentData.getUniqueId(), - // inTransaction); - Either component = getLightComponent((String) componentData.getUniqueId(), inTransaction); - if (component.isRight()) { - log.debug("Failed to get component for id = {} error : {} skip resource", componentData.getUniqueId(), component.right().value()); - // return Either.right(service.right().value()); - } else { - result.add(component.left().value()); - } - } - } - return Either.left(result); - } - - protected StorageOperationStatus removeArtifactsFromComponent(Component component, NodeTypeEnum componentType) { - - String componentId = component.getUniqueId(); - // Map artifacts = component.getArtifacts(); - Either, StorageOperationStatus> artifactsRes = artifactOperation.getArtifacts(componentId, componentType, true); - if (artifactsRes.isRight() && !artifactsRes.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - return artifactsRes.right().value(); - } - if (artifactsRes.isLeft() && artifactsRes.left().value() != null) { - Map artifacts = artifactsRes.left().value(); - for (Entry entry : artifacts.entrySet()) { - - ArtifactDefinition artifactDefinition = entry.getValue(); - Either removeArifactFromResource = artifactOperation.removeArifactFromResource(componentId, artifactDefinition.getUniqueId(), componentType, true, true); - if (removeArifactFromResource.isRight()) { - return removeArifactFromResource.right().value(); - } - } - } - return StorageOperationStatus.OK; - } - - public Either, StorageOperationStatus> getTesterFollowedComponent(String userId, Set lifecycleStates, boolean inTransaction, NodeTypeEnum neededType) { - List resList = new ArrayList<>(); - Either, StorageOperationStatus> rip = getFollowedComponent(userId, lifecycleStates, null, inTransaction, titanGenericDao, neededType); - if (rip.isLeft()) { - List ripRes = rip.left().value(); - if (ripRes != null && !ripRes.isEmpty()) { - resList.addAll(ripRes); - } - Set rfcState = new HashSet<>(); - rfcState.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - Either, StorageOperationStatus> rfc = getFollowedComponent(null, rfcState, null, inTransaction, titanGenericDao, neededType); - if (rfc.isLeft()) { - List rfcRes = rfc.left().value(); - if (rfcRes != null && !rfcRes.isEmpty()) { - resList.addAll(rfcRes); - } - } else { - return Either.right(rfc.right().value()); - } - - } else { - return Either.right(rip.right().value()); - } - return Either.left(resList); - - } - - /** - * generate UUID only for case that version is "XX.01" - (start new version) - * - * @param component - */ - protected void generateUUID(Component component) { - String version = component.getVersion(); - if (uuidNewVersion.matcher(version).matches()) { - UUID uuid = UUID.randomUUID(); - component.getComponentMetadataDefinition().getMetadataDataDefinition().setUUID(uuid.toString()); - MDC.put("serviceInstanceID", uuid.toString()); - } - } - - protected Either, TitanOperationStatus> getVersionList(NodeTypeEnum type, String version, Component component, Class clazz) { - return getVersionList(type, version, component.getUUID(), component.getSystemName(), clazz); - } - - protected Either, TitanOperationStatus> getVersionList(NodeTypeEnum type, String version, String uuid, String systemName, Class clazz) { - Map props = new HashMap(); - Map hasNotProps = new HashMap(); - - if (version.startsWith("0")) { - props.put(GraphPropertiesDictionary.UUID.getProperty(), uuid); - } else { - props.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), systemName); - } - hasNotProps.put(GraphPropertiesDictionary.IS_DELETED.getProperty(), true); - Either, TitanOperationStatus> result = titanGenericDao.getByCriteria(type, props, hasNotProps, clazz); - - Map versionMap = new HashMap(); - if (result.isRight()) { - if (!result.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - return Either.right(result.right().value()); - } - - } else { - switch (type) { - case Resource: - List components = (List) result.left().value(); - for (ResourceMetadataData data : components) { - versionMap.put(data.getMetadataDataDefinition().getVersion(), (String) data.getUniqueId()); - } - break; - case Service: - List componentsS = (List) result.left().value(); - for (ServiceMetadataData data : componentsS) { - versionMap.put(data.getMetadataDataDefinition().getVersion(), (String) data.getUniqueId()); - } - break; - case Product: - List componentsP = (List) result.left().value(); - for (ProductMetadataData data : componentsP) { - versionMap.put(data.getMetadataDataDefinition().getVersion(), (String) data.getUniqueId()); - } - break; - default: - break; - } - } - - return Either.left(versionMap); - } - - protected StorageOperationStatus deleteAdditionalInformation(NodeTypeEnum nodeType, String componentId) { - - Either deleteRes = additionalInformationOperation.deleteAllAdditionalInformationParameters(nodeType, componentId, true); - - if (deleteRes.isRight()) { - StorageOperationStatus status = deleteRes.right().value(); - return status; - } - - return StorageOperationStatus.OK; - - } - - protected StorageOperationStatus addAdditionalInformation(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition informationDefinition) { - - Either status = additionalInformationOperation.addAdditionalInformationNode(nodeType, componentId, informationDefinition); - - if (status.isRight()) { - TitanOperationStatus titanStatus = status.right().value(); - return DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); - } - - log.trace("After adding additional information to component {}. Result is {}" , componentId ,status.left().value()); - - return StorageOperationStatus.OK; - - } - - protected StorageOperationStatus addAdditionalInformation(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition informationDefinition, TitanVertex metadataVertex) { - - TitanOperationStatus status = additionalInformationOperation.addAdditionalInformationNode(nodeType, componentId, informationDefinition, metadataVertex); - log.trace("After adding additional information to component {}. Result is {}", componentId, status); - - if (!status.equals(TitanOperationStatus.OK)) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - - return StorageOperationStatus.OK; - - } - - public Either, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType, boolean inTransacton) { - List artifacts = new ArrayList(); - Either, StorageOperationStatus> artifactsResponse = artifactOperation.getArtifacts(parentId, parentType, inTransacton); - if (artifactsResponse.isRight()) { - if (!artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - log.debug("failed to retrieve artifacts for {} {}", parentType, parentId); - return Either.right(artifactsResponse.right().value()); - } - } else { - artifacts.addAll(artifactsResponse.left().value().values()); - } - - if (NodeTypeEnum.Resource.equals(parentType)) { - Either, StorageOperationStatus> interfacesArtifactsForResource = getAdditionalArtifacts(parentId, false, true); - if (artifactsResponse.isRight() && !interfacesArtifactsForResource.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - log.debug("failed to retrieve interface artifacts for {} {}", parentType, parentId); - return Either.right(interfacesArtifactsForResource.right().value()); - } else if (artifactsResponse.isLeft()) { - artifacts.addAll(interfacesArtifactsForResource.left().value()); - } - } - return Either.left(artifacts); - } - - protected void addComponentInternalFields(ComponentMetadataData componentMetadataData) { - org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition metadataDataDefinition = componentMetadataData.getMetadataDataDefinition(); - Long creationDate = metadataDataDefinition.getCreationDate(); - - long currentDate = System.currentTimeMillis(); - if (creationDate == null) { - metadataDataDefinition.setCreationDate(currentDate); - } - metadataDataDefinition.setLastUpdateDate(currentDate); - - String lifecycleStateEnum = metadataDataDefinition.getState(); - if (lifecycleStateEnum == null) { - metadataDataDefinition.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - } - String componentUniqueId = UniqueIdBuilder.buildComponentUniqueId(); - metadataDataDefinition.setUniqueId(componentUniqueId); - metadataDataDefinition.setHighestVersion(true); - } - - protected StorageOperationStatus createTagsForComponent(Component component) { - List tags = component.getTags(); - if (tags != null && false == tags.isEmpty()) { - Either, StorageOperationStatus> tagsResult = createNewTagsList(tags); - - if (tagsResult == null) { - log.debug("tagsResult is null"); - return StorageOperationStatus.GENERAL_ERROR; - } - if (tagsResult.isRight()) { - return tagsResult.right().value(); - } - List tagsToCreate = tagsResult.left().value(); - return createTagNodesOnGraph(tagsToCreate); - } - log.trace("All tags created succesfully for component {}", component.getUniqueId()); - return StorageOperationStatus.OK; - } - - protected Either, StorageOperationStatus> findGroupingsForComponent(NodeTypeEnum nodeTypeEnum, Component component) { - List categories = component.getCategories(); - List groupingDataToAssociate = new ArrayList<>(); - if (categories != null) { - groupingDataToAssociate = new ArrayList<>(); - for (CategoryDefinition categoryDefinition : categories) { - List subcategories = categoryDefinition.getSubcategories(); - if (subcategories != null) { - for (SubCategoryDefinition subCategoryDefinition : subcategories) { - List groupingDataDefinitions = subCategoryDefinition.getGroupings(); - if (groupingDataDefinitions != null) { - for (GroupingDataDefinition grouping : groupingDataDefinitions) { - String groupingId = grouping.getUniqueId(); - Either findGroupingEither = findGrouping(nodeTypeEnum, groupingId); - if (findGroupingEither.isRight()) { - TitanOperationStatus status = findGroupingEither.right().value(); - log.error("Cannot find grouping {} in the graph. status is {}", groupingId, status); - if (status == TitanOperationStatus.NOT_FOUND) { - return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); - } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } else { - groupingDataToAssociate.add(findGroupingEither.left().value()); - } - } - } - } - } - } - } - return Either.left(groupingDataToAssociate); - } - - protected TitanOperationStatus associateGroupingsToComponent(ComponentMetadataData componentMetadataData, List groupingDataToAssociate) { - for (GroupingData groupingData : groupingDataToAssociate) { - GraphEdgeLabels groupingLabel = GraphEdgeLabels.GROUPING; - Either result = titanGenericDao.createRelation(componentMetadataData, groupingData, groupingLabel, null); - log.debug("After associating grouping {} to component {}. Edge type is {}", groupingData, componentMetadataData, groupingLabel); - if (result.isRight()) { - return result.right().value(); - } - } - log.trace("All groupings associated succesfully to component {}", componentMetadataData); - return TitanOperationStatus.OK; - } - - public abstract Either increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction); - - protected Either increaseAndGetComponentInstanceCounter(String componentId, NodeTypeEnum nodeType, boolean inTransaction) { - Either result = null; - try { - - Either graphResult = titanGenericDao.getGraph(); - if (graphResult.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); - return result; - } - Either vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId); - if (vertexService.isRight()) { - log.debug("failed to fetch vertex of component metadata, nodeType:{} , id: {}", nodeType, componentId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value())); - return result; - } - Vertex vertex = vertexService.left().value(); - Integer instanceCounter = vertex.value(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty()); - ++instanceCounter; - vertex.property(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty(), instanceCounter); - result = Either.left(instanceCounter); - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("increaseAndGetComponentInstanceCounter operation : Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("increaseAndGetComponentInstanceCounter operation : Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - protected Either setComponentInstanceCounter(String componentId, NodeTypeEnum nodeType, int counter, boolean inTransaction) { - Either result = null; - try { - - Either graphResult = titanGenericDao.getGraph(); - if (graphResult.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); - return result; - } - Either vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId); - if (vertexService.isRight()) { - log.debug("failed to fetch vertex of component metadata ofor id = {}", componentId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value())); - return result; - } - Vertex vertex = vertexService.left().value(); - vertex.property(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty(), counter); - result = Either.left(counter); - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("deleteService operation : Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("deleteService operation : Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - protected TitanOperationStatus setComponentInstancesFromGraph(String uniqueId, Component component, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType) { - - Either, List>, TitanOperationStatus> resourceInstancesOfService = componentInstanceOperation.getComponentInstancesOfComponent(uniqueId, containerNodeType, compInstNodeType); - - if (resourceInstancesOfService.isRight()) { - TitanOperationStatus status = resourceInstancesOfService.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } else { - log.error("Failed to fetch resource instances and their relations. status is {}", status); - } - return status; - } - - ImmutablePair, List> immutablePair = resourceInstancesOfService.left().value(); - List instances = immutablePair.getKey(); - List relations = immutablePair.getValue(); - - component.setComponentInstances(instances); - component.setComponentInstancesRelations(relations); - - return TitanOperationStatus.OK; - } - - /** - * set all properties of all of its resources - * - * @param uniqueId - * @return - */ - protected TitanOperationStatus ___setComponentInstancesPropertiesFromGraph(String uniqueId, Component component) { - - List resourceInstances = component.getComponentInstances(); - - Map> resourceInstancesProperties = new HashMap<>(); - - Map> alreadyProcessedResources = new HashMap<>(); - - if (resourceInstances != null) { - for (ComponentInstance resourceInstance : resourceInstances) { - - log.debug("Going to update properties of resource instance {}", resourceInstance.getUniqueId()); - String resourceUid = resourceInstance.getComponentUid(); - - List properties = alreadyProcessedResources.get(resourceUid); - if (properties == null) { - properties = new ArrayList<>(); - TitanOperationStatus findAllRes = propertyOperation.findAllResourcePropertiesRecursively(resourceUid, properties); - if (findAllRes != TitanOperationStatus.OK) { - return findAllRes; - } - alreadyProcessedResources.put(resourceUid, properties); - } - log.debug("After getting properties of resource {}. Number of properties is {}", resourceUid, (properties == null ? 0 : properties.size())); - if (false == properties.isEmpty()) { - - String resourceInstanceUid = resourceInstance.getUniqueId(); - - Either, TitanOperationStatus> propertyValuesRes = propertyOperation.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceUid); - log.debug("After fetching property under resource instance {}", resourceInstanceUid); - if (propertyValuesRes.isRight()) { - TitanOperationStatus status = propertyValuesRes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - return status; - } - } - - Map propertyIdToValue = new HashMap<>(); - populateMapperWithPropertyValues(propertyValuesRes, propertyIdToValue); - - List resourceInstancePropertyList = new ArrayList<>(); - for (PropertyDefinition propertyDefinition : properties) { - - String defaultValue = propertyDefinition.getDefaultValue(); - String value = defaultValue; - String valueUid = null; - - String propertyId = propertyDefinition.getUniqueId(); - ComponentInstanceProperty valuedProperty = propertyIdToValue.get(propertyId); - if (valuedProperty != null) { - String newValue = valuedProperty.getValue(); - // if (newValue != null) { - value = newValue; - // } - - valueUid = valuedProperty.getValueUniqueUid(); - log.trace("Found value {} under resource instance which override the default value {}" , value, defaultValue); - } - ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty(propertyDefinition, value, valueUid); - - // TODO: currently ignore constraints since they are not - // inuse and cause to error in convertion to object. - resourceInstanceProperty.setConstraints(null); - - resourceInstancePropertyList.add(resourceInstanceProperty); - - } - - resourceInstancesProperties.put(resourceInstanceUid, resourceInstancePropertyList); - } - - } - - component.setComponentInstancesProperties(resourceInstancesProperties); - } - - return TitanOperationStatus.OK; - } - - private void populateMapperWithPropertyValues(Either, TitanOperationStatus> propertyValuesRes, Map propertyIdToValue) { - - if (propertyValuesRes.isLeft()) { - List resourceInstanceValues = propertyValuesRes.left().value(); - if (resourceInstanceValues != null) { - for (ComponentInstanceProperty resourceInstanceProperty : resourceInstanceValues) { - propertyIdToValue.put(resourceInstanceProperty.getUniqueId(), resourceInstanceProperty); - } - } - } - } - - public abstract Either, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction); - - protected abstract StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type); - - protected abstract StorageOperationStatus updateDerived(Component component, Component currentComponent, ComponentMetadataData updatedResourceData, Class clazz); - - public abstract Either markComponentToDelete(Component componentToDelete, boolean inTransaction); - - protected Either internalMarkComponentToDelete(Component componentToDelete, boolean inTransaction) { - Either result = null; - - if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) { - // component already marked for delete - result = Either.left(componentToDelete); - return result; - } else { - - ComponentMetadataData componentMetaData = getMetaDataFromComponent(componentToDelete); - - componentMetaData.getMetadataDataDefinition().setIsDeleted(true); - componentMetaData.getMetadataDataDefinition().setHighestVersion(false); - componentMetaData.getMetadataDataDefinition().setLastUpdateDate(System.currentTimeMillis()); - try { - Either updateNode = titanGenericDao.updateNode(componentMetaData, ComponentMetadataData.class); - - StorageOperationStatus updateComponent; - if (updateNode.isRight()) { - log.debug("Failed to update component {}. status is {}", componentMetaData.getUniqueId(), updateNode.right().value()); - updateComponent = DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()); - result = Either.right(updateComponent); - return result; - } - - result = Either.left(componentToDelete); - return result; - } finally { - - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.error("updateResource operation : Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("updateResource operation : Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - - } - } - } - - private Either, TitanOperationStatus> convertReqDataListToReqDefList(ComponentInstance componentInstance, List> requirementData) { - ConvertDataToDef convertor = (instance, data, edge) -> convertReqDataToReqDef(instance, data, edge); - AddOwnerData dataAdder = (reqDef, compInstance) -> addOwnerDataReq(reqDef, compInstance); - return convertDataToDefinition(componentInstance, requirementData, convertor, dataAdder); - } - - private Either, TitanOperationStatus> convertCapDataListToCapDefList(ComponentInstance componentInstance, List> capabilityData) { - ConvertDataToDef convertor = (instance, data, edge) -> convertCapDataToCapDef(instance, data, edge); - AddOwnerData dataAdder = (capDef, compInstance) -> addOwnerDataCap(capDef, compInstance); - Either, TitanOperationStatus> convertationResult = convertDataToDefinition(componentInstance, capabilityData, convertor, dataAdder); - if (convertationResult.isLeft()) { - convertationResult = componentInstanceOperation.updateCapDefPropertyValues(componentInstance, convertationResult.left().value()); - } - return convertationResult; - } - - private Either convertCapDataToCapDef(ComponentInstance componentInstance, CapabilityData data, GraphEdge edge) { - Either eitherDef = capabilityOperation.getCapabilityByCapabilityData(data); - - if (eitherDef.isLeft()) { - CapabilityDefinition capDef = eitherDef.left().value(); - Map properties = edge.getProperties(); - if (properties != null) { - String name = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty()); - String source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty()); - List sourcesList = new ArrayList(); - capabilityOperation.getCapabilitySourcesList(source, sourcesList); - capDef.setName(name); - capDef.setCapabilitySources(sourcesList); - capDef.setPath(toscaDefinitionPathCalculator.calculateToscaDefinitionPath(componentInstance, edge)); - - String requiredOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty()); - if (requiredOccurrences != null) { - capDef.setMinOccurrences(requiredOccurrences); - } - String leftOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - if (leftOccurrences != null) { - capDef.setMaxOccurrences(leftOccurrences); - } - - } - eitherDef = Either.left(capDef); - } - return eitherDef; - } - - private Either convertReqDataToReqDef(ComponentInstance componentInstance, RequirementData data, GraphEdge edge) { - Either eitherDef = requirementOperation.getRequirement(data.getUniqueId()); - - if (eitherDef.isLeft()) { - RequirementDefinition requirementDef = eitherDef.left().value(); - Map properties = edge.getProperties(); - if (properties != null) { - String name = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty()); - requirementDef.setName(name); - String requiredOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty()); - if (requiredOccurrences != null) { - requirementDef.setMinOccurrences(requiredOccurrences); - } - requirementDef.setPath(toscaDefinitionPathCalculator.calculateToscaDefinitionPath(componentInstance, edge)); - String leftOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - if (leftOccurrences != null) { - requirementDef.setMaxOccurrences(leftOccurrences); - } - } - eitherDef = Either.left(requirementDef); - } - return eitherDef; - } - - private Either, TitanOperationStatus> convertDataToDefinition(ComponentInstance componentInstance, List> requirementData, ConvertDataToDef convertor, AddOwnerData dataAdder) { - Either, TitanOperationStatus> eitherResult; - // Convert Data To Definition - Stream> reqDefStream = requirementData.stream().map(e -> convertor.convert(componentInstance, e.left, e.right)); - - // Collect But Stop After First Error - List> filteredReqDefList = StreamUtils.takeWhilePlusOne(reqDefStream, p -> p.isLeft()).collect(Collectors.toList()); - Optional> optionalError = filteredReqDefList.stream().filter(p -> p.isRight()).findAny(); - if (optionalError.isPresent()) { - eitherResult = Either.right(optionalError.get().right().value()); - } else { - // Convert From Either To Definition And Collect - List reqDefList = filteredReqDefList.stream().map(e -> e.left().value()).collect(Collectors.toList()); - // Add Owner Data - reqDefList.forEach(e -> dataAdder.addData(e, componentInstance)); - eitherResult = Either.left(reqDefList); - } - - return eitherResult; - } - - interface ConvertDataToDef { - Either convert(ComponentInstance compInstance, Data d, GraphEdge edge); - } - - interface AddOwnerData { - void addData(Def def, ComponentInstance compInstance); - } - - private void addOwnerDataCap(CapabilityDefinition capDef, ComponentInstance componentInstance) { - capDef.setOwnerId(componentInstance.getUniqueId()); - capDef.setOwnerName(componentInstance.getName()); - } - - private void addOwnerDataReq(RequirementDefinition reqDef, ComponentInstance componentInstance) { - reqDef.setOwnerId(componentInstance.getUniqueId()); - reqDef.setOwnerName(componentInstance.getName()); - } - - public Either>, TitanOperationStatus> getRequirements(Component component, NodeTypeEnum nodeTypeEnum, boolean inTransaction) { - final HashMap> emptyMap = new HashMap<>(); - Either>, TitanOperationStatus> eitherResult = Either.left(emptyMap); - try { - List componentInstances = component.getComponentInstances(); - if (componentInstances != null) { - Function>, TitanOperationStatus>> dataCollector = e -> componentInstanceOperation.getRequirements(e, nodeTypeEnum); - Either>, TitanOperationStatus>>>, TitanOperationStatus> eitherDataCollected = collectDataFromComponentsInstances(componentInstances, - dataCollector); - if (eitherDataCollected.isRight()) { - eitherResult = Either.right(eitherDataCollected.right().value()); - } else { - // Converts Data to Def stop if encountered conversion error - DataDefConvertor someConvertor = (e1, e2) -> convertReqDataListToReqDefList(e1, e2); - Either>, TitanOperationStatus> fullDefList = convertDataToDefComponentLevel(eitherDataCollected.left().value(), someConvertor); - if (fullDefList.isRight()) { - eitherResult = Either.right(fullDefList.right().value()); - } else { - Stream defStream = fullDefList.left().value().stream().flatMap(e -> e.stream()); - // Collect to Map and using grouping by - Map> capTypeCapListMap = defStream.collect(Collectors.groupingBy(e -> e.getCapability())); - eitherResult = Either.left(capTypeCapListMap); - } - - } - - } - } finally { - if (inTransaction == false) { - titanGenericDao.commit(); - } - } - - return eitherResult; - } - - public Either>, TitanOperationStatus> getCapabilities(Component component, NodeTypeEnum nodeTypeEnum, boolean inTransaction) { - final HashMap> emptyMap = new HashMap<>(); - Either>, TitanOperationStatus> eitherResult = Either.left(emptyMap); - try { - List componentInstances = component.getComponentInstances(); - if (componentInstances != null) { - Function>, TitanOperationStatus>> dataCollector = e -> componentInstanceOperation.getCapabilities(e, nodeTypeEnum); - Either>, TitanOperationStatus>>>, TitanOperationStatus> eitherDataCollected = collectDataFromComponentsInstances(componentInstances, - dataCollector); - if (eitherDataCollected.isRight()) { - eitherResult = Either.right(eitherDataCollected.right().value()); - } else { - // Converts CapData to CapDef removes stop if encountered - // conversion error - DataDefConvertor someConvertor = (e1, e2) -> convertCapDataListToCapDefList(e1, e2); - Either>, TitanOperationStatus> fullDefList = convertDataToDefComponentLevel(eitherDataCollected.left().value(), someConvertor); - if (fullDefList.isRight()) { - eitherResult = Either.right(fullDefList.right().value()); - } else { - Stream defStream = fullDefList.left().value().stream().flatMap(e -> e.stream()); - // Collect to Map grouping by Type - Map> capTypeCapListMap = defStream.collect(Collectors.groupingBy(e -> e.getType())); - eitherResult = Either.left(capTypeCapListMap); - } - - } - - } - } finally { - if (inTransaction == false) { - titanGenericDao.commit(); - } - } - - return eitherResult; - } - - public Either>, TitanOperationStatus>>>, TitanOperationStatus> collectDataFromComponentsInstances(List componentInstances, - Function>, TitanOperationStatus>> dataGetter) { - Either>, TitanOperationStatus>>>, TitanOperationStatus> eitherResult; - - // Get List of Each componentInstance and it's Capabilities Data - Stream>, TitanOperationStatus>>> ownerDataStream = componentInstances.stream().map(element -> new ImmutablePair<>(element, dataGetter.apply(element))); - // Collect but stop after first error - List>, TitanOperationStatus>>> ownerCapDataList = StreamUtils - .takeWhilePlusOne(ownerDataStream, p -> p.right.isLeft() || p.right.isRight() && p.right.right().value() == TitanOperationStatus.NOT_FOUND).collect(Collectors.toList()); - - Optional>, TitanOperationStatus>>> optionalError = ownerCapDataList.stream() - .filter(p -> p.right.isRight() && p.right.right().value() != TitanOperationStatus.NOT_FOUND).findAny(); - if (optionalError.isPresent()) { - eitherResult = Either.right(optionalError.get().right.right().value()); - } else { - eitherResult = Either.left(ownerCapDataList.stream().filter(p -> p.right.isLeft()).collect(Collectors.toList())); - } - - return eitherResult; - } - - interface DataDefConvertor { - Either, TitanOperationStatus> convertDataToDefComponentInstance(ComponentInstance componentInstance, List> data); - } - - public Either>, TitanOperationStatus> convertDataToDefComponentLevel(List>, TitanOperationStatus>>> ownerCapDataList, - DataDefConvertor convertor) { - // Converts CapData to CapDef removes stop if encountered conversion - // error - TitanOperationStatus error = null; - List> defList = new ArrayList<>(); - for (int i = 0; i < ownerCapDataList.size(); i++) { - ImmutablePair>, TitanOperationStatus>> immutablePair = ownerCapDataList.get(i); - Either, TitanOperationStatus> convertCapDataListToCapDefList = convertor.convertDataToDefComponentInstance(immutablePair.left, immutablePair.right.left().value()); - if (convertCapDataListToCapDefList.isRight()) { - error = convertCapDataListToCapDefList.right().value(); - break; - } else { - defList.add(convertCapDataListToCapDefList.left().value()); - } - - } - Either>, TitanOperationStatus> eitherResult = (error != null) ? Either.right(error) : Either.left(defList); - return eitherResult; - - } - - private Map findLatestVersion(List resourceDataList) { - Map, ComponentMetadataData> latestVersionMap = new HashMap, ComponentMetadataData>(); - for (ComponentMetadataData resourceData : resourceDataList) { - ComponentMetadataData latestVersionData = resourceData; - - ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition(); - Pair pair = createKeyPair(latestVersionData); - if (latestVersionMap.containsKey(pair)) { - latestVersionData = latestVersionMap.get(pair); - String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion(); - String newVersion = metadataDataDefinition.getVersion(); - if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) { - latestVersionData = resourceData; - } - } - if (log.isDebugEnabled()) - log.debug("last certified version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion()); - - latestVersionMap.put(pair, latestVersionData); - } - - Map resVersionMap = new HashMap(); - for (ComponentMetadataData resourceData : latestVersionMap.values()) { - ComponentMetadataData latestVersionData = resourceData; - ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition(); - if (resVersionMap.containsKey(metadataDataDefinition.getUUID())) { - latestVersionData = resVersionMap.get(metadataDataDefinition.getUUID()); - String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion(); - String newVersion = metadataDataDefinition.getVersion(); - if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) { - latestVersionData = resourceData; - } - } - if (log.isDebugEnabled()) - log.debug("last uuid version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion()); - resVersionMap.put(latestVersionData.getMetadataDataDefinition().getUUID(), latestVersionData); - } - - return resVersionMap; - } - - private Pair createKeyPair(ComponentMetadataData metadataData) { - Pair pair = null; - NodeTypeEnum label = NodeTypeEnum.getByName(metadataData.getLabel()); - switch (label) { - case Resource: - pair = new ImmutablePair(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().name()); - break; - default: - pair = new ImmutablePair(metadataData.getMetadataDataDefinition().getName(), metadataData.getLabel()); - break; - } - - return pair; - } - - public Either, StorageOperationStatus> getLatestVersionNotAbstractComponentsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) { - try { - - // Map hasPpropertiesToMatch = new HashMap<>(); - // Map hasNotPpropertiesToMatch = new HashMap<>(); - List> properties = new ArrayList<>(); - if (componentTypeEnum.equals(ComponentTypeEnum.RESOURCE)) { - // hasPpropertiesToMatch.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), - // isAbstract); - properties.add(new ImmutableTriple<>(QueryType.HAS, GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), isAbstract)); - - if (internalComponentType != null) { - switch (internalComponentType.toLowerCase()) { - case "vf": - properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name())); -// properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name())); - // hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), - // ResourceTypeEnum.VF.name()); - break; - case "service": - properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VFC.name())); - properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VFCMT.name())); - properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.CVFC.name())); -// properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name())); - // hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), - // ResourceTypeEnum.VFC.name()); - break; - case "vl": - properties.add(new ImmutableTriple<>(QueryType.HAS, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name())); - // hasPpropertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), - // ResourceTypeEnum.VL.name()); - break; - default: - break; - } - } - } - // hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), - // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())); - // hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.IS_DELETED.getProperty(), - // true); - properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.IS_DELETED.getProperty(), true)); - // Either, TitanOperationStatus> - // resourceNodes = titanGenericDao.getByCriteria( - // componentTypeEnum.getNodeType(), hasPpropertiesToMatch, - // hasNotPpropertiesToMatch, - // ComponentMetadataData.class); - Either, TitanOperationStatus> resourceNodes = titanGenericDao.getByCriteria(componentTypeEnum.getNodeType(), ComponentMetadataData.class, properties); - if (resourceNodes.isRight()) { - // in case of NOT_FOUND from Titan client return to UI empty - // list - if (resourceNodes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - return Either.left(new ArrayList<>()); - } else { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceNodes.right().value())); - } - } else { - List resourceDataList = resourceNodes.left().value(); - Collection resCollection = resourceDataList; - if (isHighest != null && isHighest) { - Map latestVersionListMap = findLatestVersion(resourceDataList); - resCollection = latestVersionListMap.values(); - } - return Either.left(resCollection); - } - } finally { - titanGenericDao.commit(); - } - - } - - public Either, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List componentUids) { - try { - List result = new ArrayList<>(); - Map componentUidsMap = new HashMap<>(); - if (componentUids == null) { - Either, StorageOperationStatus> resourceNodes = getLatestVersionNotAbstractComponentsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType); - if (resourceNodes.isRight()) { - return Either.right(resourceNodes.right().value()); - } - Collection collection = resourceNodes.left().value(); - - if (collection == null) { - componentUids = new ArrayList<>(); - } else { - componentUids = collection.stream().map(p -> p.getMetadataDataDefinition().getUniqueId()).collect(Collectors.toList()); - // collection.forEach(p -> { - // if (NodeTypeEnum.Resource.getName().equals(p.getLabel())) - // { - // componentUidsMap.put(p.getMetadataDataDefinition().getUniqueId(), - // ((ResourceMetadataDataDefinition) - // p.getMetadataDataDefinition()).getResourceType()); - // } - // }); - - } - - } - if (false == componentUids.isEmpty()) { - - Manager manager = new Manager(); - int numberOfWorkers = 5; - - manager.init(numberOfWorkers); - for (String componentUid : componentUids) { - ComponentParametersView componentParametersView = buildComponentViewForNotAbstract(); - // ResourceTypeEnum type = - // componentUidsMap.get(componentUid); - // if (type != null && ResourceTypeEnum.VL.equals(type)) { - if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) { - componentParametersView.setIgnoreCapabilities(false); - componentParametersView.setIgnoreRequirements(false); - } - manager.addJob(new Job() { - @Override - public Either doWork() { - Either component = getComponent(componentUid, componentParametersView, false); - return component; - } - }); - } - LinkedBlockingQueue> res = manager.start(); - - for (Either resource : res) { - if (resource == null) { - if (log.isDebugEnabled()) - log.debug("Failed to fetch resource returned null "); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - if (resource.isRight()) { - if (log.isDebugEnabled()) - log.debug("Failed to fetch resource for error is {}", resource.right().value()); - return Either.right(resource.right().value()); - } - Component component = resource.left().value(); - component.setContactId(null); - component.setCreationDate(null); - component.setCreatorUserId(null); - component.setCreatorFullName(null); - component.setLastUpdateDate(null); - component.setLastUpdaterUserId(null); - component.setLastUpdaterFullName(null); - component.setNormalizedName(null); - result.add(resource.left().value()); - } - - if (componentUids.size() != result.size()) { - if (log.isDebugEnabled()) - log.debug("one of the workers failed to complete job "); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - } - - return Either.left(result); - - } finally { - titanGenericDao.commit(); - } - } - - private ComponentParametersView buildComponentViewForNotAbstract() { - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - // componentParametersView.setIgnoreRequirements(false); - // componentParametersView.setIgnoreCapabilities(false); - componentParametersView.setIgnoreCategories(false); - componentParametersView.setIgnoreAllVersions(false); - componentParametersView.setIgnoreAllVersions(false); - return componentParametersView; - } - - protected TitanOperationStatus setCapabilitiesFromGraph(String uniqueId, Component component, NodeTypeEnum nodeType) { - TitanOperationStatus titanStatus; - Either>, TitanOperationStatus> eitherCapabilities = getCapabilities(component, nodeType, true); - if (eitherCapabilities.isLeft()) { - titanStatus = TitanOperationStatus.OK; - Map> capabilities = eitherCapabilities.left().value(); - if (capabilities != null && !capabilities.isEmpty()) { - component.setCapabilities(capabilities); - } - } else { - titanStatus = eitherCapabilities.right().value(); - } - return titanStatus; - } - - protected TitanOperationStatus setRequirementsFromGraph(String uniqueId, Component component, NodeTypeEnum nodeType) { - TitanOperationStatus status; - Either>, TitanOperationStatus> eitherRequirements = getRequirements(component, nodeType, false); - if (eitherRequirements.isLeft()) { - status = TitanOperationStatus.OK; - Map> requirements = eitherRequirements.left().value(); - if (requirements != null && !requirements.isEmpty()) { - component.setRequirements(requirements); - } - } else { - status = eitherRequirements.right().value(); - } - return status; - } - - protected boolean isComponentExist(String componentId, NodeTypeEnum nodeType) { - boolean result = true; - Either compVertex = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId); - if (compVertex.isRight()) { - log.debug("failed to fetch vertex of component data for id {}", componentId); - result = false; - - } - return result; - } - - Either getLightComponent(String id, NodeTypeEnum nodeType, boolean inTransaction) { - - T component = null; - try { - log.debug("Starting to build light component of type {}, id {}", nodeType, id); - Either graphResult = titanGenericDao.getGraph(); - if (graphResult.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); - } - TitanGraph titanGraph = graphResult.left().value(); - Iterable vertecies = titanGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), id).vertices(); - if (vertecies != null) { - Iterator iterator = vertecies.iterator(); - if (iterator != null && iterator.hasNext()) { - Vertex vertex = iterator.next(); - Map resourceProperties = titanGenericDao.getProperties(vertex); - ComponentMetadataData componentMetadataData = GraphElementFactory.createElement(nodeType.getName(), GraphElementTypeEnum.Node, resourceProperties, ComponentMetadataData.class); - component = (T) convertComponentMetadataDataToComponent(componentMetadataData); - - // get creator - Iterator iterCreator = vertex.edges(Direction.IN, GraphEdgeLabels.CREATOR.name()); - if (iterCreator.hasNext() == false) { - log.debug("no creator was defined for component {}", id); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - Vertex vertexCreator = iterCreator.next().outVertex(); - UserData creator = GraphElementFactory.createElement(NodeTypeEnum.User.getName(), GraphElementTypeEnum.Node, titanGenericDao.getProperties(vertexCreator), UserData.class); - log.debug("Build component : set creator userId to {}", creator.getUserId()); - String fullName = buildFullName(creator); - log.debug("Build component : set creator full name to {}", fullName); - ((Component) component).setCreatorUserId(creator.getUserId()); - ((Component) component).setCreatorFullName(fullName); - - // get modifier - Iterator iterModifier = vertex.edges(Direction.IN, GraphEdgeLabels.LAST_MODIFIER.name()); - - if (iterModifier.hasNext() == false) { - log.debug("no modifier was defined for component {}", id); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - Vertex vertexModifier = iterModifier.next().outVertex(); - UserData modifier = GraphElementFactory.createElement(NodeTypeEnum.User.getName(), GraphElementTypeEnum.Node, titanGenericDao.getProperties(vertexModifier), UserData.class); - log.debug("Build component : set last modifier userId to {}", creator.getUserId()); - fullName = buildFullName(modifier); - log.debug("Build component : set last modifier full name to {}", fullName); - ((Component) component).setLastUpdaterUserId(modifier.getUserId()); - ((Component) component).setLastUpdaterFullName(fullName); - - // get category - TitanOperationStatus status = setComponentCategoriesFromGraph((Component) component); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } else { - // Nothing found - log.debug("Component with id {} not found", id); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - } else { - // Nothing found - log.debug("Component with id {} not found", id); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - log.debug("Ended to build light component of type {}, id {}", nodeType, id); - return Either.left(component); - } finally { - if (false == inTransaction) { - titanGenericDao.commit(); - } - } - } - - Either getMetadataComponent(String id, NodeTypeEnum nodeType, boolean inTransaction) { - Component component = null; - try { - log.debug("Starting to build metadata component of type {}, id {}", nodeType, id); - Either graphResult = titanGenericDao.getGraph(); - if (graphResult.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); - } - TitanGraph titanGraph = graphResult.left().value(); - Iterable vertecies = titanGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), id).vertices(); - if (vertecies != null) { - Iterator iterator = vertecies.iterator(); - if (iterator != null && iterator.hasNext()) { - Vertex vertex = iterator.next(); - Map resourceProperties = titanGenericDao.getProperties(vertex); - ComponentMetadataData componentMetadataData = GraphElementFactory.createElement(nodeType.getName(), GraphElementTypeEnum.Node, resourceProperties, ComponentMetadataData.class); - component = convertComponentMetadataDataToComponent(componentMetadataData); - } else { - // Nothing found - log.debug("Component with id {} not found", id); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - } else { - // Nothing found - log.debug("Component with id {} not found", id); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - log.debug("Ended to build metadata component of type {}, id {}", nodeType, id); - return Either.left(component); - } finally { - if (false == inTransaction) { - titanGenericDao.commit(); - } - } - } - - public Either getComponentInstanceCoutner(String origServiceId, NodeTypeEnum nodeType) { - Either result; - Either graphResult = titanGenericDao.getGraph(); - if (graphResult.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); - return result; - } - Either vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), origServiceId); - if (vertexService.isRight()) { - log.debug("failed to fetch vertex of component metadata, nodeType:{} , id: {}", nodeType, origServiceId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value())); - return result; - } - Vertex vertex = vertexService.left().value(); - Integer instanceCounter = vertex.value(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty()); - return Either.left(instanceCounter); - } - - protected TitanOperationStatus setComponentInstancesPropertiesFromGraph(Component component) { - - List resourceInstances = component.getComponentInstances(); - - Map> resourceInstancesProperties = new HashMap<>(); - - Map> alreadyProcessedResources = new HashMap<>(); - - Map> alreadyProcessedInstances = new HashMap<>(); - - Map> processedInstances = new HashMap<>(); - - if (resourceInstances != null) { - - for (ComponentInstance resourceInstance : resourceInstances) { - - List path = new ArrayList<>(); - path.add(resourceInstance.getUniqueId()); - Either, TitanOperationStatus> componentInstanceProperties = componentInstanceOperation.getComponentInstanceProperties(resourceInstance, alreadyProcessedResources, alreadyProcessedInstances, - processedInstances, path); - - if (componentInstanceProperties.isRight()) { - TitanOperationStatus status = componentInstanceProperties.right().value(); - if (status != TitanOperationStatus.OK) { - return status; - } - } - - List listOfProps = componentInstanceProperties.left().value(); - String resourceInstanceUid = resourceInstance.getUniqueId(); - resourceInstancesProperties.put(resourceInstanceUid, listOfProps); - - // alreadyProcessedInstances.put(resourceInstance.getUniqueId(), - // resourceInstance); - - processedInstances.put(resourceInstance.getUniqueId(), new ImmutablePair(resourceInstance, path.size())); - path.remove(path.size() - 1); - - } - - } - - Either>, TitanOperationStatus> findAllPropertiesValuesOnInstances = componentInstanceOperation.findAllPropertyValueOnInstances(processedInstances); - // 1. check status - if (findAllPropertiesValuesOnInstances.isRight()) { - TitanOperationStatus status = findAllPropertiesValuesOnInstances.right().value(); - if (status != TitanOperationStatus.OK) { - return status; - } - } - // 2. merge data from rules on properties (resourceInstancesProperties) - propertyOperation.updatePropertiesByPropertyValues(resourceInstancesProperties, findAllPropertiesValuesOnInstances.left().value()); - - component.setComponentInstancesProperties(resourceInstancesProperties); - - return TitanOperationStatus.OK; - } - - protected TitanOperationStatus setComponentInstancesInputsFromGraph(String uniqueId, Component component) { - - Map> resourceInstancesInputs = new HashMap<>(); - TitanOperationStatus status = TitanOperationStatus.OK; - List componentInstances = component.getComponentInstances(); - if (componentInstances != null) { - for (ComponentInstance resourceInstance : componentInstances) { - Either, TitanOperationStatus> eitherRIAttributes = inputOperation.getAllInputsOfResourceInstance(resourceInstance); - if (eitherRIAttributes.isRight()) { - if (eitherRIAttributes.right().value() != TitanOperationStatus.NOT_FOUND) { - status = eitherRIAttributes.right().value(); - break; - } - } else { - resourceInstancesInputs.put(resourceInstance.getUniqueId(), eitherRIAttributes.left().value()); - } - } - if (!resourceInstancesInputs.isEmpty()) - component.setComponentInstancesInputs(resourceInstancesInputs); - } - - return status; - } - - public Either getInvariantUUID(NodeTypeEnum nodeType, String componentId, boolean inTransaction) { - Either res = null; - try { - Either vertexByProperty = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId); - if (vertexByProperty.isRight()) { - TitanOperationStatus status = vertexByProperty.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - res = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } else { - Vertex v = vertexByProperty.left().value(); - String invariantUUID = v.value(GraphPropertiesDictionary.INVARIANT_UUID.getProperty()); - - if (invariantUUID == null || invariantUUID.isEmpty()) { - - log.info("The component {} has empty invariant UUID.", componentId); - res = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.INVALID_ELEMENT)); - - } - res = Either.left(invariantUUID); - } - } finally { - if (false == inTransaction) { - titanGenericDao.commit(); - } - } - return res; - } - - protected TitanOperationStatus setGroupsFromGraph(String uniqueId, Component component, NodeTypeEnum nodeTypeEnum) { - - Either, TitanOperationStatus> res = groupOperation.getAllGroupsFromGraph(uniqueId, nodeTypeEnum); - if (res.isRight()) { - TitanOperationStatus status = res.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - return TitanOperationStatus.OK; - } else { - return status; - } - } - component.setGroups(res.left().value()); - - return TitanOperationStatus.OK; - - } - - protected TitanOperationStatus setComponentInputsFromGraph(String uniqueId, Component component, boolean inTransaction) { - - List inputs = new ArrayList<>(); - TitanOperationStatus status = inputsOperation.findAllResourceInputs(uniqueId, inputs); - if (status == TitanOperationStatus.OK) { - component.setInputs(inputs); - } - - return status; - - } - - protected StorageOperationStatus deleteGroups(NodeTypeEnum nodeType, String componentId) { - - Either, StorageOperationStatus> deleteRes = groupOperation.deleteAllGroups(componentId, nodeType, true); - - if (deleteRes.isRight()) { - StorageOperationStatus status = deleteRes.right().value(); - return status; - } - - return StorageOperationStatus.OK; - - } - - protected StorageOperationStatus removeInputsFromComponent(NodeTypeEnum typeEnum, Component component) { - Either, StorageOperationStatus> deleteAllInputsAssociatedToNode = inputsOperation.deleteAllInputsAssociatedToNode(typeEnum, component.getUniqueId()); - return deleteAllInputsAssociatedToNode.isRight() ? deleteAllInputsAssociatedToNode.right().value() : StorageOperationStatus.OK; - } - - protected TitanOperationStatus associateInputsToComponent(NodeTypeEnum nodeType, ComponentMetadataData resourceData, List properties) { - - Either, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - log.debug("Cannot find any data type. Status is {}.", status); - return status; - } - - Map convertedProperties = new HashMap<>(); - - if (properties != null) { - for (InputDefinition propertyDefinition : properties) { - convertedProperties.put(propertyDefinition.getName(), propertyDefinition); - } - - Either, TitanOperationStatus> operationStatus = inputsOperation.addInputsToGraph(resourceData.getMetadataDataDefinition().getUniqueId(), nodeType, convertedProperties, allDataTypes.left().value()); - if (operationStatus.isLeft()) - return TitanOperationStatus.OK; - else - return operationStatus.right().value(); - } - - return TitanOperationStatus.OK; - - } - - protected TitanOperationStatus associateInputsToComponent(TitanVertex metadataVertex, String componentId, List properties) { - - Either, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - log.debug("Cannot find any data type. Status is {}.", status); - return status; - } - - Map convertedProperties = new HashMap<>(); - - if (properties != null) { - for (InputDefinition propertyDefinition : properties) { - convertedProperties.put(propertyDefinition.getName(), propertyDefinition); - } - - return inputsOperation.addInputsToGraph(metadataVertex, componentId, convertedProperties, allDataTypes.left().value()); - } - - return TitanOperationStatus.OK; - - } - - public Either, StorageOperationStatus> getAllComponentInstncesMetadata(String componentId, NodeTypeEnum nodeType) { - Instant start = Instant.now(); - Either, StorageOperationStatus> resourceInstancesOfService = componentInstanceOperation.getAllComponentInstancesMetadataOnly(componentId, nodeType); - Instant end = Instant.now(); - log.debug("TOTAL TIME BL GET INSTANCES: {}", Duration.between(start, end)); - return resourceInstancesOfService; - } - - @Deprecated - public Either, ActionStatus> getComponentsFromCacheForCatalog(Set components, ComponentTypeEnum componentType) { - - Either, List, Set>, ActionStatus> componentsForCatalog = componentCache.getComponentsForCatalog(components, componentType); - if (componentsForCatalog.isLeft()) { - ImmutableTriple, List, Set> immutableTriple = componentsForCatalog.left().value(); - List foundComponents = immutableTriple.getLeft(); - - if (foundComponents != null) { - // foundComponents.forEach(p -> result.add((Resource)p)); - log.debug("The number of {}s added to catalog from cache is {}", componentType.name().toLowerCase(), foundComponents.size()); - - } - List foundDirtyComponents = immutableTriple.getMiddle(); - Set nonCachedComponents = immutableTriple.getRight(); - int numberDirtyResources = foundDirtyComponents == null ? 0 : foundDirtyComponents.size(); - int numberNonCached = nonCachedComponents == null ? 0 : nonCachedComponents.size(); - log.debug("The number of left {}s for catalog is {}", componentType.name().toLowerCase(), numberDirtyResources + numberNonCached); - return Either.left(foundComponents); - } - - return Either.right(componentsForCatalog.right().value()); - } - - public Either, TitanOperationStatus> getListOfHighestComponents(NodeTypeEnum nodeTypeEnum, Class clazz) { - - long startFetchAllStates = System.currentTimeMillis(); - Map propertiesToMatchHigest = new HashMap<>(); - propertiesToMatchHigest.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - Either, TitanOperationStatus> allHighestStates = titanGenericDao.getByCriteria(nodeTypeEnum, propertiesToMatchHigest, clazz); - if (allHighestStates.isRight() && allHighestStates.right().value() != TitanOperationStatus.NOT_FOUND) { - return Either.right(allHighestStates.right().value()); - } - long endFetchAllStates = System.currentTimeMillis(); - - if (allHighestStates.isRight()) { - return Either.left(new ArrayList<>()); - } - List services = allHighestStates.left().value(); - - List certifiedHighest = new ArrayList<>(); - List notCertifiedHighest = new ArrayList<>(); - for (T reData : services) { - if (reData.getMetadataDataDefinition().getState().equals(LifecycleStateEnum.CERTIFIED.name())) { - certifiedHighest.add(reData); - } else { - notCertifiedHighest.add(reData); - } - } - - log.debug("Fetch catalog {}s all states: certified {}, noncertified {}", nodeTypeEnum.getName(), certifiedHighest.size(), notCertifiedHighest.size()); - log.debug("Fetch catalog {}s all states from graph took {} ms", nodeTypeEnum.getName(), endFetchAllStates - startFetchAllStates); - - HashMap serviceNames = new HashMap<>(); - for (T data : notCertifiedHighest) { - String serviceName = data.getMetadataDataDefinition().getName(); - serviceNames.put(serviceName, serviceName); - } - - for (T data : certifiedHighest) { - String serviceName = data.getMetadataDataDefinition().getName(); - if (!serviceNames.containsKey(serviceName)) { - notCertifiedHighest.add(data); - } - } - - return Either.left(notCertifiedHighest); - } - - protected Either getComponentFromCacheIfUpToDate(String uniqueId, ComponentMetadataData componentMetadataData, ComponentParametersView componentParametersView, Class clazz, - ComponentTypeEnum componentTypeEnum) { - - long start = System.currentTimeMillis(); - try { - - long lastModificationTime = componentMetadataData.getMetadataDataDefinition().getLastUpdateDate(); - Either cacheComponentRes = this.componentCache.getComponent(uniqueId, lastModificationTime); - if (cacheComponentRes.isLeft()) { - Component cachedComponent = cacheComponentRes.left().value(); - - // Must calculate allVersions - if (false == componentParametersView.isIgnoreAllVersions()) { - Class clazz1 = null; - switch (componentTypeEnum) { - case RESOURCE: - clazz1 = ResourceMetadataData.class; - break; - case SERVICE: - clazz1 = ServiceMetadataData.class; - break; - case PRODUCT: - clazz1 = ProductMetadataData.class; - break; - default: - break; - } - if (clazz1 != null) { - Either, TitanOperationStatus> versionList = getVersionList(componentTypeEnum.getNodeType(), cachedComponent.getVersion(), cachedComponent.getUUID(), cachedComponent.getSystemName(), clazz1); - if (versionList.isRight()) { - return Either.right(ActionStatus.GENERAL_ERROR); - } - - Map allVersions = versionList.left().value(); - cachedComponent.setAllVersions(allVersions); - } else { - return Either.right(ActionStatus.GENERAL_ERROR); - } - } - if (componentParametersView != null) { - cachedComponent = componentParametersView.filter(cachedComponent, componentTypeEnum); - } - return Either.left(clazz.cast(cachedComponent)); - } - - return Either.right(cacheComponentRes.right().value()); - - } finally { - log.trace("Fetch component {} with uid {} from cache took {} ms", componentTypeEnum.name().toLowerCase(), uniqueId, System.currentTimeMillis() - start); - } - } - - public Either, Set>, ActionStatus> getComponentsFromCacheForCatalog(Map components, ComponentTypeEnum componentType) { - - Either, Set>, ActionStatus> componentsForCatalog = componentCache.getComponentsForCatalog(components, componentType); - if (componentsForCatalog.isLeft()) { - ImmutablePair, Set> immutablePair = componentsForCatalog.left().value(); - List foundComponents = immutablePair.getLeft(); - - if (foundComponents != null) { - // foundComponents.forEach(p -> result.add((Resource)p)); - log.debug("The number of {}s added to catalog from cache is {}", componentType.name().toLowerCase(), foundComponents.size()); - } - Set leftComponents = immutablePair.getRight(); - int numberNonCached = leftComponents == null ? 0 : leftComponents.size(); - log.debug("The number of left {}s for catalog is {}", componentType.name().toLowerCase(), numberNonCached); - - ImmutablePair, Set> result = new ImmutablePair, Set>(foundComponents, leftComponents); - return Either.left(result); - } - - return Either.right(componentsForCatalog.right().value()); - } - - /** - * - * @param component - * @param inTransaction - * @param titanGenericDao - * @param clazz - * @return - */ - public Either updateComponentFilterResult(Component component, boolean inTransaction, TitanGenericDao titanGenericDao, Class clazz, NodeTypeEnum type, ComponentParametersView filterResult) { - Either result = null; - - try { - - log.debug("In updateComponent. received component uid = {}", (component == null ? null : component.getUniqueId())); - if (component == null) { - log.error("Service object is null"); - result = Either.right(StorageOperationStatus.BAD_REQUEST); - return result; - } - - ComponentMetadataData componentData = getMetaDataFromComponent(component); - - log.debug("After converting component to componentData. ComponentData = {}", componentData); - - if (componentData.getUniqueId() == null) { - log.error("Resource id is missing in the request."); - return Either.right(StorageOperationStatus.BAD_REQUEST); - } - - Either counterStatus = this.getComponentInstanceCoutner(component.getUniqueId(), component.getComponentType().getNodeType()); - - if (counterStatus.isRight()) { - - log.error("Cannot find componentInstanceCounter for component {} in the graph. status is {}", componentData.getUniqueId(), counterStatus); - // result = sendError(status, - // StorageOperationStatus.USER_NOT_FOUND); - return result; - } - - componentData.setComponentInstanceCounter(counterStatus.left().value()); - - String modifierUserId = component.getLastUpdaterUserId(); - if (modifierUserId == null || modifierUserId.isEmpty()) { - log.error("UserId is missing in the request."); - result = Either.right(StorageOperationStatus.BAD_REQUEST); - return result; - } - Either findUser = findUser(modifierUserId); - - if (findUser.isRight()) { - TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user {} in the graph. status is {}", modifierUserId, status); - // result = sendError(status, - // StorageOperationStatus.USER_NOT_FOUND); - return result; - } - - UserData modifierUserData = findUser.left().value(); - String resourceId = component.getUniqueId(); - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreUsers(false); - componentParametersView.setIgnoreCategories(false); - componentParametersView.setIgnoreDerivedFrom(false); - componentParametersView.setIgnoreArtifacts(false); - Either currentComponentResult = this.getComponent(resourceId, componentParametersView, inTransaction); - if (currentComponentResult.isRight()) { - log.error("Cannot find resource with id {} in the graph.", resourceId); - result = Either.right(currentComponentResult.right().value()); - return result; - } - - Component currentComponent = (Component) currentComponentResult.left().value(); - String currentModifier = currentComponent.getLastUpdaterUserId(); - - if (currentModifier.equals(modifierUserData.getUniqueId())) { - log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier."); - } else { - log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId); - StorageOperationStatus status = moveLastModifierEdge(component, componentData, modifierUserData, type); - log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - return result; - } - } - final long currentTimeMillis = System.currentTimeMillis(); - log.debug("Going to update the last Update Date of the resource from {} to {}", component.getLastUpdateDate(), currentTimeMillis); - component.setLastUpdateDate(currentTimeMillis); - - StorageOperationStatus checkCategories = validateCategories(currentComponent, component, componentData, type); - if (checkCategories != StorageOperationStatus.OK) { - result = Either.right(checkCategories); - return result; - } - - List tags = component.getTags(); - if (tags != null && false == tags.isEmpty()) { - Either, StorageOperationStatus> tagsResult = createNewTagsList(tags); - if (tagsResult.isRight()) { - result = Either.right(tagsResult.right().value()); - return result; - } - List tagsToCreate = tagsResult.left().value(); - if (tagsToCreate != null && !tagsToCreate.isEmpty()) { - tagsToCreate = ImmutableSet.copyOf(tagsToCreate).asList(); - for (TagData tagData : tagsToCreate) { - log.debug("Before creating tag {}", tagData); - Either createTagResult = titanGenericDao.createNode(tagData, TagData.class); - if (createTagResult.isRight()) { - TitanOperationStatus status = createTagResult.right().value(); - log.error("Cannot find tag {} in the graph. status is {}", tagData, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - log.debug("After creating tag {}", tagData); - } - } - } - - Either updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class); - - if (updateNode.isRight()) { - log.error("Failed to update resource {}. status is {}", component.getUniqueId(), updateNode.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); - return result; - } - - ComponentMetadataData updatedResourceData = updateNode.left().value(); - log.debug("ComponentData After update is {}", updatedResourceData); - - // DE230195 in case resource name changed update TOSCA artifacts - // file names accordingly - String newSystemName = updatedResourceData.getMetadataDataDefinition().getSystemName(); - String prevSystemName = currentComponent.getSystemName(); - if (newSystemName != null && !newSystemName.equals(prevSystemName)) { - Map toscaArtifacts = component.getToscaArtifacts(); - if (toscaArtifacts != null) { - for (Entry artifact : toscaArtifacts.entrySet()) { - Either updateName = generateAndUpdateToscaFileName(component.getComponentType().getValue().toLowerCase(), newSystemName, updatedResourceData.getMetadataDataDefinition().getUniqueId(), - type, artifact.getValue()); - if (updateName.isRight()) { - result = Either.right(updateName.right().value()); - return result; - } - } - } - //TODO call to new Artifact operation in order to update list of artifacts - - //US833308 VLI in service - specific network_role property value logic - if (ComponentTypeEnum.SERVICE == component.getComponentType()) { - //update method logs success/error and returns boolean (true if nothing fails) - updateServiceNameInVLIsNetworkRolePropertyValues(component, prevSystemName, newSystemName); - } - } - - - if (component.getComponentType().equals(ComponentTypeEnum.RESOURCE)) { - updateDerived(component, currentComponent, componentData, component.getClass()); - } - - Either updatedResource = getComponent(component.getUniqueId(), filterResult, inTransaction); - if (updatedResource.isRight()) { - log.error("Resource id is missing in the request. status is {}", updatedResource.right().value()); - result = Either.right(StorageOperationStatus.BAD_REQUEST); - return result; - } - - T updatedResourceValue = updatedResource.left().value(); - result = Either.left(updatedResourceValue); - - return result; - } finally { - - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.error("updateComponent operation : Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("updateComponent operation : Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - } - - private boolean updateServiceNameInVLIsNetworkRolePropertyValues (Component component, String prevSystemName, String newSystemName) { - // find VLIs in service - boolean res = true; - if(null == component.getComponentInstances() || component.getComponentInstances().isEmpty()){ - return res; - } - - List vlInstances = - component.getComponentInstances().stream() - .filter(p -> OriginTypeEnum.VL == p.getOriginType()) - .collect(Collectors.toList()); - if (!vlInstances.isEmpty()) { - for (ComponentInstance vlInstance : vlInstances){ - // find network_role property - Optional networkRoleProperty = component.getComponentInstancesProperties().get(vlInstance.getUniqueId()).stream() - .filter(p -> PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(p.getName())) - .findAny(); - res = res && updateNetworkRolePropertyValue(prevSystemName, newSystemName, vlInstance, networkRoleProperty); - } - } - return res; - } - - private boolean updateNetworkRolePropertyValue(String prevSystemName, String newSystemName, ComponentInstance vlInstance, Optional networkRoleProperty) { - if (networkRoleProperty.isPresent() && !StringUtils.isEmpty(networkRoleProperty.get().getValue()) ) { - ComponentInstanceProperty property = networkRoleProperty.get(); - String updatedValue = property.getValue().replaceFirst(prevSystemName, newSystemName); - property.setValue(updatedValue); - StorageOperationStatus updateCustomizationUUID; - //disregard property value rule - property.setRules(null); - Either result = componentInstanceOperation.updatePropertyValueInResourceInstance(property, vlInstance.getUniqueId(), true); - if (result.isLeft()) { - log.debug("Property value {} was updated on graph.", property.getValueUniqueUid()); - updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(vlInstance.getUniqueId()); - } else { - updateCustomizationUUID = StorageOperationStatus.EXEUCTION_FAILED; - log.debug("Failed to update property value: {} in resource instance {}", updatedValue, vlInstance.getUniqueId()); - } - return result.isLeft() && StorageOperationStatus.OK == updateCustomizationUUID; - } - return true; - } - - public Either updateComponentLastUpdateDateAndLastModifierOnGraph( Component component, User modifier, NodeTypeEnum componentType, boolean inTransaction) { - - log.debug("Going to update last update date and last modifier info of component {}. ", component.getName()); - Either result = null; - try{ - String modifierUserId = modifier.getUserId(); - ComponentMetadataData componentData = getMetaDataFromComponent(component); - String currentUser = component.getLastUpdaterUserId(); - UserData modifierUserData = new UserData(); - modifierUserData.setUserId(modifierUserId); - if (currentUser.equals(modifierUserId)) { - log.debug("Graph last modifier edge should not be changed since the modifier is the same as the last modifier."); - } else { - log.debug("Going to update the last modifier user of the component from {} to {}", currentUser, modifierUserId); - StorageOperationStatus status = moveLastModifierEdge(component, componentData, modifierUserData, componentType); - log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentUser, modifierUserId, status); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - } - } - Either updateNode = null; - if(result == null){ - log.debug("Going to update the component {} with new last update date. ", component.getName()); - componentData.getMetadataDataDefinition().setLastUpdateDate(System.currentTimeMillis()); - updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class); - if (updateNode.isRight()) { - log.error("Failed to update component {}. status is {}", component.getUniqueId(), updateNode.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); - } - } - if(result == null){ - result = Either.left(updateNode.left().value()); - } - }catch(Exception e){ - log.error("Exception occured during update last update date and last modifier info of component {}. The message is {}. ", component.getName(), e.getMessage()); - }finally { - if(!inTransaction){ - if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - return result; - } - /** - * updates component lastUpdateDate on graph node - * @param component - * @param componentType - * @param lastUpdateDate - * @param inTransaction - * @return - */ - public Either updateComponentLastUpdateDateOnGraph( Component component, NodeTypeEnum componentType, Long lastUpdateDate, boolean inTransaction) { - - log.debug("Going to update last update date of component {}. ", component.getName()); - Either result = null; - try{ - ComponentMetadataData componentData = getMetaDataFromComponent(component); - Either updateNode = null; - if(result == null){ - log.debug("Going to update the component {} with new last update date. ", component.getName()); - componentData.getMetadataDataDefinition().setLastUpdateDate(lastUpdateDate); - updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class); - if (updateNode.isRight()) { - log.error("Failed to update component {}. status is {}", component.getUniqueId(), updateNode.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); - } - } - if(result == null){ - result = Either.left(updateNode.left().value()); - } - }catch(Exception e){ - log.error("Exception occured during update last update date of component {}. The message is {}. ", component.getName(), e.getMessage()); - }finally { - if(!inTransaction){ - if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - return result; - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java index 89f8f71e2a..a47f7cfdef 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 @@ -40,7 +40,7 @@ import fj.data.Either; @Component("graph-lock-operation") public class GraphLockOperation implements IGraphLockOperation { - private static Logger log = LoggerFactory.getLogger(ResourceOperation.class.getName()); + private static Logger log = LoggerFactory.getLogger(GraphLockOperation.class.getName()); @javax.annotation.Resource private TitanGenericDao titanGenericDao; 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 d282ecfae9..4ffea48dee 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,18 +20,11 @@ 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.CollectionUtils; import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; @@ -39,64 +32,51 @@ import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.VertexProperty; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; -import org.openecomp.sdc.be.dao.graph.GraphElementFactory; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; - import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.dao.utils.Constants; import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; - -import org.openecomp.sdc.be.model.ArtifactDefinition; - -import org.openecomp.sdc.be.model.ComponentInstance; - import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.model.GroupInstanceProperty; import org.openecomp.sdc.be.model.GroupProperty; -import org.openecomp.sdc.be.model.GroupTypeDefinition; import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; - import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.resources.data.ArtifactData; -import org.openecomp.sdc.be.resources.data.AttributeValueData; -import org.openecomp.sdc.be.resources.data.ComponentInstanceData; -import org.openecomp.sdc.be.resources.data.GroupData; import org.openecomp.sdc.be.resources.data.GroupInstanceData; import org.openecomp.sdc.be.resources.data.PropertyData; import org.openecomp.sdc.be.resources.data.PropertyValueData; import org.openecomp.sdc.be.resources.data.UniqueIdData; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.util.ValidationUtils; -import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; +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; @org.springframework.stereotype.Component("group-instance-operation") public class GroupInstanceOperation extends AbstractOperation implements IGroupInstanceOperation { - private static String ADDING_GROUP = "AddingGroupInstance"; - private static Logger log = LoggerFactory.getLogger(GroupInstanceOperation.class.getName()); @Autowired @@ -110,72 +90,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI @javax.annotation.Resource private ApplicationDataTypeCache dataTypeCache; - @Override - public Either createGroupInstance(String componentInstId, GroupInstance groupInstance, boolean isCreateLogicalName) { - Either result = null; - - if (!ValidationUtils.validateStringNotEmpty(groupInstance.getCustomizationUUID())) { - generateCustomizationUUID(groupInstance); - } - - Either addRes = addGroupInstanceToComponentInstance(componentInstId, isCreateLogicalName, groupInstance); - if (addRes.isRight()) { - TitanOperationStatus status = addRes.right().value(); - log.error("Failed to add resource instance {} to service {}. status is {}", groupInstance, componentInstId, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - GroupInstance value = addRes.left().value(); - result = Either.left(value); - - return result; - - } - - @Override - public Either createGroupInstance(TitanVertex ciVertex, String componentInstId, GroupInstance groupInstance, boolean isCreateLogicalName) { - Either result = null; - - if (!ValidationUtils.validateStringNotEmpty(groupInstance.getCustomizationUUID())) { - generateCustomizationUUID(groupInstance); - } - - Either addComponentInstanceToContainerComponent = addGroupInstanceToContainerComponent(ciVertex, componentInstId, isCreateLogicalName, groupInstance); - - if (addComponentInstanceToContainerComponent.isRight()) { - TitanOperationStatus status = addComponentInstanceToContainerComponent.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - TitanVertex giVertex = addComponentInstanceToContainerComponent.left().value(); - Map properties = titanGenericDao.getProperties(giVertex); - GroupInstanceData createdGroupInstanceData = GraphElementFactory.createElement(NodeTypeEnum.GroupInstance.getName(), GraphElementTypeEnum.Node, properties, GroupInstanceData.class); - - GroupInstance createdGroupInstance = new GroupInstance(createdGroupInstanceData.getGroupDataDefinition()); - createdGroupInstance.setGroupName(groupInstance.getGroupName()); - - createdGroupInstance.setArtifacts(groupInstance.getArtifacts()); - - result = Either.left(createdGroupInstance); - - return result; - - } - - @Override - public Either deleteGroupInstanceInstance(NodeTypeEnum containerNodeType, String containerComponentId, String groupInstUid) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either updateGroupInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance) { - // TODO Auto-generated method stub - return null; - } @Override public Either, StorageOperationStatus> getAllGroupInstances(String parentId, NodeTypeEnum parentType) { @@ -274,55 +188,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI } - @Override - public Either getGroupInstanceById(String groupResourceId) { - // TODO Auto-generated method stub - return getGroupInstanceFromGraph(groupResourceId, false, false); - } - - @Override - public TitanOperationStatus deleteAllGroupInstances(String componentInstId) { - - return deleteAssociatedGroupInstances(componentInstId); - } - - private TitanOperationStatus deleteAssociatedGroupInstances(String resourceInstanceUid) { - final GraphEdgeLabels edgeConectingToRI = GraphEdgeLabels.GROUP_INST; - final NodeTypeEnum elementTypeToDelete = NodeTypeEnum.GroupInstance; - return deleteAssociatedRIElements(elementTypeToDelete, edgeConectingToRI, resourceInstanceUid, () -> GroupInstanceData.class); - } - - private TitanOperationStatus deleteAssociatedRIElements(NodeTypeEnum elementTypeToDelete, GraphEdgeLabels edgeConectingToRI, String resourceInstanceUid, Supplier> classGen) { - - Either>, TitanOperationStatus> elementsNodesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid, edgeConectingToRI, elementTypeToDelete, - classGen.get()); - - if (elementsNodesRes.isRight()) { - TitanOperationStatus status = elementsNodesRes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logInternalFlowError("deleteAssociatedRIElements", "Failed to find the elements of resource instance " + resourceInstanceUid + ". status is " + status, ErrorSeverity.ERROR); - return status; - } - } else { - - List> relationshipNodes = elementsNodesRes.left().value(); - if (relationshipNodes != null) { - for (ImmutablePair immutablePair : relationshipNodes) { - T elementValueDataData = immutablePair.getKey(); - Either deleteNode = titanGenericDao.deleteNode(elementValueDataData, classGen.get()); - if (deleteNode.isRight()) { - TitanOperationStatus status = deleteNode.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("deleteAssociatedRIElements", "Failed to delete element value node " + elementValueDataData + ". status is " + status, ErrorSeverity.ERROR); - return status; - } - } - } - - } - - return TitanOperationStatus.OK; - } - @Override public Either increaseAndGetGroupInstancePropertyCounter(String groupInstanceId) { Either result = null; @@ -360,18 +225,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI } - @Override - public Either isGroupInstanceNameExist(String parentComponentId, NodeTypeEnum parentNodeType, String compInstId, String componentInstName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either getFullGroupInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType) { - // TODO Auto-generated method stub - return null; - } - @Override public Either addPropertyValueToGroupInstance(ComponentInstanceProperty groupInstanceProperty, String groupInstanceId, Integer index, boolean inTransaction) { /// #RULES SUPPORT @@ -424,12 +277,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI } - @Override - public Either addPropertyValueToGroupInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isvalidate, Integer index, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } - @Override public Either updatePropertyValueInGroupInstance(ComponentInstanceProperty gropuInstanceProperty, String groupInstanceId, boolean inTransaction) { // TODO Auto-generated method stub @@ -437,26 +284,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI return null; } - @Override - public Either, StorageOperationStatus> fetchCIEnvArtifacts(String componentInstanceId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public StorageOperationStatus updateCustomizationUUID(String groupInstanceId) { - Either vertexByProperty = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), groupInstanceId); - if (vertexByProperty.isRight()) { - log.debug("Failed to fetch component instance by id {} error {}", groupInstanceId, vertexByProperty.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(vertexByProperty.right().value()); - } - UUID uuid = UUID.randomUUID(); - TitanVertex ciVertex = vertexByProperty.left().value(); - ciVertex.property(GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty(), uuid.toString()); - - return StorageOperationStatus.OK; - } - public void generateCustomizationUUID(GroupInstance groupInstance) { UUID uuid = UUID.randomUUID(); groupInstance.setCustomizationUUID(uuid.toString()); @@ -465,8 +292,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI /** * add property to resource instance * - * @param resourceInstanceProperty - * @param resourceInstanceId * @param index * @return */ @@ -608,242 +433,7 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI } - public Either addPropertyToResourceInstance(ComponentInstanceProperty groupInstanceProperty, TitanVertex groupInstanceVertex, Integer index, String groupInstanceId) { - - String propertyId = groupInstanceProperty.getUniqueId(); - Either findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class); - - if (findPropertyDefRes.isRight()) { - TitanOperationStatus status = findPropertyDefRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); - } - - String valueUniqueUid = groupInstanceProperty.getValueUniqueUid(); - if (valueUniqueUid == null) { - - PropertyData propertyData = findPropertyDefRes.left().value(); - - ImmutablePair isPropertyValueExists = propertyOperation.findPropertyValue(groupInstanceId, propertyId); - if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) { - log.trace("The property {} already added to the resource instance {}", propertyId, groupInstanceId); - groupInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight()); - Either updatePropertyOfResourceInstance = updatePropertyOfGroupInstance(groupInstanceProperty, groupInstanceId); - if (updatePropertyOfResourceInstance.isRight()) { - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR); - return Either.right(updatePropertyOfResourceInstance.right().value()); - } - return Either.right(TitanOperationStatus.OK); - } - - if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { - log.trace("After finding property value of {} on componenet instance {}", propertyId, groupInstanceId); - return Either.right(isPropertyValueExists.getLeft()); - } - - String innerType = null; - - PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition(); - String propertyType = propDataDef.getType(); - String value = groupInstanceProperty.getValue(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = propDataDef.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - innerType = propDef.getType(); - } - - log.trace("Before validateAndUpdatePropertyValue"); - Either, 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 isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value()); - log.trace("After validateAndUpdatePropertyValue. isValid = {}", isValid); - - String newValue = value; - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - - String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(groupInstanceId, index); - PropertyValueData propertyValueData = new PropertyValueData(); - propertyValueData.setUniqueId(uniqueId); - propertyValueData.setValue(newValue); - - log.trace("Before validateAndUpdateRules"); - ImmutablePair pair = propertyOperation.validateAndUpdateRules(propertyType, groupInstanceProperty.getRules(), innerType, allDataTypes.left().value(), false); - log.debug("After validateAndUpdateRules. pair = {} ", pair); - if (pair.getRight() != null && pair.getRight() == false) { - BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProperty.getName(), propertyType); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - propertyOperation.addRulesToNewPropertyValue(propertyValueData, groupInstanceProperty, groupInstanceId); - - log.trace("Before adding property value to graph {}", propertyValueData); - Either createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class); - log.trace("After adding property value to graph {}", propertyValueData); - - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - return Either.right(operationStatus); - } - propertyValueData = createNodeResult.left().value(); - - Either createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null); - - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus); - return Either.right(operationStatus); - } - - TitanOperationStatus edgeResult = titanGenericDao.createEdge(groupInstanceVertex, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null); - - if (edgeResult != TitanOperationStatus.OK) { - log.error("Failed to associate resource instance {} property value {} in graph. status is {}", groupInstanceId, uniqueId, edgeResult); - return Either.right(edgeResult); - } - - ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, groupInstanceProperty); - log.debug("The returned ResourceInstanceProperty is {} ", propertyValueResult); - - return Either.left(propertyValueResult); - } else { - log.debug("property value already exists."); - return Either.right(TitanOperationStatus.ALREADY_EXIST); - } - - } - - public Either addGroupInstanceToComponentInstance(String componentInstanceId, boolean isCreateLogicaName, GroupInstance groupInstance) { - log.debug("Going to create group instance {} in componentInstance {}", groupInstance, componentInstanceId); - Either metadataVertex = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); - } - Either addComponentInstanceToContainerComponent = addGroupInstanceToContainerComponent(metadataVertex.left().value(), componentInstanceId, isCreateLogicaName, groupInstance); - - if (addComponentInstanceToContainerComponent.isRight()) { - TitanOperationStatus status = addComponentInstanceToContainerComponent.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); - } - TitanVertex ciVertex = addComponentInstanceToContainerComponent.left().value(); - Map properties = titanGenericDao.getProperties(ciVertex); - GroupInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.GroupInstance.getName(), GraphElementTypeEnum.Node, properties, GroupInstanceData.class); - - GroupInstance createdResourceInstance = new GroupInstance(createdComponentInstance.getGroupDataDefinition()); - - return Either.left(createdResourceInstance); - - } - - /** - * - * @param containerComponentId - * @param containerNodeType - * @param instanceNumber - * @param isCreateLogicaName - * @param componentInstance - * @param compInstNodeType - * @param metadataVertex - * @return - */ - public Either addGroupInstanceToContainerComponent(TitanVertex ciVertex, String componentInstanceId, boolean isCreateLogicaName, GroupInstance groupInstance) { - TitanOperationStatus status = null; - log.debug("Going to create group instance {} in component instance {}", groupInstance, componentInstanceId); - String instOriginGroupId = groupInstance.getGroupUid(); - String logicalName = groupInstance.getName(); - if (isCreateLogicaName){ - String instanceName = (String) titanGenericDao.getProperty(ciVertex, GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()); - logicalName = createGroupInstLogicalName(instanceName, groupInstance.getGroupName()); - } - - GroupInstanceData groupInstanceData = buildGroupInstanceData(groupInstance, componentInstanceId, logicalName); - Either originVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), instOriginGroupId); - if (originVertexEither.isRight()) { - log.debug("Failed to fetch vertex of origin resource for id {} error {}", instOriginGroupId, originVertexEither.right().value()); - return Either.right(originVertexEither.right().value()); - } - TitanVertex originVertex = originVertexEither.left().value(); - - // String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty()); - String groupType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.TYPE.getProperty()); - // detectOriginType(originType, groupInstanceData, resourceType); - - log.trace("Before adding component instance to graph. componentInstanceData = {}", groupInstanceData); - // groupInstanceData.getGroupDataDefinition().setGroupUid(groupType); - - Either createGIResult = titanGenericDao.createNode(groupInstanceData); - - log.debug("After adding component instance to graph. status is = {}", createGIResult); - - if (createGIResult.isRight()) { - status = createGIResult.right().value(); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance"); - log.debug("Failed to create group instance node in graph. status is {}", status); - return Either.right(status); - } - TitanVertex createdGroupInstanceVertex = createGIResult.left().value(); - TitanOperationStatus associateContainerRes = associateComponentInstanceToGroupInstance(ciVertex, createdGroupInstanceVertex, logicalName); - - String componentInstanceUniqueId = groupInstanceData.getUniqueId(); - if (associateContainerRes != TitanOperationStatus.OK) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance"); - log.debug("Failed to associate container component {} to component instance {}. Status is {}", componentInstanceId, componentInstanceUniqueId, associateContainerRes); - return Either.right(associateContainerRes); - } - // String originId = (String) titanGenericDao.getProperty(createdGroupInstanceVertex, GraphPropertiesDictionary.TYPE.getProperty()); - - TitanOperationStatus associateToInstOriginComponent = associateToInstOriginGroup(createdGroupInstanceVertex, originVertex, instOriginGroupId); - if (associateToInstOriginComponent != TitanOperationStatus.OK) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance"); - log.debug("Failed to associate component instance {} to its origin component {}. Status is {}", componentInstanceUniqueId, groupInstanceData.getGroupDataDefinition().getGroupUid(), associateToInstOriginComponent); - return Either.right(associateToInstOriginComponent); - } - - // Capability instance with property values implementation - - if (status == null) { - // ComponentInstance createdResourceInstance = new - // ComponentInstance(createdComponentInstance.getComponentInstDataDefinition()); - // - // String icon = (String) titanGenericDao.getProperty(originVertex, - // GraphPropertiesDictionary.ICON.getProperty()); - // createdResourceInstance.setIcon(icon); - return Either.left(createdGroupInstanceVertex); - } - return Either.right(status); - } private GroupInstanceData buildGroupInstanceData(GroupInstance groupInstance, String componentInstanceId, String logicalName) { String ciOriginComponentUid = groupInstance.getGroupUid(); @@ -869,119 +459,9 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI return resourceInstanceData; } - @Override - public String createGroupInstLogicalName(String instanceName, String groupName) { - - String logicalName = buildGroupInstanceLogicalName(instanceName, groupName); - - return logicalName; - } - - private String buildGroupInstanceLogicalName(String instanceName, String groupName) { - return ValidationUtils.normalizeComponentInstanceName(instanceName) + ".." + groupName; - } - - /** - * Make a relation between service to resource instance. - * - * @param containerCompIdData - * @param componentInstanceData - * @param logicalName - * @return - */ - private Either associateComponentInstanceToGroupInstance(UniqueIdData compInstIdData, GroupInstanceData groupInstanceData, String logicalName) { - Map properties = new HashMap(); - - properties.put(GraphPropertiesDictionary.NAME.getProperty(), logicalName); - Either createRelation = titanGenericDao.createRelation(compInstIdData, groupInstanceData, GraphEdgeLabels.GROUP_INST, properties); - - log.debug("After associating container component {} to resource instance {} with logical name {}. Status is {}", compInstIdData.getUniqueId(), groupInstanceData.getUniqueId(), logicalName, createRelation); - - return createRelation; - } - - private TitanOperationStatus associateComponentInstanceToGroupInstance(TitanVertex componentInstVertex, TitanVertex groupInstanceVertex, String logicalName) { - Map properties = new HashMap(); - - properties.put(GraphPropertiesDictionary.NAME.getProperty(), logicalName); - TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstVertex, groupInstanceVertex, GraphEdgeLabels.GROUP_INST, properties); - - return createRelation; - } - - private Either associateToInstOriginGroup(GroupInstanceData groupInstanceData, NodeTypeEnum compInstNodeType) { - - UniqueIdData groupIdData = new UniqueIdData(compInstNodeType, groupInstanceData.getGroupDataDefinition().getGroupUid()); - - Either createRelation = titanGenericDao.createRelation(groupInstanceData, groupIdData, GraphEdgeLabels.INSTANCE_OF, null); - - log.debug("After associating group instance {} to group {}. status is {}", groupInstanceData.getUniqueId(), groupInstanceData.getGroupDataDefinition().getGroupUid(), createRelation); - - return createRelation; - } - - private TitanOperationStatus associateToInstOriginGroup(TitanVertex groupInstanceVertex, TitanVertex originVertex, String originId) { - - TitanOperationStatus createRelation = titanGenericDao.createEdge(groupInstanceVertex, originVertex, GraphEdgeLabels.INSTANCE_OF, null); - - log.debug("After associating group instance {} to group {}. status is {}", groupInstanceVertex, originId, createRelation); - - return createRelation; - } - - public Either, TitanOperationStatus> getGroupInstanceProperties(GroupInstance groupInstance, GroupDefinition groupDefinition) { - - // 1. Go over each instance - // 1.1 get all properties of from the parents of the instance - // 1.2 get all updated properties - // 1.3 find all instances included in the parent of this instance and - // run this method on them. - String groupInstanceId = groupInstance.getUniqueId(); - if (log.isDebugEnabled()) - log.debug("Going to update properties of group instance {}", groupInstanceId); - String groupUid = groupInstance.getGroupUid(); - List properties = groupDefinition.convertToGroupProperties(); - - if (log.isDebugEnabled()) - log.debug("After getting properties of group {} . Number of properties is {}", groupUid, (properties == null ? 0 : properties.size())); - List resourceInstancePropertyList = new ArrayList<>(); - if (properties != null && false == properties.isEmpty()) { - - // TODO: WE MAY HAVE INDIRECT PROPERTY VALUE ALSO IN CASE NO - // PROPERTY ON THIS COMPONENT - - // String resourceInstanceUid = resourceInstance.getUniqueId(); - - for (GroupProperty propertyDefinition : properties) { - - String defaultValue = propertyDefinition.getDefaultValue(); - String value = defaultValue; - String valueUid = null; - - // String propertyId = propertyDefinition.getUniqueId(); - - GroupProperty resourceInstanceProperty = new GroupProperty(propertyDefinition, value, valueUid); - - // resourceInstanceProperty.setPath(cloneList(path)); - - // TODO: currently ignore constraints since they are not inuse - // and cause to error in convertion to object. - resourceInstanceProperty.setConstraints(null); - - resourceInstancePropertyList.add(resourceInstanceProperty); - - } - - } - - return Either.left(resourceInstancePropertyList); - } - /** * update value of attribute on resource instance * - * @param resourceInstanceProerty - * @param resourceInstanceId * @return */ public Either updatePropertyOfGroupInstance(ComponentInstanceProperty groupInstanceProerty, String groupInstanceId) { @@ -1207,68 +687,7 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI } } - /** - * Associate artifacts to a given group - * - * @param groupId - * @param artifactsId - * @param inTransaction - * @return - */ - public Either associateArtifactsToGroupInstance(String groupId, List artifactsId) { - - Either result = null; - - Either titanRes = this.associateArtifactsToGroupInstanceOnGraph(groupId, artifactsId); - - if (titanRes.isRight()) { - StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value()); - result = Either.right(status); - } - - result = Either.left(titanRes.left().value()); - return result; - - } - - public Either associateArtifactsToGroupInstanceOnGraph(String groupInstanceId, List artifactsId) { - - if (artifactsId == null || artifactsId.isEmpty()) { - return Either.right(TitanOperationStatus.OK); - } - - for (String artifactId : artifactsId) { - Either findArtifactRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class); - if (findArtifactRes.isRight()) { - TitanOperationStatus status = findArtifactRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - String description = "Failed to associate group " + groupInstanceId + " to artifact " + artifactId + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); - return Either.right(status); - } - - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), findArtifactRes.left().value().getLabel()); - - GraphNode groupData = new UniqueIdData(NodeTypeEnum.GroupInstance, groupInstanceId); - Either addArtifactsRefResult = titanGenericDao.createRelation(groupData, findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF, props); - - if (addArtifactsRefResult.isRight()) { - TitanOperationStatus status = addArtifactsRefResult.right().value(); - String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); - return Either.right(status); - } - } - - Either groupFromGraph = this.getGroupInstanceFromGraph(groupInstanceId, true, false); - - return groupFromGraph; - } - - public Either getGroupInstanceFromGraph(String uniqueId, boolean skipProperties, boolean skipArtifacts) { + private Either getGroupInstanceFromGraph(String uniqueId, boolean skipProperties, boolean skipArtifacts) { Either result = null; @@ -1337,20 +756,20 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI private void buildGroupInstanceFromGroup(GroupInstance groupInstance, GroupDefinition groupDefinition, Map 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 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); -} + 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 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 groupInstancePropertyValues){ @@ -1401,14 +820,11 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI @Override public StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { - StorageOperationStatus result = null; - return this.dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(componentId, componentTypeEnum, oldArtifactId, newArtifact); } - @Override - public StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { + private StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { Either, StorageOperationStatus> allGroupsFromGraph = getAllGroupInstances(componentId, componentTypeEnum); if (allGroupsFromGraph.isRight()) { @@ -1461,212 +877,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI return StorageOperationStatus.OK; } - @Override - public Either updateGroupInstancePropertyValues(GroupInstance oldGroupInstance, List newProperties, Boolean inTransaction) { - - Either updateRes = Either.left(oldGroupInstance); - try{ - if(!CollectionUtils.isEmpty(newProperties)){ - updateRes = updateGroupInstancePropertyValuesOnGraph(oldGroupInstance, newProperties); - } - }catch(Exception e){ - log.debug("The Exception occured during update of group instance {} property values. The message is {}. ", oldGroupInstance.getName(), e.getMessage(), e); - updateRes = Either.right(StorageOperationStatus.GENERAL_ERROR); - }finally { - handleTransactionCommitRollback(inTransaction, updateRes); - } - return updateRes; - } - - private Either updateGroupInstancePropertyValuesOnGraph( GroupInstance oldGroupInstance, List newProperties ) { - Either updateRes = null; - Either nodeUpdateRes = null; - Vertex groupInstanceVertex = null; - Either groupInstanceVertexRes; - Map existingPropertyValueVertices = new HashMap<>(); - Map existingPropertyVertices = new HashMap<>(); - groupInstanceVertexRes = getVertexFromGraph(GraphPropertiesDictionary.UNIQUE_ID.getProperty(),oldGroupInstance.getUniqueId()); - try{ - if (groupInstanceVertexRes.isRight()) { - log.debug("Failed to fetch group instance vertex {} from graph. ", oldGroupInstance.getName()); - updateRes = Either.right(groupInstanceVertexRes.right().value()); - } else { - groupInstanceVertex = groupInstanceVertexRes.left().value(); - findExistingPropertyValueVertices(groupInstanceVertex, existingPropertyValueVertices); - nodeUpdateRes = handlePropertyValues(oldGroupInstance, oldGroupInstance.getPropertyValueCounter(), newProperties, groupInstanceVertex, existingPropertyValueVertices, existingPropertyVertices); - if(nodeUpdateRes.isRight()){ - log.debug("Failed to handle property values of group instance {}. ", oldGroupInstance.getName()); - updateRes = Either.right(nodeUpdateRes.right().value()); - } else { - updateRes = updateGroupInstanceVertexAndGetUpdatedGroupInstance(groupInstanceVertex, nodeUpdateRes.left().value(), oldGroupInstance); - } - } - } catch(Exception e){ - log.debug("The Exception occured during update group instance {} property values on graph. The message is {}. ", oldGroupInstance.getName(), e.getMessage(), e); - updateRes = Either.right(StorageOperationStatus.GENERAL_ERROR); - } - return updateRes; - } - - private Either handlePropertyValues(GroupInstance oldGroupInstance, Integer propertyValueCounter, List newProperties, Vertex groupInstanceVertex, - Map existingPropertyValueVertices, Map existingPropertyVertices) { - - Either nodeHandleRes = null; - int currCounter = propertyValueCounter; - for(GroupInstanceProperty currProperty : newProperties){ - nodeHandleRes = handlePropertyValueNode(oldGroupInstance, currCounter, currProperty, groupInstanceVertex, existingPropertyValueVertices, existingPropertyVertices); - if(nodeHandleRes.isRight()){ - break; - } - currCounter = nodeHandleRes.left().value(); - } - return nodeHandleRes; - } - - private Either updateGroupInstanceVertexAndGetUpdatedGroupInstance( Vertex groupInstanceVertex, Integer propertyValueCounter, GroupInstance oldGroupInstance) { - - TitanOperationStatus status; - Either actionResult; - status = updateGroupInstanceVertex(groupInstanceVertex, propertyValueCounter); - if(status != TitanOperationStatus.OK){ - log.debug("Failed to update group instance {}. ", oldGroupInstance.getName()); - actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - }else{ - Either updatedGroupInstanceRes = getGroupInstanceFromGraph(oldGroupInstance.getUniqueId(), false, false); - if(updatedGroupInstanceRes.isRight()){ - status = updatedGroupInstanceRes.right().value(); - log.debug("Failed to get updated group instance {}. Status is {}. ", oldGroupInstance.getName(), status); - actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - }else{ - actionResult = Either.left(updatedGroupInstanceRes.left().value()); - } - } - return actionResult; - } - - private Either handlePropertyValueNode(GroupInstance oldGroupInstance, Integer propertyValueCounter, GroupInstanceProperty currProperty, Vertex groupInstanceVertex, Map existingPropertyValueVertices, Map existingPropertyVertices) { - - String groupInstanceName = oldGroupInstance.getName(); - TitanOperationStatus updateStatus; - TitanOperationStatus addStatus; - Vertex propertyValueVertex; - String propertyValueId; - propertyValueId = currProperty.getValueUniqueUid(); - Either actionResult = null; - if(existingPropertyValueVertices.containsKey(propertyValueId)){ - updateStatus = updatePropertyValueVertex(existingPropertyValueVertices.get(propertyValueId), currProperty); - if(updateStatus != TitanOperationStatus.OK){ - log.debug("Failed to update property value {} of group instance {}. ", currProperty.getName(), groupInstanceName); - actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateStatus)); - } - } - else{ - if(MapUtils.isEmpty(existingPropertyVertices)){ - findExistingPropertyVertices(existingPropertyVertices, groupInstanceVertex); - } - propertyValueVertex = existingPropertyVertices.get(currProperty.getUniqueId()); - addStatus = addPropertyValueNodeToGroupInstance(currProperty, groupInstanceVertex, propertyValueVertex, oldGroupInstance.getUniqueId(), ++propertyValueCounter); - if(addStatus != TitanOperationStatus.OK){ - log.debug("Failed to add property value {} to group instance {}. ", currProperty.getName(), groupInstanceName); - actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addStatus)); - } - } - if(actionResult == null){ - actionResult = Either.left(propertyValueCounter); - } - return actionResult; - } - - @SuppressWarnings("unchecked") - private Either getVertexFromGraph(String uniqueKeyName, String uniqueId) { - - Either actionResult = null; - try{ - Either graph = titanGenericDao.getGraph(); - Iterable vertices = null; - if (graph.isRight()) { - log.debug("Failed to get graph. Status is {}", graph.right().value()); - actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); - } - if(actionResult == null){ - TitanGraph tGraph = graph.left().value(); - vertices = tGraph.query().has(uniqueKeyName, uniqueId).vertices(); - if (vertices == null || vertices.iterator() == null || !vertices.iterator().hasNext()) { - log.debug("Failed to get nodes from graph for type {} for id = {}", NodeTypeEnum.GroupInstance, uniqueId); - actionResult = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - if(actionResult == null && vertices != null){ - actionResult = Either.left(vertices.iterator().next()); - } - } catch(Exception e){ - log.debug("The Exception occured during get vertex {} from graph. The message is {}. ", uniqueId, e.getMessage(), e); - } - return actionResult; - } - - private void findExistingPropertyValueVertices(Vertex groupInstanceVertex, Map existingPropertyValueVertices) { - Iterator propertyValueEdges = groupInstanceVertex.edges(Direction.OUT, GraphEdgeLabels.PROPERTY_VALUE.getProperty()); - Vertex propertyValueVertex; - while(propertyValueEdges.hasNext()){ - propertyValueVertex = propertyValueEdges.next().inVertex(); - existingPropertyValueVertices.put((String) propertyValueVertex.property(GraphPropertiesDictionary.UNIQUE_ID.getProperty()).value(), propertyValueVertex); - } - } - - private void findExistingPropertyVertices(Map existingPropertyVertices, Vertex groupInstanceVertex) { - Vertex groupVertex = groupInstanceVertex.edges(Direction.OUT, GraphEdgeLabels.INSTANCE_OF.getProperty()).next().inVertex(); - Vertex groupTypeVertex = groupVertex.edges(Direction.OUT, GraphEdgeLabels.TYPE_OF.getProperty()).next().inVertex(); - Iterator groupTypePropertiesIterator = groupTypeVertex.edges(Direction.OUT, GraphEdgeLabels.PROPERTY.getProperty()); - while(groupTypePropertiesIterator.hasNext()){ - Vertex propertyValueVertex = groupTypePropertiesIterator.next().inVertex(); - existingPropertyVertices.put((String) propertyValueVertex.property(GraphPropertiesDictionary.UNIQUE_ID.getProperty()).value(), propertyValueVertex); - } - } - - private TitanOperationStatus addPropertyValueNodeToGroupInstance(GroupInstanceProperty currProperty, Vertex groupInstanceVertex, Vertex propertyVertex, String groupInstanceId, int index) { - TitanOperationStatus status = null; - TitanVertex propertyValueVertex = null; - PropertyValueData newPropertyValue = new PropertyValueData(); - Long creationTime = System.currentTimeMillis(); - newPropertyValue.setModificationTime(creationTime); - newPropertyValue.setCreationTime(creationTime); - newPropertyValue.setUniqueId(UniqueIdBuilder.buildGroupPropertyValueUid(groupInstanceId, index)); - newPropertyValue.setValue(currProperty.getValue()); - newPropertyValue.setType(currProperty.getType()); - Either propertyValueNodeRes = titanGenericDao.createNode(newPropertyValue); - if(propertyValueNodeRes.isRight()){ - status = propertyValueNodeRes.right().value(); - } - if(status == null){ - propertyValueVertex = propertyValueNodeRes.left().value(); - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.PROPERTY_NAME.getProperty(), currProperty.getName()); - status = titanGenericDao.createEdge(groupInstanceVertex, propertyValueVertex, GraphEdgeLabels.PROPERTY_VALUE, props); - } - if(status == TitanOperationStatus.OK){ - status = titanGenericDao.createEdge(propertyValueVertex, propertyVertex, GraphEdgeLabels.PROPERTY_IMPL, null); - } - return status; - } - - private TitanOperationStatus updatePropertyValueVertex(Vertex propertyValueVertex, GroupInstanceProperty property) { - PropertyValueData propertyValue = new PropertyValueData(); - propertyValue.setUniqueId(property.getValue()); - propertyValue.setModificationTime(System.currentTimeMillis()); - propertyValue.setType(property.getType()); - propertyValue.setValue(property.getValue()); - return titanGenericDao.updateVertex(propertyValue, propertyValueVertex); - } - - private TitanOperationStatus updateGroupInstanceVertex(Vertex groupInstanceVertex, int propertyValueCounter) { - GroupInstanceData groupInstanceData = new GroupInstanceData(); - groupInstanceData.getGroupDataDefinition().setModificationTime(System.currentTimeMillis()); - groupInstanceData.getGroupDataDefinition().setCustomizationUUID(UUID.randomUUID().toString()); - groupInstanceData.getGroupDataDefinition().setPropertyValueCounter(propertyValueCounter); - return titanGenericDao.updateVertex(groupInstanceData, groupInstanceVertex); - } - private Either, TitanOperationStatus> getAllGroupInstancePropertyValuesData(GroupInstanceData groupInstData) { Either, TitanOperationStatus> result = null; @@ -1694,8 +904,4 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI } return result; } - @Override - public Either updateGroupInstancePropertyValues(GroupInstance groupInstance, List newProperties) { - return updateGroupInstancePropertyValues(groupInstance, newProperties, false); - } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java index 52bcae36db..02c5194da3 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 @@ -71,10 +71,6 @@ import fj.data.Either; @Component("group-operation") public class GroupOperation extends AbstractOperation implements IGroupOperation { - private static String ADDING_GROUP = "AddingGroup"; - private static String DELETING_GROUP = "DeletingGroup"; - private static String DELETING_ALL_GROUPS = "DeletingAllGroups"; - private static String ASSOCIATING_GROUP_TO_COMP_INST = "AssociatingGroupToComponentInstance"; private static Logger log = LoggerFactory.getLogger(GroupOperation.class.getName()); @@ -87,597 +83,18 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation @javax.annotation.Resource private ApplicationDataTypeCache dataTypeCache; - @javax.annotation.Resource - protected ResourceOperation resourceOperation; - - @Override - public Either addGroupToGraph(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition) { - - String groupTypeUid = groupDefinition.getTypeUid(); - - if (groupTypeUid == null) { - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, "Group type id is empty", ErrorSeverity.ERROR); - return Either.right(TitanOperationStatus.INVALID_ID); - } - - ComponentMetadataData metaData = null; - if (nodeTypeEnum == NodeTypeEnum.Resource) { - metaData = new ResourceMetadataData(); - } else { - metaData = new ServiceMetadataData(); - } - metaData.getMetadataDataDefinition().setUniqueId(componentId); - - groupDefinition.setUniqueId(UniqueIdBuilder.buildGroupUniqueId(componentId, groupDefinition.getName())); - - int propertiesSize = groupDefinition.getProperties() == null ? 0 : groupDefinition.getProperties().size(); - groupDefinition.setPropertyValueCounter(propertiesSize); - - GroupData groupData = new GroupData(groupDefinition); - - TitanOperationStatus status = null; - // Adding group data node to graph - log.debug("Before adding group to graph {}", groupData.toString()); - Either createNodeResult = titanGenericDao.createNode(groupData, GroupData.class); - log.debug("After adding group to graph {}", groupData.toString()); - if (createNodeResult.isRight()) { - status = createNodeResult.right().value(); - log.error("Failed to add group {} to graph. status is {}", groupDefinition.getName(), status); - return Either.right(status); - } - - // Associate group to group type - log.debug("Going to associate group {} to its groupType {}", groupDefinition.getName(), groupDefinition.getType()); - Either associateGroupTypeRes = associateGroupToGroupType(groupData, groupTypeUid); - log.debug("After associating group {} to its groupType {}. status is {}", groupDefinition.getName(), groupDefinition.getType(), associateGroupTypeRes); - if (associateGroupTypeRes.isRight()) { - status = associateGroupTypeRes.right().value(); - String description = "Failed to associate group " + groupDefinition.getName() + " to its groupType " + groupDefinition.getType() + " in graph."; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); - return Either.right(status); - } - - // Associate group to component RESOURCE/SERVICE/PRODUCT - Either associateComponentRes = associateGroupToComponent(groupData, nodeTypeEnum, componentId); - if (associateComponentRes.isRight()) { - status = associateComponentRes.right().value(); - String description = "Failed to associate group " + groupDefinition.getName() + " to " + nodeTypeEnum.getName() + " " + componentId + ". status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); - return Either.right(status); - } - - Either groupTypeRes = groupTypeOperation.getGroupTypeByUid(groupDefinition.getTypeUid()); - if (groupTypeRes.isRight()) { - TitanOperationStatus operationStatus = groupTypeRes.right().value(); - log.debug("Failed to find group type {}", groupDefinition.getTypeUid()); - if (operationStatus == TitanOperationStatus.NOT_FOUND) { - return Either.right(TitanOperationStatus.INVALID_ID); - } - } - GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value(); - // 1. find properties from group type - List groupTypeProperties = groupTypeDefinition.getProperties(); - - // 2. check the properties exists in the group type. - // 3. add parent unique id to the properties - // 4. add node per group property which the group point to it and it - // points to the parent unique id - - // Adding properties to group - List properties = groupDefinition.convertToGroupProperties(); - - if (properties != null && false == properties.isEmpty()) { - - if (groupTypeProperties == null || true == groupTypeProperties.isEmpty()) { - BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO); - return Either.right(TitanOperationStatus.MATCH_NOT_FOUND); - } - - Map groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); - - Either addPropertyResult = null; - int i = 1; - for (GroupProperty prop : properties) { - addPropertyResult = addPropertyToGroup(groupData, prop, groupTypePropertiesMap.get(prop.getName()), i); - if (addPropertyResult.isRight()) { - status = addPropertyResult.right().value(); - String description = "Failed to associate group " + groupData.getUniqueId() + " to property " + prop.getName() + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); - return Either.right(status); - } - i++; - } - } - - // Associate artifacts to group - List artifacts = groupDefinition.getArtifacts(); - - Either associateArtifactsToGroupOnGraph = associateArtifactsToGroupOnGraph(groupData.getGroupDataDefinition().getUniqueId(), artifacts); - if (associateArtifactsToGroupOnGraph.isRight() && associateArtifactsToGroupOnGraph.right().value() != TitanOperationStatus.OK) { - return Either.right(status); - } - /* - * Either addArtifactsRefResult = null; if (artifacts != null) { for (String artifactId : artifacts) { Either findArtifactRes = titanGenericDao .getNode(UniqueIdBuilder - * .getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class); if (findArtifactRes.isRight()) { status = findArtifactRes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { status = - * TitanOperationStatus.INVALID_ID; } String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status; BeEcompErrorManager.getInstance().logInternalFlowError( - * ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } - * - * Map props = new HashMap(); props.put(GraphPropertiesDictionary.NAME.getProperty(), findArtifactRes.left().value().getLabel()); - * - * addArtifactsRefResult = titanGenericDao.createRelation( groupData, findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF, props); - * - * if (addArtifactsRefResult.isRight()) { status = addArtifactsRefResult.right().value(); String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status; - * BeEcompErrorManager.getInstance().logInternalFlowError( ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } } } - */ - - // Associate group to members - // map of componentInstances - Map members = groupDefinition.getMembers(); - - if (members != null && false == members.isEmpty()) { - Either addMembersRefResult = null; - for (Entry member : members.entrySet()) { - if (member.getValue() == null || member.getValue().isEmpty()) { - continue; - } - Either findComponentInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), member.getValue(), ComponentInstanceData.class); - if (findComponentInstanceRes.isRight()) { - status = findComponentInstanceRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - String description = "Failed to find to find member of group " + member.getValue() + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); - return Either.right(status); - } - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), member.getKey()); - addMembersRefResult = titanGenericDao.createRelation(groupData, findComponentInstanceRes.left().value(), GraphEdgeLabels.GROUP_MEMBER, props); - - if (addMembersRefResult.isRight()) { - status = addMembersRefResult.right().value(); - String description = "Failed to associate group " + groupData.getUniqueId() + " to component instance " + member.getValue() + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); - return Either.right(status); - } - } - } - - return Either.left(groupData); - } - - private Either getPropertyDefFromGroupType(GroupProperty groupProperty) { - Either ret; - Either groupTypeRes = groupTypeOperation - .getGroupTypeByUid(groupProperty.getParentUniqueId()); - if (groupTypeRes.isRight()) { - TitanOperationStatus operationStatus = groupTypeRes.right().value(); - log.debug("Failed to find group type {}", groupProperty.getParentUniqueId()); - if (operationStatus == TitanOperationStatus.NOT_FOUND) { - ret = Either.right(TitanOperationStatus.INVALID_ID); - } else { - ret = Either.right(operationStatus); - } - } else { - GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value(); - List groupTypeProperties = groupTypeDefinition.getProperties(); - - Map groupTypePropertiesMap = groupTypeProperties.stream() - .collect(Collectors.toMap(p -> p.getName(), p -> p)); - if (groupTypeProperties == null || true == groupTypeProperties.isEmpty()) { - BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, - "group type does not have properties", ErrorSeverity.INFO); - ret = Either.right(TitanOperationStatus.MATCH_NOT_FOUND); - } else { - PropertyDefinition propertyDefinition = groupTypePropertiesMap.get(groupProperty.getName()); - ret = Either.left(propertyDefinition); - } - } - return ret; - } - - /** - * Updates GroupProperty Value - * @param componentId TODO - * @param groupId TODO - * @param groupProperties - * @param inTransaction TODO - * - * @return - */ - public Either, StorageOperationStatus> updateGroupProperties(String componentId, - String groupId, List groupProperties, boolean inTransaction) { - - Wrapper lastUpdateTimeWrapper = new Wrapper<>(); - TitanOperationStatus titanStatus = TitanOperationStatus.OK; - Either, StorageOperationStatus> result = null; - //Get Group Data - final GroupData groupData; - Either eitherGroupData = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupId, GroupData.class); - if( eitherGroupData.isRight() ){ - log.debug("Error: Could not fetch group with groupId = {}", groupId); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherGroupData.right().value())); - } - else{ - groupData = eitherGroupData.left().value(); - } - - try { - Optional optionalError = - //Stream of group properties to be updated - groupProperties.stream(). - //updating each property and mapping to the TitanOperationStatus - map(e -> updateGroupProperty(e, groupData, lastUpdateTimeWrapper)). - //filtering in errors if there are such - filter( e -> e != TitanOperationStatus.OK). - //collect - findFirst(); - if( optionalError.isPresent() ){ - titanStatus = optionalError.get(); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus)); - } - else{ - result = updateLastModificationTimeOnVf(componentId, groupId, groupProperties, lastUpdateTimeWrapper); - } - - } - finally { - handleTransactionCommitRollback(inTransaction, result); - } - - return result; - } - - private Either, StorageOperationStatus> updateLastModificationTimeOnVf(String componentId, - String groupId, List groupProperties, Wrapper lastUpdateTimeWrapper) { - Either, StorageOperationStatus> result; - Either eitherResource = resourceOperation.getResource(componentId); - if( eitherResource.isRight() ){ - result = Either.right(eitherResource.right().value()); - } - else{ - Either eitherLastUpdateDateUpdatedOnResource = resourceOperation - .updateComponentLastUpdateDateOnGraph(eitherResource.left().value(), NodeTypeEnum.Resource, - lastUpdateTimeWrapper.getInnerElement(), true); - if (eitherLastUpdateDateUpdatedOnResource.isLeft()) { - - groupProperties = - //Group Stream From VF - eitherResource.left().value().getGroups().stream(). - //Filter in Only the relevant group - filter( e -> e.getUniqueId().equals(groupId)). - //Get it - findAny().get(). - //Get Group Properties from it - convertToGroupProperties(); - - result = Either.left(groupProperties); - } - else{ - result = Either.right(eitherLastUpdateDateUpdatedOnResource.right().value()); - } - } - return result; - } - - - private TitanOperationStatus updateGroupProperty(GroupProperty groupProperty, GroupData groupData, - Wrapper lastUpdateTimeWrapper) { - TitanOperationStatus titanStatus = TitanOperationStatus.OK; - // PropertyValueData node does not exist - if (StringUtils.isEmpty(groupProperty.getValueUniqueUid())) { - // create new node - if (!StringUtils.isEmpty(groupProperty.getValue())) { - // Value does not exit and was not updated as well. no need - // to do anything - } else { - titanStatus = addGroupPropertyToGraph(groupProperty, groupData, lastUpdateTimeWrapper); - - } - } - - else { - titanStatus = updateGroupPropertyInGraph(groupProperty, lastUpdateTimeWrapper); - } - return titanStatus; - } - - private TitanOperationStatus updateGroupPropertyInGraph(GroupProperty groupProperty, - Wrapper lastUpdateTimeWrapper) { - TitanOperationStatus titanStatus; - Either eitherGroupPropertyValue = titanGenericDao.getNode( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), groupProperty.getValueUniqueUid(), - PropertyValueData.class); - if (eitherGroupPropertyValue.isRight()) { - - titanStatus = eitherGroupPropertyValue.right().value(); - - } else { - PropertyValueData groupPropertyValue = eitherGroupPropertyValue.left().value(); - // Actual Update only if value changed - if (!StringUtils.equals(groupPropertyValue.getValue(), groupProperty.getValue())) { - long modificationTime = lastUpdateTimeWrapper.isEmpty() ? System.currentTimeMillis() - : lastUpdateTimeWrapper.getInnerElement(); - groupPropertyValue.setValue(groupProperty.getValue()); - groupPropertyValue.setModificationTime(modificationTime); - Either eitherUpdateNode = titanGenericDao - .updateNode(groupPropertyValue, PropertyValueData.class); - if( eitherUpdateNode.isLeft() ){ - titanStatus = TitanOperationStatus.OK; - lastUpdateTimeWrapper.setInnerElement(modificationTime); - } - else{ - titanStatus = eitherUpdateNode.right().value(); - } - - } else { - titanStatus = TitanOperationStatus.OK; - } - } - return titanStatus; - } - - private TitanOperationStatus addGroupPropertyToGraph(GroupProperty groupProperty, GroupData groupData, - Wrapper lastUpdateTimeWrapper) { - PropertyDefinition propertyDefinition = null; - TitanOperationStatus ret = TitanOperationStatus.OK; - if (ret == TitanOperationStatus.OK) { - Either eitherPropertyDefFromGroupType = getPropertyDefFromGroupType( - groupProperty); - if (eitherPropertyDefFromGroupType.isRight()) { - log.debug("Error: Could not fetch group property from group Type with groupTypeId = {}", - groupProperty.getParentUniqueId()); - ret = eitherPropertyDefFromGroupType.right().value(); - } else { - propertyDefinition = eitherPropertyDefFromGroupType.left().value(); - } - } - if (ret == TitanOperationStatus.OK){ - final int groupPropCounter = groupData.getGroupDataDefinition().getPropertyValueCounter() + NumberUtils.INTEGER_ONE; - Either eitherAddPropertyToGroup = addPropertyToGroup(groupData, - groupProperty, propertyDefinition, groupPropCounter); - - if( eitherAddPropertyToGroup.isLeft() ){ - ret = TitanOperationStatus.OK; - if( lastUpdateTimeWrapper.isEmpty() ){ - lastUpdateTimeWrapper.setInnerElement(eitherAddPropertyToGroup.left().value().getCreationTime()); - } - } - else{ - ret = eitherAddPropertyToGroup.right().value(); - } - if( ret == TitanOperationStatus.OK){ - groupData.getGroupDataDefinition().setPropertyValueCounter(groupPropCounter); - Either updateNode = titanGenericDao .updateNode(groupData, GroupData.class); - if( updateNode.isRight() ){ - ret = updateNode.right().value(); - } - } - - } - return ret; - } - - public Either addPropertyToGroup(GroupData groupData, - GroupProperty groupProperty, PropertyDefinition prop, Integer index) { - - if (prop == null) { - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - - String propertyId = prop.getUniqueId(); - Either 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); - } - - PropertyData propertyData = findPropertyDefRes.left().value(); - - PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition(); - String propertyType = propDataDef.getType(); - String value = groupProperty.getValue(); - - Either checkInnerType = propertyOperation.checkInnerType(propDataDef); - if (checkInnerType.isRight()) { - TitanOperationStatus status = checkInnerType.right().value(); - return Either.right(status); - } - - String innerType = checkInnerType.left().value(); - - Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); - return Either.right(status); - - } - - log.debug("Before validateAndUpdatePropertyValue"); - Either 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.buildGroupPropertyValueUid((String) groupData.getUniqueId(), index); - PropertyValueData propertyValueData = new PropertyValueData(); - propertyValueData.setUniqueId(uniqueId); - propertyValueData.setValue(newValue); - - log.debug("Before adding property value to graph {}", propertyValueData); - Either 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); - } - - Either createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null); - - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - String description = "Failed to associate property value " + uniqueId + " to property " + propertyId + " in graph. status is " + operationStatus; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); - return Either.right(operationStatus); - } - - createRelResult = titanGenericDao.createRelation(groupData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null); - - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - String description = "Failed to associate group " + groupData.getGroupDataDefinition().getName() + " to property value " + uniqueId + " in graph. Status is " + operationStatus; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); - return Either.right(operationStatus); - } - - return Either.left(createNodeResult.left().value()); - } - - private Either associateGroupToComponent(GroupData groupData, NodeTypeEnum nodeTypeEnum, String componentId) { - UniqueIdData componentIdData = new UniqueIdData(nodeTypeEnum, componentId); - - log.debug("Before associating component {} to group {}", componentId, groupData); - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), groupData.getGroupDataDefinition().getName()); - Either createRelResult = titanGenericDao.createRelation(componentIdData, groupData, GraphEdgeLabels.GROUP, props); - log.debug("After associating component {} to group {}. status is {}", componentId, groupData, createRelResult); - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - log.debug("Failed to associate component {} to group {} in graph. Status is {}", componentId, groupData, operationStatus); - return Either.right(operationStatus); - } - - return Either.left(createRelResult.left().value()); - } - - private Either associateGroupToGroupType(GroupData groupData, String groupTypeUid) { - - UniqueIdData groupTypeIdData = new UniqueIdData(NodeTypeEnum.GroupType, groupTypeUid); - - log.debug("Before associating {} to group type {} (uid = {})", groupData, groupData.getGroupDataDefinition().getType(), groupTypeUid); - Either createRelResult = titanGenericDao.createRelation(groupData, groupTypeIdData, GraphEdgeLabels.TYPE_OF, null); - log.debug("After associating {} to group type {} (uid = {}). Result is {}", groupData, groupData.getGroupDataDefinition().getType(), groupTypeUid, createRelResult); - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - return Either.right(operationStatus); - } - return createRelResult; - } - - @Override - public Either addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition) { - return addGroup(nodeTypeEnum, componentId, groupDefinition, false); - } - - @Override - public Either addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition, boolean inTransaction) { - - Either result = null; - try { - Either addGroupRes = addGroupToGraph(nodeTypeEnum, componentId, groupDefinition); - if (addGroupRes.isRight()) { - TitanOperationStatus status = addGroupRes.right().value(); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } else { - - GroupData groupData = addGroupRes.left().value(); - String groupUid = groupData.getGroupDataDefinition().getUniqueId(); - result = this.getGroup(groupUid, true); - - } - - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph. Failed to add group {} to {}", groupDefinition.getName(), nodeTypeEnum.toString()); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - } - private GroupDefinition convertGroupDataToGroupDefinition(GroupData groupData) { GroupDefinition newGroupDefinition = new GroupDefinition(groupData.getGroupDataDefinition()); return newGroupDefinition; } - public Either getGroup(String uniqueId) { - return getGroup(uniqueId, false); - } - - @Override - public Either getGroup(String uniqueId, boolean inTransaction) { - - Either result = null; - - try { - - Either groupFromGraph = this.getGroupFromGraph(uniqueId); - - if (groupFromGraph.isRight()) { - TitanOperationStatus status = groupFromGraph.right().value(); - log.debug("Failed to retrieve group {} from graph. Status is {}", uniqueId, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } else { - GroupDefinition groupDefinition = groupFromGraph.left().value(); - result = Either.left(groupDefinition); - } - - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - @Override - public Either getGroupFromGraph(String uniqueId) { - - return getGroupFromGraph(uniqueId, false, false, false); - - } - /** * get members of group * * @param groupUniqueId * @return */ - protected Either, TitanOperationStatus> getGroupMembers(String groupUniqueId) { + private Either, TitanOperationStatus> getGroupMembers(String groupUniqueId) { Either, TitanOperationStatus> result = null; @@ -711,7 +128,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation return result; } - public Either getGroupTypeOfGroup(String groupUniqueId) { + private Either getGroupTypeOfGroup(String groupUniqueId) { Either, TitanOperationStatus> groupTypeRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.TYPE_OF, NodeTypeEnum.GroupType, GroupTypeData.class); @@ -726,9 +143,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation GroupTypeData groupTypeData = groupTypeRes.left().value().getKey(); - Either groupTypeByUid = groupTypeOperation.getGroupTypeByUid(groupTypeData.getGroupTypeDataDefinition().getUniqueId()); - - return groupTypeByUid; + return groupTypeOperation.getGroupTypeByUid(groupTypeData.getGroupTypeDataDefinition().getUniqueId()); } @@ -740,7 +155,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation * @param groupUid * @return */ - public Either, TitanOperationStatus> getGroupProperties(String groupUid) { + private Either, TitanOperationStatus> getGroupProperties(String groupUid) { List groupPropertiesList = new ArrayList<>(); @@ -824,313 +239,273 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation return Either.left(groupPropertiesList); } - public Either, TitanOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum) { - - return getAllGroupsFromGraph(componentId, componentTypeEnum, false, false, false); + @Override + public Either, TitanOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String artifactId) { - } + List relations = new ArrayList<>(); + Either, TitanOperationStatus> result = Either.left(relations); - @Override - public Either, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction) { + Either, TitanOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true, false); + if (allGroupsFromGraph.isRight()) { + TitanOperationStatus status = allGroupsFromGraph.right().value(); + return Either.right(status); + } - Either, StorageOperationStatus> result = null; + List allGroups = allGroupsFromGraph.left().value(); + if (allGroups == null || allGroups.isEmpty()) { + return Either.right(TitanOperationStatus.OK); + } - try { + // Find all groups which contains this artifact id + List associatedGroups = allGroups.stream().filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(artifactId)).collect(Collectors.toList()); - Either, TitanOperationStatus> allGroups = this.getAllGroupsFromGraph(componentId, compTypeEnum); + if (associatedGroups != null && false == associatedGroups.isEmpty()) { + log.debug("The groups {} contains the artifact {}", associatedGroups.stream().map(p -> p.getName()).collect(Collectors.toList()), artifactId); - if (allGroups.isRight()) { - TitanOperationStatus status = allGroups.right().value(); - log.debug("Failed to retrieve all groups of component {} from graph. Status is {}", componentId, status); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; + UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId); + for (GroupDefinition groupDefinition : associatedGroups) { + UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId()); + Either 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); } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } else { - List groupsDefinition = allGroups.left().value(); - result = Either.left(groupsDefinition); + + relations.add(deleteRelation.left().value()); } return result; - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } + } else { + log.debug("No group under component id {} is associated to artifact {}", componentId, artifactId); + return Either.right(TitanOperationStatus.OK); } } - @Override - public Either, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum) { - return getAllGroups(componentId, compTypeEnum, false); - } + public Either getGroupFromGraph(String uniqueId, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) { - public Either deleteGroupFromGraph(String groupUniqueId) { + Either result = null; - Either groupFromGraph = this.getGroupFromGraph(groupUniqueId); - if (groupFromGraph.isRight()) { - TitanOperationStatus status = groupFromGraph.right().value(); - log.debug("Cannot find group {} on graph. Status is {}", groupUniqueId, status); - return Either.right(status); + Either 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; } - GroupDefinition groupDefinition = groupFromGraph.left().value(); - // 1. delete all properties values nodes - List properties = groupDefinition.convertToGroupProperties(); - if (properties != null) { - for (GroupProperty groupProperty : properties) { - String propValueUniqueId = groupProperty.getValueUniqueUid(); - - if (propValueUniqueId != null) { - UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.PropertyValue, propValueUniqueId); - Either deleteNode = titanGenericDao.deleteNode(uniqueIdData, PropertyValueData.class); - if (deleteNode.isRight()) { - TitanOperationStatus status = groupFromGraph.right().value(); - log.debug("Failed to delete property {} under group {} {} on graph. Status is {}", propValueUniqueId, groupDefinition.getName(), groupUniqueId, status.name()); - BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_GROUP, propValueUniqueId, status.name()); - return Either.right(status); - } else { - log.trace("Property {} was deleted from group {}" ,propValueUniqueId, groupDefinition.getName()); - } - } - } - } + GroupData groupData = groupRes.left().value(); - // 2. delete the group node - UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.Group, groupUniqueId); - Either deleteNode = titanGenericDao.deleteNode(uniqueIdData, GroupData.class); - if (deleteNode.isRight()) { - TitanOperationStatus status = groupFromGraph.right().value(); - log.debug("Failed to delete group {} with uid {} on graph. Status is {}", groupDefinition.getName(), groupUniqueId, status.name()); - BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_GROUP, groupUniqueId, status.name()); - return Either.right(status); - } else { - log.trace("Group {} was deleted from group", groupUniqueId); - } + GroupDefinition groupDefinition = convertGroupDataToGroupDefinition(groupData); - GroupData groupData = deleteNode.left().value(); - return Either.left(groupData); - } + Either groupTypeOfGroup = getGroupTypeOfGroup(uniqueId); - public Either deleteGroup(String groupUniqueId) { - return deleteGroup(groupUniqueId, false); - } + if (groupTypeOfGroup.isRight()) { + TitanOperationStatus status = groupTypeOfGroup.right().value(); + log.debug("Failed to retrieve capability type of capability {}. Status is {}", uniqueId, status); - public Either deleteGroup(String groupUniqueId, boolean inTransaction) { + result = Either.right(status); + return result; + } - Either result = null; + GroupTypeDefinition groupTypeDefinition = groupTypeOfGroup.left().value(); - try { + groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); - Either deleteGroup = this.deleteGroupFromGraph(groupUniqueId); + if (false == skipMembers) { + Either, TitanOperationStatus> membersRes = getGroupMembers(uniqueId); + if (membersRes.isRight()) { + TitanOperationStatus status = membersRes.right().value(); + if (status != TitanOperationStatus.OK) { + result = Either.right(status); + return result; + } + } else { + Map members = membersRes.left().value(); + groupDefinition.setMembers(members); + } + } - if (deleteGroup.isRight()) { - TitanOperationStatus status = deleteGroup.right().value(); - log.debug("Failed to delete group {} from graph. Status is ", groupUniqueId, status.name()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + if (false == skipProperties) { + Either, TitanOperationStatus> propertiesRes = getGroupProperties(uniqueId); + if (propertiesRes.isRight()) { + TitanOperationStatus status = propertiesRes.right().value(); + if (status != TitanOperationStatus.OK) { + result = Either.right(status); + return result; + } } else { - GroupData groupData = deleteGroup.left().value(); - GroupDefinition groupDefinition = convertGroupDataToGroupDefinition(groupData); - result = Either.left(groupDefinition); + List properties = propertiesRes.left().value(); + groupDefinition.convertFromGroupProperties(properties); } + } - return result; + if (false == skipArtifacts) { + Either>, TitanOperationStatus> artifactsRes = getGroupArtifactsPairs(uniqueId); + if (artifactsRes.isRight()) { + TitanOperationStatus status = artifactsRes.right().value(); + if (status != TitanOperationStatus.OK) { + result = Either.right(status); + return result; + } + } else { + List artifactsUid = new ArrayList<>(); + List artifactsUUID = new ArrayList<>(); - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); + List> list = artifactsRes.left().value(); + if (list != null) { + for (ImmutablePair 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 Either, TitanOperationStatus> deleteAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum) { + public boolean isGroupExist(String groupName, boolean inTransaction) { + + Either, TitanOperationStatus> eitherGroup = null; + try { + Map 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, TitanOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) { + + List groups = new ArrayList(); Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId, GraphEdgeLabels.GROUP, NodeTypeEnum.Group, GroupData.class); if (childrenNodes.isRight()) { TitanOperationStatus status = childrenNodes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeFailedFindAllNodesError(DELETING_ALL_GROUPS, NodeTypeEnum.Group.name(), componentId, status.name()); - } return Either.right(status); } - List result = new ArrayList<>(); + List> graphGroups = childrenNodes.left().value(); - List> list = childrenNodes.left().value(); - if (list != null) { - for (ImmutablePair pair : list) { - String uniqueId = pair.left.getGroupDataDefinition().getUniqueId(); - Either deleteGroupFromGraph = deleteGroupFromGraph(uniqueId); - if (deleteGroupFromGraph.isRight()) { - TitanOperationStatus status = deleteGroupFromGraph.right().value(); - BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_ALL_GROUPS, uniqueId, status.name()); - return Either.right(status); - } - GroupData groupData = deleteGroupFromGraph.left().value(); - GroupDefinition groupDefinition = convertGroupDataToGroupDefinition(groupData); - result.add(groupDefinition); - } + if (graphGroups == null || true == graphGroups.isEmpty()) { + return Either.right(TitanOperationStatus.NOT_FOUND); } - return Either.left(result); - } - - @Override - public Either, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction) { - - Either, StorageOperationStatus> result = null; + // Consumer consumer = (x) -> getGroup(x); + // StreamUtils.takeWhile(graphGroups.stream().map(p -> + // p.left.getUniqueId()), consumer); - try { + for (ImmutablePair pair : graphGroups) { - Either, TitanOperationStatus> allGroups = this.deleteAllGroupsFromGraph(componentId, compTypeEnum); + String groupUniqueId = pair.left.getGroupDataDefinition().getUniqueId(); + Either groupRes = this.getGroupFromGraph(groupUniqueId, skipProperties, skipMembers, skipArtifacts); - if (allGroups.isRight()) { - TitanOperationStatus status = allGroups.right().value(); - log.debug("Failed to delete all groups of component {} from graph. Status is {}", componentId, status); + if (groupRes.isRight()) { + TitanOperationStatus status = groupRes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; + status = TitanOperationStatus.INVALID_ID; } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return Either.right(status); } else { - List groupsDefinition = allGroups.left().value(); - result = Either.left(groupsDefinition); + groups.add(groupRes.left().value()); } - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } } + return Either.left(groups); } - @Override - public Either, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum) { - return deleteAllGroups(componentId, compTypeEnum, false); - } + private TitanOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { - public Either, StorageOperationStatus> prepareGroupsForCloning(org.openecomp.sdc.be.model.Component origResource, ImmutablePair, Map> cloneInstances) { + Either, TitanOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true, false); + if (allGroupsFromGraph.isRight()) { + TitanOperationStatus status = allGroupsFromGraph.right().value(); + return status; + } - List groupsToCreate = new ArrayList<>(); - Either, StorageOperationStatus> result = Either.left(groupsToCreate); + List allGroups = allGroupsFromGraph.left().value(); + if (allGroups == null || allGroups.isEmpty()) { + return TitanOperationStatus.OK; + } - List groups = origResource.getGroups(); + // Find all groups which contains this artifact id + List associatedGroups = allGroups.stream().filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(oldArtifactId)).collect(Collectors.toList()); - if (groups != null) { - // keep typeUid - // keep artifacts uids - // remove properties without valueUniqueId - for (GroupDefinition groupDefinition : groups) { + if (associatedGroups != null && false == associatedGroups.isEmpty()) { - GroupDefinition gdToCreate = new GroupDefinition(groupDefinition); - gdToCreate.setUniqueId(null); - gdToCreate.setMembers(null); + log.debug("The groups {} contains the artifact {}", associatedGroups.stream().map(p -> p.getName()).collect(Collectors.toList()), oldArtifactId); - List properties = groupDefinition.convertToGroupProperties(); - if (properties != null) { - // Take properties which was updated in the - // group(getValueUniqueUid != null), - // Then set null instead of the value(prepare for the - // creation). - List propertiesToUpdate = properties.stream().filter(p -> p.getValueUniqueUid() != null).map(p -> { - p.setValueUniqueUid(null); - return p; - }).collect(Collectors.toList()); + UniqueIdData oldArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, oldArtifactId); + UniqueIdData newArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, newArtifact.getArtifactDataDefinition().getUniqueId()); + Map props = new HashMap(); + props.put(GraphPropertiesDictionary.NAME.getProperty(), newArtifactData.getLabel()); - gdToCreate.convertFromGroupProperties(propertiesToUpdate); + for (GroupDefinition groupDefinition : associatedGroups) { + UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId()); + Either 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; } - Map members = groupDefinition.getMembers(); - if (cloneInstances != null) { - List createdInstances = cloneInstances.left; - Map oldCompUidToNew = cloneInstances.right; - if (members != null && createdInstances != null) { - - Map compInstIdToName = createdInstances.stream().collect(Collectors.toMap(p -> p.getUniqueId(), p -> p.getName())); - - Map membersToCreate = new HashMap<>(); - - for (String oldCompInstId : members.values()) { - String newCompInstUid = oldCompUidToNew.get(oldCompInstId); - if (newCompInstUid == null) { - result = Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - return result; - } - String newCompInstName = compInstIdToName.get(newCompInstUid); - membersToCreate.put(newCompInstName, newCompInstUid); - } - - gdToCreate.setMembers(membersToCreate); + Either 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; } - - log.debug("The group definition for creation is {}", gdToCreate); - - groupsToCreate.add(gdToCreate); } } - - return result; + return TitanOperationStatus.OK; } @Override - public Either, StorageOperationStatus> addGroups(NodeTypeEnum nodeTypeEnum, String componentId, List groups, boolean inTransaction) { - - List createdGroups = new ArrayList<>(); + public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction) { - Either, StorageOperationStatus> result = null; + StorageOperationStatus result = null; try { + TitanOperationStatus status = this.dissociateAndAssociateGroupsFromArtifactOnGraph(componentId, componentTypeEnum, oldArtifactId, newArtifact); - if (groups != null) { - for (GroupDefinition groupDefinition : groups) { - Either addGroup = this.addGroup(nodeTypeEnum, componentId, groupDefinition, true); - if (addGroup.isRight()) { - StorageOperationStatus status = addGroup.right().value(); - result = Either.right(status); - return result; - } - - createdGroups.add(addGroup.left().value()); - } + if (status != TitanOperationStatus.OK && status != TitanOperationStatus.NOT_FOUND) { + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + return result; } - result = Either.left(createdGroups); + result = StorageOperationStatus.OK; return result; } finally { if (false == inTransaction) { - if (result == null || result.isRight()) { + if (result == null || result != StorageOperationStatus.OK) { log.debug("Going to execute rollback on graph."); BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); titanGenericDao.rollback(); @@ -1142,971 +517,41 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } } - @Override - public Either, TitanOperationStatus> getAssociatedGroupsToComponentInstanceFromGraph(String componentInstanceId) { - - List groups = new ArrayList<>(); - Either, TitanOperationStatus> result = Either.left(groups); + private Either>, TitanOperationStatus> getGroupArtifactsPairs(String groupUniqueId) { - Either>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), componentInstanceId, GraphEdgeLabels.GROUP_MEMBER, - NodeTypeEnum.Group, GroupData.class); + Either>, TitanOperationStatus> result = null; - if (parentNodes.isRight()) { - TitanOperationStatus status = parentNodes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeFailedFindParentError("FetchGroupMembers", componentInstanceId, status.name()); + Either>, 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; } - return Either.right(status); - } - - List> fetchedGroups = parentNodes.left().value(); - if (fetchedGroups != null) { - List list = fetchedGroups.stream().map(p -> p.left.getGroupDataDefinition().getUniqueId()).collect(Collectors.toList()); - groups.addAll(list); - } - - return result; - - } - - @Override - public Either, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId, boolean inTransaction) { - - Either, StorageOperationStatus> result = null; - - try { + result = Either.right(status); - Either, TitanOperationStatus> groups = this.getAssociatedGroupsToComponentInstanceFromGraph(componentInstanceId); + } else { - if (groups.isRight()) { - TitanOperationStatus status = groups.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; + List> artifactsList = new ArrayList<>(); + List> list = childrenNodes.left().value(); + if (list != null) { + for (ImmutablePair pair : list) { + ArtifactData artifactData = pair.getKey(); + String uniqueId = artifactData.getArtifactDataDefinition().getUniqueId(); + String UUID = artifactData.getArtifactDataDefinition().getArtifactUUID(); + ImmutablePair artifact = new ImmutablePair(uniqueId, UUID); + artifactsList.add(artifact); } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; } - List list = groups.left().value(); + log.debug("The artifacts list related to group {} is {}", groupUniqueId, artifactsList); + result = Either.left(artifactsList); + } - return Either.left(list); + return result; - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - @Override - public Either, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId) { - return getAssociatedGroupsToComponentInstance(componentInstanceId, false); - } - - @Override - public Either, TitanOperationStatus> associateGroupsToComponentInstanceOnGraph(List groups, String componentInstanceId, String compInstName) { - - List relations = new ArrayList<>(); - Either, TitanOperationStatus> result = Either.left(relations); - - if (groups != null && false == groups.isEmpty()) { - - UniqueIdData compInstData = new UniqueIdData(NodeTypeEnum.ResourceInstance, componentInstanceId); - - for (String groupId : groups) { - UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupId); - - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), compInstName); - Either createRelation = titanGenericDao.createRelation(groupData, compInstData, GraphEdgeLabels.GROUP_MEMBER, props); - if (createRelation.isRight()) { - TitanOperationStatus status = createRelation.right().value(); - String description = "Failed to associate group " + groupData.getUniqueId() + " to component instance " + compInstName + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ASSOCIATING_GROUP_TO_COMP_INST, description, ErrorSeverity.ERROR); - result = Either.right(status); - break; - } - GraphRelation graphRelation = createRelation.left().value(); - relations.add(graphRelation); - } - } else { - result = Either.right(TitanOperationStatus.OK); - } - - return result; - } - - public StorageOperationStatus associateGroupsToComponentInstance(List groups, String componentInstanceId, String compInstName) { - - return associateGroupsToComponentInstance(groups, componentInstanceId, compInstName, false); - } - - @Override - public StorageOperationStatus associateGroupsToComponentInstance(List groups, String componentInstanceId, String compInstName, boolean inTransaction) { - - StorageOperationStatus result = null; - - try { - Either, TitanOperationStatus> either = this.associateGroupsToComponentInstanceOnGraph(groups, componentInstanceId, compInstName); - - if (either.isRight()) { - TitanOperationStatus status = either.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - 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(); - } - } - } - - } - - @Override - public Either, TitanOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String artifactId) { - - List relations = new ArrayList<>(); - Either, TitanOperationStatus> result = Either.left(relations); - - Either, TitanOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true, false); - if (allGroupsFromGraph.isRight()) { - TitanOperationStatus status = allGroupsFromGraph.right().value(); - return Either.right(status); - } - - List allGroups = allGroupsFromGraph.left().value(); - if (allGroups == null || allGroups.isEmpty()) { - return Either.right(TitanOperationStatus.OK); - } - - // Find all groups which contains this artifact id - List 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); - - UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId); - for (GroupDefinition groupDefinition : associatedGroups) { - UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId()); - Either 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); - } - - relations.add(deleteRelation.left().value()); - } - - return result; - - } else { - log.debug("No group under component id {} is associated to artifact {}", componentId, artifactId); - return Either.right(TitanOperationStatus.OK); - } - - } - - public Either getGroupFromGraph(String uniqueId, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) { - - Either result = null; - - Either 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; - } - - GroupData groupData = groupRes.left().value(); - - GroupDefinition groupDefinition = convertGroupDataToGroupDefinition(groupData); - - Either groupTypeOfGroup = getGroupTypeOfGroup(uniqueId); - - if (groupTypeOfGroup.isRight()) { - TitanOperationStatus 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 (false == skipMembers) { - Either, TitanOperationStatus> membersRes = getGroupMembers(uniqueId); - if (membersRes.isRight()) { - TitanOperationStatus status = membersRes.right().value(); - if (status != TitanOperationStatus.OK) { - result = Either.right(status); - return result; - } - } else { - Map members = membersRes.left().value(); - groupDefinition.setMembers(members); - } - } - - if (false == skipProperties) { - Either, TitanOperationStatus> propertiesRes = getGroupProperties(uniqueId); - if (propertiesRes.isRight()) { - TitanOperationStatus status = propertiesRes.right().value(); - if (status != TitanOperationStatus.OK) { - result = Either.right(status); - return result; - } - } else { - List properties = propertiesRes.left().value(); - groupDefinition.convertFromGroupProperties(properties); - } - } - - if (false == skipArtifacts) { - Either>, TitanOperationStatus> artifactsRes = getGroupArtifactsPairs(uniqueId); - if (artifactsRes.isRight()) { - TitanOperationStatus status = artifactsRes.right().value(); - if (status != TitanOperationStatus.OK) { - result = Either.right(status); - return result; - } - } else { - List artifactsUid = new ArrayList<>(); - List artifactsUUID = new ArrayList<>(); - - List> list = artifactsRes.left().value(); - if (list != null) { - for (ImmutablePair 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, TitanOperationStatus> eitherGroup = null; - try { - Map 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, TitanOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) { - - List groups = new ArrayList(); - - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId, GraphEdgeLabels.GROUP, NodeTypeEnum.Group, - GroupData.class); - - if (childrenNodes.isRight()) { - TitanOperationStatus status = childrenNodes.right().value(); - return Either.right(status); - } - - List> graphGroups = childrenNodes.left().value(); - - if (graphGroups == null || true == graphGroups.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - // Consumer consumer = (x) -> getGroup(x); - // StreamUtils.takeWhile(graphGroups.stream().map(p -> - // p.left.getUniqueId()), consumer); - - for (ImmutablePair pair : graphGroups) { - - String groupUniqueId = pair.left.getGroupDataDefinition().getUniqueId(); - Either 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()); - } - - } - - return Either.left(groups); - } - - @Override - public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId, boolean inTransaction) { - - StorageOperationStatus result = null; - - try { - Either, TitanOperationStatus> either = this.dissociateAllGroupsFromArtifactOnGraph(componentId, componentTypeEnum, artifactId); - - if (either.isRight()) { - TitanOperationStatus status = either.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - 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(); - } - } - } - - } - - @Override - public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId) { - - return dissociateAllGroupsFromArtifact(componentId, componentTypeEnum, artifactId, false); - } - - @Override - public TitanOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { - - Either, TitanOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true, false); - if (allGroupsFromGraph.isRight()) { - TitanOperationStatus status = allGroupsFromGraph.right().value(); - return status; - } - - List allGroups = allGroupsFromGraph.left().value(); - if (allGroups == null || allGroups.isEmpty()) { - return TitanOperationStatus.OK; - } - - // Find all groups which contains this artifact id - List 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 props = new HashMap(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), newArtifactData.getLabel()); - - for (GroupDefinition groupDefinition : associatedGroups) { - UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId()); - - Either 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 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; - } - } - - } - 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(); - } - } - } - - } - - @Override - public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { - return dissociateAndAssociateGroupsFromArtifact(componentId, componentTypeEnum, oldArtifactId, newArtifact, false); - } - - private Either>, TitanOperationStatus> getGroupArtifactsPairs(String groupUniqueId) { - - Either>, TitanOperationStatus> result = null; - - Either>, 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> artifactsList = new ArrayList<>(); - List> list = childrenNodes.left().value(); - if (list != null) { - for (ImmutablePair pair : list) { - ArtifactData artifactData = pair.getKey(); - String uniqueId = artifactData.getArtifactDataDefinition().getUniqueId(); - String UUID = artifactData.getArtifactDataDefinition().getArtifactUUID(); - ImmutablePair 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; - - } - - public Either, TitanOperationStatus> updateGroupVersionOnGraph(List groupsUniqueId) { - - if (groupsUniqueId != null) { - - List groups = new ArrayList<>(); - for (String groupUid : groupsUniqueId) { - Either either = updateGroupVersionOnGraph(groupUid); - if (either.isRight()) { - log.debug("Failed to update version of group {}", groupUid); - return Either.right(either.right().value()); - } - groups.add(either.left().value()); - } - return Either.left(groups); - } - - return Either.right(TitanOperationStatus.OK); - - } - - /** - * update the group version of a given group. It also creates a new UUID. - * - * @param groupUniqueId - * @return - */ - public Either updateGroupVersionOnGraph(String groupUniqueId) { - - Either groupFromGraph = this.getGroupFromGraph(groupUniqueId, false, false, false); - - if (groupFromGraph.isRight()) { - TitanOperationStatus status = groupFromGraph.right().value(); - return Either.right(status); - } else { - GroupDefinition groupDefinition = groupFromGraph.left().value(); - String version = groupDefinition.getVersion(); - String newVersion = increaseMajorVersion(version); - Integer pvCounter = groupDefinition.getPropertyValueCounter(); - - GroupData groupData = new GroupData(); - groupData.getGroupDataDefinition().setUniqueId(groupUniqueId); - groupData.getGroupDataDefinition().setVersion(newVersion); - groupData.getGroupDataDefinition().setPropertyValueCounter(pvCounter); - - String groupUUID = UniqueIdBuilder.generateUUID(); - groupData.getGroupDataDefinition().setGroupUUID(groupUUID); - - Either updateNode = titanGenericDao.updateNode(groupData, GroupData.class); - if (updateNode.isRight()) { - return Either.right(updateNode.right().value()); - } else { - groupFromGraph = this.getGroupFromGraph(groupUniqueId, false, false, false); - return groupFromGraph; - } - - } - } - - - - /** - * The version of the group is an integer. In order to support BC, we might get a version in a float format. - * - * @param version - * @return - */ - private String increaseMajorVersion(String version) { - - String[] versionParts = version.split(LifecycleOperation.VERSION_DELIMETER_REGEXP); - Integer majorVersion = Integer.parseInt(versionParts[0]); - - majorVersion++; - - return String.valueOf(majorVersion); - - } - - public Either associateArtifactsToGroupOnGraph(String groupId, List artifactsId) { - - if (artifactsId == null || artifactsId.isEmpty()) { - return Either.right(TitanOperationStatus.OK); - } - - for (String artifactId : artifactsId) { - Either findArtifactRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class); - if (findArtifactRes.isRight()) { - TitanOperationStatus status = findArtifactRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - String description = "Failed to associate group " + groupId + " to artifact " + artifactId + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); - return Either.right(status); - } - - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), findArtifactRes.left().value().getLabel()); - - GraphNode groupData = new UniqueIdData(NodeTypeEnum.Group, groupId); - Either addArtifactsRefResult = titanGenericDao.createRelation(groupData, findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF, props); - - if (addArtifactsRefResult.isRight()) { - TitanOperationStatus status = addArtifactsRefResult.right().value(); - String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); - return Either.right(status); - } - } - - Either groupFromGraph = this.getGroupFromGraph(groupId, true, true, false); - - return groupFromGraph; - } - - public Either associateMembersToGroupOnGraph(String groupId, Map members) { - - if (members != null && false == members.isEmpty()) { - Either addMembersRefResult = null; - for (Entry member : members.entrySet()) { - Either findComponentInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), member.getValue(), ComponentInstanceData.class); - if (findComponentInstanceRes.isRight()) { - - TitanOperationStatus status = findComponentInstanceRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - String description = "Failed to find to find component instance group " + member.getValue() + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); - return Either.right(status); - } - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), member.getKey()); - GraphNode groupData = new UniqueIdData(NodeTypeEnum.Group, groupId); - addMembersRefResult = titanGenericDao.createRelation(groupData, findComponentInstanceRes.left().value(), GraphEdgeLabels.GROUP_MEMBER, props); - if (addMembersRefResult.isRight()) { - TitanOperationStatus status = addMembersRefResult.right().value(); - String description = "Failed to associate group " + groupData.getUniqueId() + " to component instance " + member.getValue() + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); - return Either.right(status); - } - } - } - - Either groupFromGraph = this.getGroupFromGraph(groupId, true, false, true); - - return groupFromGraph; - } - - public Either dissociateArtifactsFromGroupOnGraph(String groupId, List artifactsId) { - - if (artifactsId == null || artifactsId.isEmpty()) { - return Either.right(TitanOperationStatus.OK); - } - - UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupId); - for (String artifactId : artifactsId) { - - UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.Group, artifactId); - Either deleteRelation = titanGenericDao.deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF); - log.trace("After dissociate group {} from artifact {}" ,groupId, artifactId); - - if (deleteRelation.isRight()) { - TitanOperationStatus status = deleteRelation.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - String description = "Failed to diassociate group " + groupId + " from artifact " + artifactId + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); - return Either.right(status); - } - - } - - Either groupFromGraph = this.getGroupFromGraph(groupId, true, true, false); - - return groupFromGraph; - - } - - public Either dissociateMembersFromGroupOnGraph(String groupId, Map members) { - - if (members == null || members.isEmpty()) { - return Either.right(TitanOperationStatus.OK); - } - - UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupId); - for (Entry member : members.entrySet()) { - - UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.Group, member.getValue()); - Either deleteRelation = titanGenericDao.deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_MEMBER); - log.trace("After dissociate group {} from members {}" ,groupId, member.getValue()); - - if (deleteRelation.isRight()) { - TitanOperationStatus status = deleteRelation.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - String description = "Failed to diassociate group " + groupId + " from member " + member.getValue() + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); - return Either.right(status); - } - - } - - Either groupFromGraph = this.getGroupFromGraph(groupId, true, true, false); - - return groupFromGraph; - - } - - /** - * dissociate artifacts from a group. It do not delete the artifacts !!! - * - * @param groupId - * @param artifactsId - * @param inTransaction - * @return - */ - public Either dissociateArtifactsFromGroup(String groupId, List artifactsId, boolean inTransaction) { - - Either result = null; - - try { - Either titanRes = this.dissociateArtifactsFromGroupOnGraph(groupId, artifactsId); - - if (titanRes.isRight()) { - StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value()); - result = Either.right(storageOperationStatus); - return result; - } - - result = Either.left(titanRes.left().value()); - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - public Either dissociateMembersFromGroup(String groupId, Map members, boolean inTransaction) { - - Either result = null; - - try { - Either titanRes = this.dissociateMembersFromGroupOnGraph(groupId, members); - - if (titanRes.isRight()) { - StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value()); - result = Either.right(storageOperationStatus); - return result; - } - - result = Either.left(titanRes.left().value()); - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - /** - * Associate artifacts to a given group - * - * @param groupId - * @param artifactsId - * @param inTransaction - * @return - */ - public Either associateArtifactsToGroup(String groupId, List artifactsId, boolean inTransaction) { - - Either result = null; - - try { - - Either titanRes = this.associateArtifactsToGroupOnGraph(groupId, artifactsId); - - if (titanRes.isRight()) { - StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value()); - result = Either.right(status); - } - - result = Either.left(titanRes.left().value()); - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - /** - * Associate artifacts to a given group - * - * @param groupId - * @param artifactsId - * @param inTransaction - * @return - */ - public Either associateMembersToGroup(String groupId, Map members, boolean inTransaction) { - - Either result = null; - - try { - - Either titanRes = this.associateMembersToGroupOnGraph(groupId, members); - - if (titanRes.isRight()) { - StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value()); - result = Either.right(status); - return result; - } - - result = Either.left(titanRes.left().value()); - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - public Either, StorageOperationStatus> updateGroupVersion(List groupsId, boolean inTransaction) { - - Either, StorageOperationStatus> result = null; - - try { - Either, TitanOperationStatus> updateGroupVersionOnGraph = this.updateGroupVersionOnGraph(groupsId); - - if (updateGroupVersionOnGraph.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateGroupVersionOnGraph.right().value())); - return result; - } - - result = Either.left(updateGroupVersionOnGraph.left().value()); - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - /** - * This method updates group name - * @param groupToUpdateFromUniqueId - * @param newName - * @param inTransaction - * @return - */ - public Either updateGroupName(String groupToUpdateFromUniqueId, - String newName, boolean inTransaction) { - Either result = null; - - try { - //Update Name - Either updateGroupNameOnGraph = updateGroupNameOnGraph( - groupToUpdateFromUniqueId, newName); - - if (updateGroupNameOnGraph.isRight()) { - result = Either.right( - DaoStatusConverter.convertTitanStatusToStorageStatus(updateGroupNameOnGraph.right().value())); - } - else{ - result = Either.left(updateGroupNameOnGraph.left().value()); - } - return result; - - } finally { - handleTransactionCommitRollback(inTransaction, result); - } - } - @Override - public Either updateGroupName(String groupToUpdateFromUniqueId, - String newName, GroupDefinition groupToUpdateTo, boolean inTransaction) { - Either result = null; - - try { - //Update Name - result = updateGroupName(groupToUpdateFromUniqueId, newName, true); - return result; - - } finally { - handleTransactionCommitRollback(inTransaction, result); - } - } - - private Either updateGroupNameOnGraph(String uniqueId, String newName) { - - Either groupFromGraph = this.getGroupFromGraph(uniqueId, false, false, false); - - if (groupFromGraph.isRight()) { - TitanOperationStatus status = groupFromGraph.right().value(); - return Either.right(status); - } else { - GroupDefinition groupDefinition = groupFromGraph.left().value(); - String version = groupDefinition.getVersion(); - String newVersion = increaseMajorVersion(version); - Integer pvCounter = groupDefinition.getPropertyValueCounter(); - - GroupData groupData = new GroupData(); - groupData.getGroupDataDefinition().setUniqueId(uniqueId); - groupData.getGroupDataDefinition().setVersion(newVersion); - groupData.getGroupDataDefinition().setName(newName); - groupData.getGroupDataDefinition().setPropertyValueCounter(pvCounter); - - Either updateNode = titanGenericDao.updateNode(groupData, GroupData.class); - if (updateNode.isRight()) { - return Either.right(updateNode.right().value()); - } else { - groupFromGraph = this.getGroupFromGraph(uniqueId, false, false, false); - return groupFromGraph; - } - } } - @Override public StorageOperationStatus validateAndUpdatePropertyValue(GroupProperty property) { 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 d3db95df65..782c78715f 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 @@ -90,462 +90,12 @@ import fj.data.Either; @Component("input-operation") public class InputsOperation extends AbstractOperation implements IInputsOperation { - private static final String GET_INPUT = "get_input"; - - private static String ASSOCIATING_INPUT_TO_PROP = "AssociatingInputToComponentInstanceProperty"; - private static Logger log = LoggerFactory.getLogger(InputsOperation.class.getName()); @Autowired PropertyOperation propertyOperation; - @Autowired - private ComponentInstanceOperation componentInstanceOperation; Gson gson = new Gson(); - /** - * Delete specific input from component Although inputId is unique, pass also componentId as all other methods, and also check that the inputId is inside that componentId. - */ - @Override - public Either deleteInput(String inputId) { - log.debug(String.format("Before deleting input: %s from graph", inputId)); - List inputsValueList = null; - List propertyList = new ArrayList<>(); - - Either vertexService = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId); - - if (vertexService.isRight()) { - log.debug("failed to fetch vertex of resource input for id = {}", inputId); - TitanOperationStatus status = vertexService.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - - StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - return Either.right(convertTitanStatusToStorageStatus); - } - TitanVertex vertex = vertexService.left().value(); - Iterator edgeIter = vertex.edges(Direction.IN, GraphEdgeLabels.INPUT.getProperty()); - - if (edgeIter == null) { - log.debug("No edges in graph for criteria"); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND)); - } - String inputName = ""; - if (edgeIter != null) { - while (edgeIter.hasNext()) { - Edge edge = edgeIter.next(); - GraphEdge graphEdge = null; - - Map edgeProps = titanGenericDao.getProperties(edge); - GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label()); - graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps); - - inputName = (String) graphEdge.getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty()); - - } - } - - - Either, TitanOperationStatus> inputsValueStatus = this.getComponentInstanceInputsByInputId(inputId); - if(inputsValueStatus.isLeft()){ - inputsValueList = inputsValueStatus.left().value(); - if(!inputsValueList.isEmpty()){ - for(ComponentInstanceInput inputValue: inputsValueList){ - Either deleteNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InputValue), inputValue.getValueUniqueUid(), InputValueData.class); - if (deleteNode.isRight()) { - StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteNode.right().value()); - return Either.right(convertTitanStatusToStorageStatus); - } - } - } - // US848813 delete service input that relates to VL / CP property - } else { - Either, TitanOperationStatus> propertyValueStatus = getComponentInstancePropertiesByInputId(inputId); - if(propertyValueStatus.isLeft() && !propertyValueStatus.left().value().isEmpty()){ - //propertyList = propertyValueStatus.left().value(); - for(ComponentInstanceProperty propertyValue: propertyValueStatus.left().value()){ - - String value = propertyValue.getValue(); - Map mappedToscaTemplate = (Map) new Yaml().load(value); - - resetInputName(mappedToscaTemplate, inputName); - - value = gson.toJson(mappedToscaTemplate); - propertyValue.setValue(value); - String compInstId = propertyValue.getComponentInstanceId(); - propertyValue.setRules(null); - - Either eitherStatus = componentInstanceOperation.updatePropertyOfResourceInstance(propertyValue, compInstId, false); - - if (eitherStatus.isRight()) { - log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", propertyValue, compInstId, eitherStatus.right().value().name()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); - - } else { - PropertyValueData propertyValueData = eitherStatus.left().value(); - - ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, propertyValue); - - log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); - - Either findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(propertyValue.getPath(), propertyValueData.getUniqueId(), propertyValue.getDefaultValue()); - if (findDefaultValue.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())); - - } - String defaultValue = findDefaultValue.left().value(); - propertyValueResult.setDefaultValue(defaultValue); - log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); - - propertyValueResult.setComponentInstanceId(compInstId); - propertyList.add(propertyValueResult); - - - } - - } - } - } - Either deleteNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Input), inputId, InputsData.class); - if (deleteNode.isRight()) { - StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteNode.right().value()); - return Either.right(convertTitanStatusToStorageStatus); - } else { - InputDefinition inputDefinition = this.convertInputDataToInputDefinition(deleteNode.left().value()); - inputDefinition.setInputs(inputsValueList); - inputDefinition.setProperties(propertyList); - inputDefinition.setName(inputName); - return Either.left(inputDefinition); - } - } - - @Override - public Either, TitanOperationStatus> addInputsToGraph(String componentId, NodeTypeEnum nodeType, Map inputs, Map dataTypes) { - - List newInputs = new ArrayList(); - if (inputs != null) { - for (Entry entry : inputs.entrySet()) { - - String inputName = entry.getKey(); - InputDefinition propertyDefinition = entry.getValue(); - - StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(propertyDefinition, dataTypes); - if (validateAndUpdateProperty != StorageOperationStatus.OK) { - log.error("Property {} is invalid. Status is {}", propertyDefinition, validateAndUpdateProperty); - return Either.right(TitanOperationStatus.INVALID_PROPERTY); - } - - Either addPropertyToGraph = addInputToGraph(inputName, propertyDefinition, componentId, nodeType); - - if (addPropertyToGraph.isRight()) { - return Either.right(addPropertyToGraph.right().value()); - } - InputDefinition createdInputyDefinition = convertInputDataToInputDefinition(addPropertyToGraph.left().value()); - createdInputyDefinition.setName(inputName); - createdInputyDefinition.setParentUniqueId(componentId); - newInputs.add(createdInputyDefinition); - } - } - - return Either.left(newInputs); - } - - @Override - public TitanOperationStatus addInputsToGraph(TitanVertex metadata, String componentId, Map inputs, Map dataTypes) { - - if (inputs != null) { - for (Entry entry : inputs.entrySet()) { - - String inputName = entry.getKey(); - InputDefinition propertyDefinition = entry.getValue(); - - StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(propertyDefinition, dataTypes); - if (validateAndUpdateProperty != StorageOperationStatus.OK) { - log.error("Property {} is invalid. Status is {} ", propertyDefinition, validateAndUpdateProperty); - return TitanOperationStatus.INVALID_PROPERTY; - } - - TitanOperationStatus addPropertyToGraph = addInputToGraph(metadata, inputName, propertyDefinition, componentId); - - if (!addPropertyToGraph.equals(TitanOperationStatus.OK)) { - return addPropertyToGraph; - } - - } - } - - return TitanOperationStatus.OK; - } - - @Override - public Either, StorageOperationStatus> getInputsOfComponent(String compId, String fromName, int amount) { - List inputs = new ArrayList<>(); - if ((fromName == null || fromName.isEmpty()) && amount == 0) { - - TitanOperationStatus status = findAllResourceInputs(compId, inputs); - - if (status != TitanOperationStatus.OK) { - log.error("Failed to set inputs of resource {}. status is {}", compId, status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - } else { - - Either graphRes = titanGenericDao.getGraph(); - if (graphRes.isRight()) { - log.error("Failed to retrieve graph. status is {}", graphRes); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphRes.right().value())); - } - - TitanGraph titanGraph = graphRes.left().value(); - @SuppressWarnings("unchecked") - Iterable vertices = titanGraph.query().has(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), compId).vertices(); - if (vertices == null || false == vertices.iterator().hasNext()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.INVALID_ID)); - } - - TitanVertex rootVertex = vertices.iterator().next(); - TitanVertexQuery query; - if (fromName == null || fromName.isEmpty()) - query = rootVertex.query().direction(Direction.OUT).labels(GraphEdgeLabels.INPUT.getProperty()).orderBy(GraphEdgePropertiesDictionary.NAME.getProperty(), Order.incr).limit(amount); - else - query = rootVertex.query().direction(Direction.OUT).labels(GraphEdgeLabels.INPUT.getProperty()).orderBy(GraphEdgePropertiesDictionary.NAME.getProperty(), Order.incr).has(GraphEdgePropertiesDictionary.NAME.getProperty(), Cmp.GREATER_THAN, fromName).limit(amount); - - Iterable edgesCreatorEges = query.edges(); - - if (edgesCreatorEges == null) { - log.debug("No edges in graph for criteria"); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND)); - } - Iterator edgesCreatorIterator = edgesCreatorEges.iterator(); - - if (edgesCreatorIterator != null) { - while (edgesCreatorIterator.hasNext()) { - Edge edge = edgesCreatorIterator.next(); - GraphEdge graphEdge = null; - - Map edgeProps = titanGenericDao.getProperties(edge); - GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label()); - graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps); - - Vertex outgoingVertex = edge.inVertex(); - Map properties = titanGenericDao.getProperties(outgoingVertex); - InputsData data = GraphElementFactory.createElement(NodeTypeEnum.Input.getName(), GraphElementTypeEnum.Node, properties, InputsData.class); - String inputName = (String) graphEdge.getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty()); - InputDefinition inputDefinition = this.convertInputDataToInputDefinition(data); - inputDefinition.setName(inputName); - inputDefinition.setParentUniqueId(compId); - - inputs.add(inputDefinition); - - } - } - - } - if (true == inputs.isEmpty()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND)); - } - - return Either.left(inputs); - - } - - @Override - public Either, StorageOperationStatus> deleteAllInputsAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) { - - Wrapper errorWrapper; - List inputs = new ArrayList<>(); - TitanOperationStatus findAllResourceAttribues = this.findNodeNonInheretedInputs(uniqueId, inputs); - errorWrapper = (findAllResourceAttribues != TitanOperationStatus.OK) ? new Wrapper<>(findAllResourceAttribues) : new Wrapper<>(); - - if (errorWrapper.isEmpty()) { - for (InputDefinition inDef : inputs) { - log.debug("Before deleting inputs from graph {}", inDef.getUniqueId()); - Either deleteNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Input), inDef.getUniqueId(), InputsData.class); - if (deleteNode.isRight()) { - errorWrapper.setInnerElement(deleteNode.right().value()); - break; - } - } - } - - if (errorWrapper.isEmpty()) { - Map inputsMap = inputs.stream().collect(Collectors.toMap(e -> e.getName(), e -> e)); - return Either.left(inputsMap); - } else { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(errorWrapper.getInnerElement())); - } - - } - - @Override - public Either addInput(String inputName, InputDefinition inputDefinition, String resourceId, NodeTypeEnum nodeType) { - - ComponentMetadataData componentMetadata = null; - - Either either = addInputToGraph(inputName, inputDefinition, resourceId, nodeType); - if (either.isRight()) { - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value()); - return Either.right(storageStatus); - } - return Either.left(either.left().value()); - } - - @Override - public Either updateInput(String inputId, InputDefinition newInDef, Map dataTypes) { - // TODO Auto-generated method stub - return null; - } - - public Either addInputToGraph(String propertyName, InputDefinition inputDefinition, String componentId, NodeTypeEnum nodeType) { - - UniqueIdData from = new UniqueIdData(nodeType, componentId); - - List constraints = inputDefinition.getConstraints(); - - inputDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, propertyName)); - InputsData inputData = new InputsData(inputDefinition, convertConstraintsToString(constraints)); - - log.debug("Before adding property to graph {}", inputData); - Either createNodeResult = titanGenericDao.createNode(inputData, InputsData.class); - log.debug("After adding input to graph {}", inputData); - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add input {} to graph. status is {}", propertyName, operationStatus); - if(operationStatus == TitanOperationStatus.TITAN_SCHEMA_VIOLATION ) - return Either.right(TitanOperationStatus.ALREADY_EXIST); - return Either.right(operationStatus); - } - - Map props = new HashMap(); - props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), propertyName); - - Either createRelResult = titanGenericDao.createRelation(from, inputData, GraphEdgeLabels.INPUT, props); - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to associate resource {} to property {} in graph. status is {}", componentId, propertyName, operationStatus); - return Either.right(operationStatus); - } - - return Either.left(createNodeResult.left().value()); - - } - - public TitanOperationStatus addInputToGraph(TitanVertex vertex, String propertyName, InputDefinition inputDefinition, String componentId) { - - List constraints = inputDefinition.getConstraints(); - - inputDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, propertyName)); - InputsData inputData = new InputsData(inputDefinition, convertConstraintsToString(constraints)); - - log.debug("Before adding property to graph {}", inputData); - Either createNodeResult = titanGenericDao.createNode(inputData); - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add input {} to graph. status is {}", propertyName, operationStatus); - return operationStatus; - } - - Map props = new HashMap(); - props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), propertyName); - TitanVertex inputVertex = createNodeResult.left().value(); - TitanOperationStatus createRelResult = titanGenericDao.createEdge(vertex, inputVertex, GraphEdgeLabels.INPUT, props); - if (!createRelResult.equals(TitanOperationStatus.OK)) { - TitanOperationStatus operationStatus = createRelResult; - log.error("Failed to associate resource {} to property {} in graph. status is {}", componentId, propertyName, operationStatus); - return operationStatus; - } - - return createRelResult; - - } - - public InputDefinition convertInputDataToInputDefinition(InputsData inputDataResult) { - if (log.isDebugEnabled()) - log.debug("The object returned after create property is {}", inputDataResult); - - InputDefinition propertyDefResult = new InputDefinition(inputDataResult.getPropertyDataDefinition()); - propertyDefResult.setConstraints(convertConstraints(inputDataResult.getConstraints())); - - return propertyDefResult; - } - - public boolean isInputExist(List inputs, String resourceUid, String inputName) { - - if (inputs == null) { - return false; - } - - for (InputDefinition propertyDefinition : inputs) { - String parentUniqueId = propertyDefinition.getParentUniqueId(); - String name = propertyDefinition.getName(); - - if (parentUniqueId.equals(resourceUid) && name.equals(inputName)) { - return true; - } - } - - return false; - - } - - @Override - public TitanOperationStatus findAllResourceInputs(String uniqueId, List inputs) { - // final NodeElementFetcher singleNodeFetcher = - // (resourceIdParam, attributesParam) -> - // findNodeNonInheretedInputs(resourceIdParam, componentType, - // attributesParam); - // return findAllResourceElementsDefinitionRecursively(uniqueId, inputs, - // singleNodeFetcher); - return findNodeNonInheretedInputs(uniqueId, inputs); - } - - @Override - public TitanOperationStatus findNodeNonInheretedInputs(String uniqueId, List inputs) { - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.INPUT, NodeTypeEnum.Input, InputsData.class); - - if (childrenNodes.isRight()) { - TitanOperationStatus status = childrenNodes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - return status; - } - - List> values = childrenNodes.left().value(); - if (values != null) { - - for (ImmutablePair immutablePair : values) { - GraphEdge edge = immutablePair.getValue(); - String inputName = (String) edge.getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty()); - log.debug("Input {} is associated to node {}", inputName, uniqueId); - InputsData inputData = immutablePair.getKey(); - InputDefinition inputDefinition = this.convertInputDataToInputDefinition(inputData); - - inputDefinition.setName(inputName); - inputDefinition.setParentUniqueId(uniqueId); - - inputs.add(inputDefinition); - - log.trace("findInputsOfNode - input {} associated to node {}", inputDefinition, uniqueId); - } - - } - - return TitanOperationStatus.OK; - } - - public Either getInputById(String uniqueId, boolean skipProperties, boolean skipInputsvalue) { - Either status = getInputFromGraph(uniqueId, skipProperties, skipInputsvalue); - - if (status.isRight()) { - log.error("Failed to get input {} from graph {}. status is {}", uniqueId, status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value())); - } - - return Either.left(status.left().value()); - - } public TitanOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List elements, NodeElementFetcher singleNodeFetcher) { @@ -580,229 +130,8 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati return TitanOperationStatus.OK; } - public TitanOperationStatus associatePropertyToInput(String riId, String inputId, InputValueData property, String name) { - TitanOperationStatus status = TitanOperationStatus.OK; - Either graphRes = titanGenericDao.getGraph(); - if (graphRes.isRight()) { - log.error("Failed to retrieve graph. status is {}", graphRes); - return graphRes.right().value(); - } - - TitanGraph titanGraph = graphRes.left().value(); - @SuppressWarnings("unchecked") - Iterable vertices = titanGraph.query().has(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), property.getUniqueId()).vertices(); - if (vertices == null || false == vertices.iterator().hasNext()) { - return TitanOperationStatus.INVALID_ID; - } - // Either findPropertyDefRes = - // titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), - // propertyId, PropertyData.class); - - Map props = new HashMap(); - props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), name); - props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), riId); - - GraphNode inputData = new UniqueIdData(NodeTypeEnum.Input, inputId); - GraphNode propertyData = new UniqueIdData(NodeTypeEnum.InputValue, property.getUniqueId()); - Either addPropRefResult = titanGenericDao.createRelation(inputData, propertyData, GraphEdgeLabels.GET_INPUT, props); - - if (addPropRefResult.isRight()) { - status = addPropRefResult.right().value(); - String description = "Failed to associate input " + inputData.getUniqueId() + " to property " + property.getUniqueId() + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ASSOCIATING_INPUT_TO_PROP, description, ErrorSeverity.ERROR); - return status; - } - return status; - - } - - public TitanOperationStatus associatePropertyToInput(String riId, String inputId, ComponentInstanceProperty property, GetInputValueDataDefinition getInput) { - TitanOperationStatus status = TitanOperationStatus.OK; - Either graphRes = titanGenericDao.getGraph(); - if (graphRes.isRight()) { - log.error("Failed to retrieve graph. status is {}", graphRes); - return graphRes.right().value(); - } - - TitanGraph titanGraph = graphRes.left().value(); - @SuppressWarnings("unchecked") - Iterable vertices = titanGraph.query().has(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), property.getUniqueId()).vertices(); - if (vertices == null || false == vertices.iterator().hasNext()) { - return TitanOperationStatus.INVALID_ID; - } - // Either findPropertyDefRes = - // titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), - // propertyId, PropertyData.class); - - Map props = new HashMap(); - if(getInput!=null){ - props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), getInput.getPropName()); - if (getInput.isList()) { - String index = ""; - if(getInput.getIndexValue()!= null ){ - index = getInput.getIndexValue().toString(); - }else{ - if (getInput.getGetInputIndex() != null) { - index = getInput.getGetInputIndex().getInputName(); - - } - } - props.put(GraphEdgePropertiesDictionary.GET_INPUT_INDEX.getProperty(), index); - } - } - props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), riId); - - GraphNode inputData = new UniqueIdData(NodeTypeEnum.Input, inputId); - GraphNode propertyData = new UniqueIdData(NodeTypeEnum.PropertyValue, property.getValueUniqueUid()); - Either addPropRefResult = titanGenericDao.createRelation(inputData, propertyData, GraphEdgeLabels.GET_INPUT, props); - - if (addPropRefResult.isRight()) { - status = addPropRefResult.right().value(); - String description = "Failed to associate input " + inputData.getUniqueId() + " to property " + property.getUniqueId() + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ASSOCIATING_INPUT_TO_PROP, description, ErrorSeverity.ERROR); - return status; - } - return status; - - } - - private Either getInputFromGraph(String uniqueId, boolean skipProperties, boolean skipInputsValue) { - - Either result = null; - - Either inputRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Input), uniqueId, InputsData.class); - if (inputRes.isRight()) { - TitanOperationStatus status = inputRes.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; - } - - InputsData inputData = inputRes.left().value(); - - InputDefinition groupDefinition = this.convertInputDataToInputDefinition(inputData); - - if (false == skipInputsValue) { - List propsList = new ArrayList(); - - Either>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Input), uniqueId, GraphEdgeLabels.GET_INPUT, NodeTypeEnum.InputValue, InputValueData.class); - - if (propertyImplNodes.isRight()) { - TitanOperationStatus status = propertyImplNodes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - return Either.right(status); - } - - } - if(propertyImplNodes.isLeft()){ - List> propertyDataPairList = propertyImplNodes.left().value(); - for (ImmutablePair propertyValue : propertyDataPairList) { - - InputValueData propertyValueData = propertyValue.getLeft(); - String propertyValueUid = propertyValueData.getUniqueId(); - String value = propertyValueData.getValue(); - - Either, 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 propertyDefPair = propertyDefRes.left().value(); - String propertyUniqueId = (String) propertyDefPair.left.getUniqueId(); - - ComponentInstanceInput resourceInstanceProperty = new ComponentInstanceInput(); - // set property original unique id - resourceInstanceProperty.setUniqueId(propertyUniqueId); - // set resource id - // TODO: esofer add resource id - resourceInstanceProperty.setParentUniqueId(null); - // set value - resourceInstanceProperty.setValue(value); - // set property value unique id - resourceInstanceProperty.setValueUniqueUid(propertyValueUid); - // set rules - // resourceInstanceProperty.setRules(propertyValueData.getRules()); - - propsList.add(resourceInstanceProperty); - - } - - groupDefinition.setInputs(propsList); - } - - } - - if (false == skipProperties) { - Either>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.GET_INPUT, NodeTypeEnum.PropertyValue, PropertyValueData.class); - - if (propertyImplNodes.isRight()) { - TitanOperationStatus status = propertyImplNodes.right().value(); - return Either.right(status); - } - - List> list = propertyImplNodes.left().value(); - - if (list == null || true == list.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - List propsRresult = new ArrayList<>(); - for (ImmutablePair propertyValueDataPair : list) { - PropertyValueData propertyValueData = propertyValueDataPair.left; - String propertyValueUid = propertyValueData.getUniqueId(); - String value = propertyValueData.getValue(); - - Either, 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); - } - - } - if(propertyDefRes.isLeft()){ - - ImmutablePair propertyDefPair = propertyDefRes.left().value(); - PropertyData propertyData = propertyDefPair.left; - String propertyUniqueId = (String) propertyData.getPropertyDataDefinition().getUniqueId(); - - ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty(); - // set property original unique id - resourceInstanceProperty.setUniqueId(propertyUniqueId); - // set resource id - // TODO: esofer add resource id - resourceInstanceProperty.setParentUniqueId(null); - // 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.setName((String) propertyValueDataPair.right.getProperties().get(GraphPropertiesDictionary.NAME.getProperty())); - - propsRresult.add(resourceInstanceProperty); - } - - groupDefinition.setProperties(propsRresult); - } - - } - - result = Either.left(groupDefinition); - - return result; - - } + @Override public ImmutablePair findInputValue(String resourceInstanceId, String propertyId) { log.debug("Going to check whether the property {} already added to resource instance {}", propertyId, resourceInstanceId); @@ -842,40 +171,6 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati } - /** - * 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, StorageOperationStatus> getComponentInstanceInputsByInputId(String resourceInstanceUid, String inputId) { - - Either, TitanOperationStatus> status = getComponentInstanceInputsByInputId(inputId); - if (status.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value())); - } - - return Either.left(status.left().value()); - - } - - /** - * 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, StorageOperationStatus> getComponentInstancePropertiesByInputId(String resourceInstanceUid, String inputId) { - - Either, TitanOperationStatus> status = getComponentInstancePropertiesByInputId(inputId); - if (status.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value())); - } - - return Either.left(status.left().value()); - - } - public Either, TitanOperationStatus> getAllInputsOfResourceInstanceOnlyInputDefId(String resourceInstanceUid, NodeTypeEnum instanceNodeType) { Either findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, ComponentInstanceData.class); @@ -967,231 +262,7 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati return Either.left(result); } - public Either, TitanOperationStatus> getComponentInstanceInputsByInputId(String inputId) { - - Either findResInputRes = titanGenericDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId, InputsData.class); - - if (findResInputRes.isRight()) { - TitanOperationStatus status = findResInputRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); - } - - - - // Either, TitanOperationStatus> propertyImplNodes - // = titanGenericDao.getByCriteria(NodeTypeEnum.InputValue, props, - // InputValueData.class); - Either vertexService = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId); - - if (vertexService.isRight()) { - log.debug("failed to fetch vertex of resource input for id = {}", inputId); - TitanOperationStatus status = vertexService.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - - return Either.right(status); - } - TitanVertex vertex = vertexService.left().value(); - - Either>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId, GraphEdgeLabels.GET_INPUT, NodeTypeEnum.InputValue, InputValueData.class); - - ////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - if (propertyImplNodes.isRight()) { - TitanOperationStatus status = propertyImplNodes.right().value(); - return Either.right(status); - } - - List> list = propertyImplNodes.left().value(); - - if (list == null || true == list.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - List result = new ArrayList<>(); - for (ImmutablePair propertyValueDataPair : list) { - InputValueData propertyValueData = propertyValueDataPair.left; - String propertyValueUid = propertyValueData.getUniqueId(); - String value = propertyValueData.getValue(); - // Either, TitanOperationStatus> out = - // titanGenericDao.getEdgesForNode(propertyValueData, - // Direction.OUT); - // Either, TitanOperationStatus> in = - // titanGenericDao.getEdgesForNode(propertyValueData, Direction.IN); - Either inputsvalueEges = titanGenericDao.getIncomingEdgeByCriteria(propertyValueData, GraphEdgeLabels.INPUT_VALUE, null); - if (inputsvalueEges.isRight()) { - TitanOperationStatus status = inputsvalueEges.right().value(); - - return Either.right(status); - } - Edge edge = inputsvalueEges.left().value(); - String componentInsName = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.NAME.getProperty()); - String componentInsId = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.OWNER_ID.getProperty()); - - Either, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InputValue), propertyValueUid, GraphEdgeLabels.INPUT_IMPL, NodeTypeEnum.Input, InputsData.class); - - if (propertyDefRes.isRight()) { - TitanOperationStatus status = propertyDefRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); - } - - ImmutablePair propertyDefPair = propertyDefRes.left().value(); - - InputsData propertyData = propertyDefPair.left; - - Either inputsEges = titanGenericDao.getIncomingEdgeByCriteria(propertyData, GraphEdgeLabels.INPUT, null); - if (inputsEges.isRight()) { - TitanOperationStatus status = inputsEges.right().value(); - - return Either.right(status); - } - 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); - // set property original unique id - resourceInstanceProperty.setUniqueId(propertyUniqueId); - resourceInstanceProperty.setName(inputName); - // set resource id - // TODO: esofer add resource id - resourceInstanceProperty.setParentUniqueId(null); - // 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(componentInsId); - - result.add(resourceInstanceProperty); - } - - return Either.left(result); - - } - - public Either, TitanOperationStatus> getComponentInstancePropertiesByInputId(String inputId) { - - Either findResInputRes = titanGenericDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId, InputsData.class); - - if (findResInputRes.isRight()) { - TitanOperationStatus status = findResInputRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); - } - - //Map props = new HashMap(); - //props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), resourceInstanceUid); - - // Either, TitanOperationStatus> - // propertyImplNodes = - // titanGenericDao.getByCriteria(NodeTypeEnum.PropertyValue, props, - // PropertyValueData.class); - Either vertexService = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId); - - if (vertexService.isRight()) { - log.debug("failed to fetch vertex of resource input for id = {}", inputId); - TitanOperationStatus status = vertexService.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - - return Either.right(status); - } - TitanVertex vertex = vertexService.left().value(); - - // Either>, - // TitanOperationStatus> propertyImplNodes = - // titanGenericDao.getChildrenByEdgeCriteria(vertex, inputId, - // GraphEdgeLabels.GET_INPUT, NodeTypeEnum.PropertyValue, - // PropertyValueData.class, props); - Either>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId, GraphEdgeLabels.GET_INPUT, NodeTypeEnum.PropertyValue, PropertyValueData.class); - - if (propertyImplNodes.isRight()) { - TitanOperationStatus status = propertyImplNodes.right().value(); - return Either.right(status); - } - - List> list = propertyImplNodes.left().value(); - - if (list == null || true == list.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - List result = new ArrayList<>(); - for (ImmutablePair propertyValueDataPair : list) { - PropertyValueData propertyValueData = propertyValueDataPair.left; - String propertyValueUid = propertyValueData.getUniqueId(); - String value = propertyValueData.getValue(); - - String componentInstanceId = (String) propertyValueDataPair.right.getProperties().get(GraphEdgePropertiesDictionary.OWNER_ID.getProperty()); - - Either, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class); - if (propertyDefRes.isRight()) { - TitanOperationStatus status = propertyDefRes.right().value(); - return Either.right(status); - } - - ImmutablePair propertyDefPair = propertyDefRes.left().value(); - PropertyData propertyData = propertyDefPair.left; - String propertyUniqueId = (String) propertyData.getPropertyDataDefinition().getUniqueId(); - - Either originVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), propertyUniqueId); - if (originVertexEither.isRight()) { - log.debug("Failed to fetch vertex of property for id {} error {}", propertyUniqueId, originVertexEither.right().value()); - return Either.right(originVertexEither.right().value()); - } - TitanVertex originVertex = originVertexEither.left().value(); - Iterator edgeIter = originVertex.edges(Direction.IN, GraphEdgeLabels.PROPERTY.getProperty()); - if (edgeIter == null) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - String propertyName = ""; - - while (edgeIter.hasNext()) { - TitanEdge edge = (TitanEdge) edgeIter.next(); - propertyName = (String) edge.property(GraphEdgePropertiesDictionary.NAME.getProperty()).value(); - } - - ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty(); - // set property original unique id - resourceInstanceProperty.setUniqueId(propertyUniqueId); - // set resource id - // TODO: esofer add resource id - resourceInstanceProperty.setParentUniqueId(null); - // 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.setName(propertyName); - resourceInstanceProperty.setComponentInstanceId(componentInstanceId); - - - result.add(resourceInstanceProperty); - } - - return Either.left(result); - } - + @Override public ComponentInstanceInput buildResourceInstanceInput(InputValueData propertyValueData, ComponentInstanceInput resourceInstanceInput) { String value = propertyValueData.getValue(); @@ -1202,271 +273,5 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati return instanceProperty; } - public Either, TitanOperationStatus> getAllInputsOfResourceInstance(ComponentInstance compInstance) { - - Either, TitanOperationStatus> result; - - return getAllInputsOfResourceInstanceOnlyInputDefId(compInstance.getUniqueId()); - - } - - - - private Either, StorageOperationStatus> createInputsFromProperty(String resourceId, NodeTypeEnum nodeType, Map dataTypes, List resList, Map> newInputsPropsMap) { - for (Entry> entry : newInputsPropsMap.entrySet()) { - String compInstId = entry.getKey(); - List properties = entry.getValue(); - - Either ciVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), compInstId); - if (ciVertexEither.isRight()) { - log.debug("Failed to fetch vertex of resource instance for id {} error {}", compInstId, ciVertexEither.right().value()); - return Either.right( DaoStatusConverter.convertTitanStatusToStorageStatus(ciVertexEither.right().value())); - } - TitanVertex ciVertex = ciVertexEither.left().value(); - - - //String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty()); - String compInstname = (String) titanGenericDao.getProperty(ciVertex, GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()); - String inputName = compInstname; - - if (properties != null && !properties.isEmpty()) { - for (ComponentInstancePropInput propInput : properties) { - Either createInputRes = createInputForComponentInstance(resourceId, nodeType, dataTypes, compInstId, inputName, propInput); - - if (createInputRes.isRight()) { - log.debug("Failed to create input of resource instance for id {} error {}", compInstId, createInputRes.right().value()); - return Either.right(createInputRes.right().value()); - } - - resList.add(createInputRes.left().value()); - - } - } - - } - return Either.left(resList); - } - - private Either createInputForComponentInstance(String resourceId, NodeTypeEnum nodeType, Map dataTypes, String compInstId, String inputName, ComponentInstancePropInput propInput) { - String propertiesName = propInput.getPropertiesName() ; - PropertyDefinition selectedProp = propInput.getInput(); - String[] parsedPropNames = propInput.getParsedPropNames(); - if(parsedPropNames != null){ - for(String str: parsedPropNames){ - inputName += "_" + str; - } - } else { - inputName += "_" + propInput.getName(); - } - - InputDefinition input = null; - ComponentInstanceProperty prop = propInput; - - if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){ - input = new InputDefinition(selectedProp); - }else{ - input = new InputDefinition(prop); - input.setName(inputName + "_" + prop.getName()); - - } - input.setName(inputName); - - JSONObject jobject = new JSONObject(); - - - if(prop.getValueUniqueUid() == null || prop.getValueUniqueUid().isEmpty()){ - if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){ - - jobject = createJSONValueForProperty(parsedPropNames.length -1, parsedPropNames, jobject, inputName); - prop.setValue(jobject.toJSONString()); - - }else{ - - jobject.put(GET_INPUT, input.getName()); - prop.setValue(jobject.toJSONString()); - - - } - Either increaseCounterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(compInstId, GraphPropertiesDictionary.PROPERTY_COUNTER, true); - if (increaseCounterRes.isRight()) { - log.debug("Failed to increase resource property counter {} to resource instance {}", prop, compInstId); - - return Either.right( increaseCounterRes.right().value()); - } - Integer index = increaseCounterRes.left().value(); - Either result = componentInstanceOperation.addPropertyValueToResourceInstance(prop, compInstId, false, index, true); - if (result.isRight()) { - log.debug("Failed to add property value {} to resource instance {}", prop, compInstId); - return Either.right( result.right().value()); - } - prop = result.left().value(); - - }else{ - - String value = prop.getValue(); - if(value != null){ - Object objValue = new Yaml().load(value); - if( objValue instanceof Map || objValue instanceof List ){ - if(propertiesName == null ||propertiesName.isEmpty()){ - jobject.put(GET_INPUT, input.getName()); - prop.setValue(jobject.toJSONString()); - prop.setRules(null); - - }else{ - Map mappedToscaTemplate = (Map) objValue; - createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName); - Gson gson = new Gson(); - String json = gson.toJson(mappedToscaTemplate); - prop.setValue(json); - prop.setRules(null); - } - - }else{ - jobject.put(GET_INPUT, input.getName()); - prop.setValue(jobject.toJSONString()); - prop.setRules(null); - } - }else{ - jobject.put(GET_INPUT, input.getName()); - prop.setValue(jobject.toJSONString()); - prop.setRules(null); - } - - Either eitherStatus = componentInstanceOperation.updatePropertyOfResourceInstance(prop, compInstId, false); - - if (eitherStatus.isRight()) { - log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", prop, compInstId, eitherStatus.right().value().name()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); - - } else { - PropertyValueData propertyValueData = eitherStatus.left().value(); - - prop = propertyOperation.buildResourceInstanceProperty(propertyValueData, prop); - - log.debug("The returned ResourceInstanceProperty is {}", prop); - - Either findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(prop.getPath(), propertyValueData.getUniqueId(), prop.getDefaultValue()); - if (findDefaultValue.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())); - - } - String defaultValue = findDefaultValue.left().value(); - prop.setDefaultValue(defaultValue); - log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); - - prop.setComponentInstanceId(compInstId); - - - - } - - - } - - StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(input, dataTypes); - if (validateAndUpdateProperty != StorageOperationStatus.OK) { - log.error("Property {} is invalid. Status is {}", input, validateAndUpdateProperty); - return Either.right(validateAndUpdateProperty); - } - - Either addPropertyToGraph = addInputToGraph(input.getName(), input, resourceId, nodeType); - - if (addPropertyToGraph.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyToGraph.right().value())); - } - InputDefinition createdInputyDefinition = convertInputDataToInputDefinition(addPropertyToGraph.left().value()); - createdInputyDefinition.setName(input.getName()); - createdInputyDefinition.setParentUniqueId(resourceId); - - TitanOperationStatus status = associatePropertyToInput(compInstId, createdInputyDefinition.getUniqueId(), prop, null); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to associate input {} tp property value{} ", createdInputyDefinition.getName(), prop.getValueUniqueUid()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - return Either.left(createdInputyDefinition); - - } - - private JSONObject createJSONValueForProperty (int i, String [] parsedPropNames, JSONObject ooj, String inputName){ - - while(i >= 1){ - if( i == parsedPropNames.length -1){ - JSONObject jobProp = new JSONObject(); - jobProp.put(GET_INPUT, inputName); - ooj.put(parsedPropNames[i], jobProp); - i--; - return createJSONValueForProperty (i, parsedPropNames, ooj, inputName); - }else{ - JSONObject res = new JSONObject(); - res.put(parsedPropNames[i], ooj); - i --; - res = createJSONValueForProperty (i, parsedPropNames, res, inputName); - return res; - } - } - - return ooj; - } - - public void resetInputName(Map lhm1, String inputName){ - for (Map.Entry entry : lhm1.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) { - value = ""; - lhm1.remove(key); - } else if (value instanceof Map) { - Map subMap = (Map)value; - resetInputName(subMap, inputName); - } else { - continue; - } - - } - } - - private Map createInputValue(Map lhm1, int index, String[] inputNames, String inputName){ - while(index < inputNames.length){ - if(lhm1.containsKey(inputNames[index])){ - Object value = lhm1.get(inputNames[index]); - if (value instanceof Map){ - if(index == inputNames.length -1){ - ((Map) value).put(GET_INPUT, inputName); - return ((Map) value); - - }else{ - index++; - return createInputValue((Map)value, index, inputNames, inputName); - } - }else{ - Map jobProp = new HashMap<>(); - if(index == inputNames.length -1){ - jobProp.put(GET_INPUT, inputName); - lhm1.put(inputNames[index], jobProp); - return lhm1; - }else{ - lhm1.put(inputNames[index], jobProp); - index++; - return createInputValue(jobProp, index, inputNames, inputName); - } - } - }else{ - Map jobProp = new HashMap<>(); - lhm1.put(inputNames[index], jobProp); - if(index == inputNames.length -1){ - jobProp.put(GET_INPUT, inputName); - return jobProp; - }else{ - index++; - return createInputValue(jobProp, index, inputNames, inputName); - } - } - } - return lhm1; - } - - - } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java index a7c883b14e..1c03d579a0 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 @@ -70,12 +70,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation @javax.annotation.Resource private TitanGenericDao titanGenericDao; - @Override - public Either addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName) { - - return addInterfaceToResource(interf, resourceId, interfaceName, false); - } - @Override public Either addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean inTransaction) { @@ -113,34 +107,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } - private Either addOperationToGraph(InterfaceDefinition interf, String opName, Operation op, TitanVertex interfaceVertex) { - - String interfaceId = (String) titanGenericDao.getProperty(interfaceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - op.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(interfaceId, opName)); - OperationData operationData = new OperationData(op); - - log.debug("Before adding operation to graph {}", operationData); - Either createOpNodeResult = titanGenericDao.createNode(operationData); - - if (createOpNodeResult.isRight()) { - TitanOperationStatus opStatus = createOpNodeResult.right().value(); - log.error("Failed to add operation {} to graph. status is {}", opName, opStatus); - return Either.right(opStatus); - } - - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), opName); - TitanVertex operationVertex = createOpNodeResult.left().value(); - TitanOperationStatus createRelResult = titanGenericDao.createEdge(interfaceVertex, operationVertex, GraphEdgeLabels.INTERFACE_OPERATION, props); - - if (!createRelResult.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate operation {} to property {} in graph. status is {}", interfaceId, opName, createRelResult); - - return Either.right(createRelResult); - } - return Either.left(operationVertex); - } - private InterfaceDefinition convertInterfaceDataToInterfaceDefinition(InterfaceData interfaceData) { log.debug("The object returned after create interface is {}", interfaceData); @@ -183,25 +149,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } } - private Either addInterfaceToGraph(InterfaceDefinition interfaceInfo, String interfaceName, String resourceId, TitanVertex metadataVertex) { - - InterfaceData interfaceData = new InterfaceData(interfaceInfo); - - String interfaceNameSplitted = getShortInterfaceName(interfaceInfo); - - interfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted)); - - Either existInterface = titanGenericDao.getVertexByProperty(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId()); - - if (existInterface.isRight()) { - - return createInterfaceNodeAndRelation(interfaceNameSplitted, resourceId, interfaceData, metadataVertex); - } else { - log.debug("Interface {} already exist", interfaceData.getUniqueId()); - return Either.right(TitanOperationStatus.ALREADY_EXIST); - } - } - private Either createInterfaceNodeAndRelation(String interfaceName, String resourceId, InterfaceData interfaceData, ResourceMetadataData resourceData) { log.debug("Before adding interface to graph {}", interfaceData); Either createNodeResult = titanGenericDao.createNode(interfaceData, InterfaceData.class); @@ -803,70 +750,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } - @Override - public StorageOperationStatus createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction, TitanVertex metadataVertex) { - - Either interfaceResult = addInterfaceToGraph(interf, interfaceName, resourceId, metadataVertex); - - if (interfaceResult.isRight()) { - if (false == inTransaction) { - titanGenericDao.rollback(); - } - log.error("Failed to add interface {} to resource {}", interfaceName, resourceId); - return DaoStatusConverter.convertTitanStatusToStorageStatus(interfaceResult.right().value()); - } else { - - if (false == inTransaction) { - titanGenericDao.commit(); - } - TitanVertex interfaceVertex = interfaceResult.left().value(); - - // InterfaceDefinition interfaceDefResult = - // convertInterfaceDataToInterfaceDefinition(interfaceData); - Map operations = interf.getOperationsMap(); - if (operations != null && !operations.isEmpty()) { - Set opNames = operations.keySet(); - for (String operationName : opNames) { - - Operation op = operations.get(operationName); - Either operationResult = addOperationToGraph(interf, operationName, op, interfaceVertex); - if (operationResult.isRight()) { - if (false == inTransaction) { - titanGenericDao.rollback(); - } - log.error("Failed to add operation {} to interface {}", operationName, interfaceName); - return DaoStatusConverter.convertTitanStatusToStorageStatus(operationResult.right().value()); - } else { - if (false == inTransaction) { - titanGenericDao.commit(); - } - TitanVertex operationVertex = operationResult.left().value(); - - ArtifactDefinition art = op.getImplementationArtifact(); - if (art != null) { - String opId = (String) titanGenericDao.getProperty(operationVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - StorageOperationStatus artRes = artifactOperation.addArifactToComponent(art, opId, NodeTypeEnum.InterfaceOperation, failIfExist, operationVertex); - if (!artRes.equals(StorageOperationStatus.OK)) { - if (false == inTransaction) { - titanGenericDao.rollback(); - } - log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); - return artRes; - } - } - } - } - } - return StorageOperationStatus.OK; - } - - } - - @Override - public Either deleteInterfaceOperation(String resourceId, String interfaceName, String operationId) { - return deleteInterfaceOperation(resourceId, interfaceName, operationId, false); - } - @Override public Either deleteInterfaceOperation(String resourceId, String interfaceName, String operationId, boolean inTransaction) { @@ -889,29 +772,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } - @Override - public Either deleteInterfaceOfResourceOnGraph(String resourceId, InterfaceDefinition interfaceDef, boolean inTransaction) { - - Map operations = interfaceDef.getOperationsMap(); - String interfaceNameSplitted = getShortInterfaceName(interfaceDef); - if (operations != null) { - for (Entry entry : operations.entrySet()) { - - Operation op = entry.getValue(); - Either removeOperationFromResource = deleteInterfaceOperation(resourceId, interfaceNameSplitted, op.getUniqueId(), true); - if (removeOperationFromResource.isRight()) { - if (false == inTransaction) { - titanGenericDao.rollback(); - } - log.error("Failed to delete operation {} of interface {} resource {}", op.getUniqueId(), interfaceDef.getType(), resourceId); - return Either.right(removeOperationFromResource.right().value()); - } - } - } - return Either.left(interfaceDef); - - } - private Either removeOperationOnGraph(String resourceId, String interfaceName, String operationId) { log.debug("Before deleting operation from graph {}", operationId); @@ -1091,27 +951,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } } - @Override - public StorageOperationStatus associateInterfaceToNode(GraphNode node, InterfaceDefinition interfaceDefinition, TitanVertex metadataVertex) { - - Either interfaceData = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDefinition.getUniqueId()); - if (interfaceData.isRight()) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(interfaceData.right().value()); - } - - Map properties = new HashMap(); - - String interfaceName = getShortInterfaceName(interfaceDefinition); - - properties.put(GraphPropertiesDictionary.NAME.getProperty(), interfaceName.toLowerCase()); - TitanOperationStatus createRelation = titanGenericDao.createEdge(metadataVertex, interfaceData.left().value(), GraphEdgeLabels.INTERFACE, properties); - if (!createRelation.equals(TitanOperationStatus.OK)) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation); - } - - return StorageOperationStatus.OK; - } - public String getShortInterfaceName(InterfaceDataDefinition interfaceDefinition) { String[] packageName = interfaceDefinition.getType().split("\\."); String interfaceName; @@ -1130,41 +969,4 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation return createInterfaceType(interf, false); } - @Override - public Either getSpecificOperation(String resourceId, String interfaceType, String operationName) { - log.trace("Getting operation, resourceId {}, interfaceType {}, operationName {}", resourceId, interfaceType, operationName); - Either, StorageOperationStatus> allInterfacesOfResource = getAllInterfacesOfResource(resourceId, false); - if (allInterfacesOfResource.isRight() || allInterfacesOfResource.left().value() == null || allInterfacesOfResource.left().value().get(interfaceType) == null) { - log.debug("Couldn't find interface definition of type {} for resource id {}", interfaceType, resourceId); - return Either.right(allInterfacesOfResource.right().value()); - } - InterfaceDefinition interfaceDefinition = allInterfacesOfResource.left().value().get(interfaceType); - Map operations = interfaceDefinition.getOperationsMap(); - if (operations == null || operations.get(operationName) == null) { - log.debug("Couldn't find operation for operation name {}, interface type {}", operationName, interfaceType); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - return Either.left(operations.get(operationName)); - } - - @Override - public Either dissociateInterfaceFromNode(GraphNode node, InterfaceDefinition interfaceDefinition) { - - Either interfaceData = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDefinition.getUniqueId(), InterfaceData.class); - if (interfaceData.isRight()) { - log.debug("Couldn't find interface {}", interfaceDefinition); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(interfaceData.right().value())); - } - - InterfaceData value = interfaceData.left().value(); - Either deleteRelation = titanGenericDao.deleteRelation(node, value, GraphEdgeLabels.INTERFACE); - if (deleteRelation.isRight()) { - TitanOperationStatus status = deleteRelation.right().value(); - log.debug("Couldn't dissociate interface between node {} to node {}. Status is {}", node.getUniqueId(), value.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - return Either.left(interfaceDefinition); - } - } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java deleted file mode 100644 index 2537891bbd..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java +++ /dev/null @@ -1,1077 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; -import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint; -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.components.ComponentMetadataDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DistributionStatusEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.resources.data.ComponentMetadataData; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import org.openecomp.sdc.be.resources.data.ServiceMetadataData; -import org.openecomp.sdc.be.resources.data.UniqueIdData; -import org.openecomp.sdc.be.resources.data.UserData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import fj.data.Either; - -@org.springframework.stereotype.Component("lifecycle-operation") -public class LifecycleOperation implements ILifecycleOperation { - - public static final String VERSION_DELIMETER = "."; - public static final String VERSION_DELIMETER_REGEXP = "\\."; - - public LifecycleOperation() { - super(); - } - - private static Logger log = LoggerFactory.getLogger(LifecycleOperation.class.getName()); - - @javax.annotation.Resource - private ResourceOperation resourceOperation; - - @javax.annotation.Resource - private ServiceOperation serviceOperation; - - @javax.annotation.Resource - private ProductOperation productOperation; - - @javax.annotation.Resource - private TitanGenericDao titanGenericDao; - - public ResourceOperation getResourceOperation() { - return resourceOperation; - } - - public void setResourceOperation(ResourceOperation resourceOperation) { - this.resourceOperation = resourceOperation; - } - - public ServiceOperation getServiceOperation() { - return serviceOperation; - } - - public ComponentOperation getComponentOperation(NodeTypeEnum componentType) { - if (NodeTypeEnum.Service.equals(componentType)) { - return serviceOperation; - } else if (NodeTypeEnum.Resource.equals(componentType)) { - return resourceOperation; - } else if (NodeTypeEnum.Product.equals(componentType)) { - return productOperation; - } - return null; - } - - public void setServiceOperation(ServiceOperation serviceOperation) { - this.serviceOperation = serviceOperation; - } - - public TitanGenericDao getTitanGenericDao() { - return titanGenericDao; - } - - public void setTitanGenericDao(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; - } - - @Override - public Either getComponentOwner(String resourceId, NodeTypeEnum nodeType, boolean inTransaction) { - - Either result = Either.right(StorageOperationStatus.GENERAL_ERROR); - try { - - Either, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.STATE, NodeTypeEnum.User, UserData.class); - - if (parentNode.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentNode.right().value())); - } - - ImmutablePair value = parentNode.left().value(); - - User owner = new User(value.left); - result = Either.left(owner); - - } finally { - if (false == inTransaction) { - titanGenericDao.commit(); - } - } - return result; - } - - @Override - public Either checkoutComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction) { - Either result = null; - - try { - // update old component - if (!component.getLifecycleState().equals(LifecycleStateEnum.CERTIFIED)) { - component.setHighestVersion(false); - ComponentOperation componentOperation = getComponentOperation(nodeType); - Either updateComponent = componentOperation.updateComponent(component, inTransaction, titanGenericDao, component.getClass(), nodeType); - if (updateComponent.isRight()) { - StorageOperationStatus error = updateComponent.right().value(); - log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, error); - return Either.right(error); - } - - StorageOperationStatus changeStateToLastState = changeStateRelation(nodeType, component.getUniqueId(), currentOwner, GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE); - if (!changeStateToLastState.equals(StorageOperationStatus.OK)) { - result = Either.right(changeStateToLastState); - return result; - } - } - - // clone the component - result = cloneComponentForCheckout(component, nodeType, modifier); - if (result.isRight()) { - log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, result.right().value()); - 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; - } - - private Either cloneComponentForCertified(Component component, User modifier, Integer majorVersion) { - - // set new version - String certifiedVersion = (majorVersion + 1) + VERSION_DELIMETER + "0"; - component.setVersion(certifiedVersion); - component.setLifecycleState(LifecycleStateEnum.CERTIFIED); - component.setLastUpdateDate(null); - component.setLastUpdaterUserId(modifier.getUserId()); - component.setHighestVersion(true); - - ComponentOperation componentOperation = getComponentOperation(component.getComponentType().getNodeType()); - Either cloneComponentResult = componentOperation.cloneComponent(component, certifiedVersion, LifecycleStateEnum.CERTIFIED, true); - - return cloneComponentResult; - } - - @Override - public Either undoCheckout(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction) { - Either result = null; - ComponentOperation componentOperation = getComponentOperation(nodeType); - - // this is in case prevVersion is 0.0 - returning OOTB component - Component prevComponent = componentOperation.getDefaultComponent(); - try { - // find previous version - String[] versionParts = component.getVersion().split(VERSION_DELIMETER_REGEXP); - Integer minorVersion = Integer.parseInt(versionParts[1]) - 1; - String previousVersion = versionParts[0] + VERSION_DELIMETER + minorVersion; - - if (!previousVersion.equals("0.0")) { - Either updateOldResourceResult = updateOldComponentBeforeUndoCheckout(componentOperation, prevComponent, component, previousVersion, nodeType, true); - if (updateOldResourceResult.isRight()) { - result = updateOldResourceResult; - return result; - } - prevComponent = updateOldResourceResult.left().value(); - } - - // delete the component - Either deleteResourceResult = componentOperation.deleteComponent(component.getUniqueId(), true); - if (deleteResourceResult.isRight()) { - result = deleteResourceResult; - return result; - } - - // return the deleted resource - result = Either.left(prevComponent); - - 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 checkinComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction) { - Either result = null; - try { - StorageOperationStatus updateCheckinInGraph = updateCheckinInGraph(nodeType, component.getUniqueId(), component.getLifecycleState(), modifier, owner); - if (!updateCheckinInGraph.equals(StorageOperationStatus.OK)) { - log.error("failed to update state of resource {}. status={}", component.getUniqueId(), updateCheckinInGraph); - return Either.right(updateCheckinInGraph); - } - LifecycleStateEnum state = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN; - ComponentParametersView componentParametersView = buildFilterForFetchComponentAfterChangeState(); - result = updateComponentMD(component, modifier, state, nodeType, componentParametersView); - if (result.isRight()) { - log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), state, result.right().value()); - } - 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 ComponentParametersView buildFilterForFetchComponentAfterChangeState() { - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreUsers(false); - // Used when we running multiple change states and want to use the - // result from another change - // state(LifecycleOperationTest.certificationStatusChange) - componentParametersView.setIgnoreCategories(false); - return componentParametersView; - } - - private StorageOperationStatus updateCheckinInGraph(NodeTypeEnum componentType, String componentId, LifecycleStateEnum state, User modifier, User owner) { - - // check if we cancel rfc - if (state.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) { - - // remove last checkin - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - UniqueIdData resourceData = new UniqueIdData(componentType, componentId); - Either deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props); - if (deleteResult.isRight()) { - log.debug("failed to update last state relation"); - return StorageOperationStatus.INCONSISTENCY; - } - } - - // remove CHECKOUT relation - StorageOperationStatus removeUserToResourceRelation = removeUserToResourceRelation(componentType, owner.getUserId(), componentId, GraphEdgeLabels.STATE); - if (!removeUserToResourceRelation.equals(StorageOperationStatus.OK)) { - return removeUserToResourceRelation; - } - - // create CHECKIN relation - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - StorageOperationStatus createUserToResourceRelation = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props); - if (!createUserToResourceRelation.equals(StorageOperationStatus.OK)) { - return createUserToResourceRelation; - } - - return StorageOperationStatus.OK; - } - - @Override - public Either requestCertificationComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction) { - Either result = null; - try { - StorageOperationStatus updateRfcOnGraph = updateRfcOnGraph(nodeType, component.getUniqueId(), component.getLifecycleState(), modifier, owner); - if (!updateRfcOnGraph.equals(StorageOperationStatus.OK)) { - log.error("failed to update state of resource {}. status={}", component.getUniqueId(), updateRfcOnGraph); - return Either.right(updateRfcOnGraph); - } - - LifecycleStateEnum state = LifecycleStateEnum.READY_FOR_CERTIFICATION; - - ComponentParametersView componentParametersView = buildFilterForFetchComponentAfterChangeState(); - - result = updateComponentMD(component, modifier, state, nodeType, componentParametersView); - if (result.isRight()) { - log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), state, result.right().value()); - return result; - } - 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 StorageOperationStatus updateRfcOnGraph(NodeTypeEnum componentType, String componentId, LifecycleStateEnum state, User modifier, User owner) { - - if (state.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - // if this is atomic checkin + RFC: create checkin relation - - // remove CHECKOUT relation - StorageOperationStatus relationStatus = removeUserToResourceRelation(componentType, owner.getUserId(), componentId, GraphEdgeLabels.STATE); - if (!relationStatus.equals(StorageOperationStatus.OK)) { - return relationStatus; - } - - // create CHECKIN relation - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - relationStatus = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.LAST_STATE, props); - if (!relationStatus.equals(StorageOperationStatus.OK)) { - return relationStatus; - } - } else { - StorageOperationStatus changeStatus = changeRelationLabel(componentType, componentId, owner, GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE); - if (!changeStatus.equals(StorageOperationStatus.OK)) { - return changeStatus; - } - } - - // create RFC relation - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - StorageOperationStatus changeRelationLabel = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props); - if (!changeRelationLabel.equals(StorageOperationStatus.OK)) { - return changeRelationLabel; - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus changeRelationLabel(NodeTypeEnum componentType, String componentId, User owner, GraphEdgeLabels prevLabel, GraphEdgeLabels toLabel) { - UniqueIdData resourceV = new UniqueIdData(componentType, componentId); - UserData userV = new UserData(); - userV.setUserId(owner.getUserId()); - Either replaceRelationLabelResult = titanGenericDao.replaceRelationLabel(userV, resourceV, prevLabel, toLabel); - if (replaceRelationLabelResult.isRight()) { - log.error("failed to replace label from last state to state"); - return DaoStatusConverter.convertTitanStatusToStorageStatus(replaceRelationLabelResult.right().value()); - } - return StorageOperationStatus.OK; - } - - @Override - public Either startComponentCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction) { - Either result = null; - try { - StorageOperationStatus updateOnGraph = updateStartCertificationOnGraph(nodeType, component.getUniqueId(), modifier, owner); - if (!updateOnGraph.equals(StorageOperationStatus.OK)) { - log.error("failed to update state of resource {}. status={}", component.getUniqueId(), updateOnGraph); - return Either.right(updateOnGraph); - } - - LifecycleStateEnum state = LifecycleStateEnum.CERTIFICATION_IN_PROGRESS; - ComponentParametersView componentParametersView = buildFilterForFetchComponentAfterChangeState(); - - result = updateComponentMD(component, modifier, state, nodeType, componentParametersView); - if (result.isRight()) { - log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), state, result.right().value()); - } - 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 StorageOperationStatus updateStartCertificationOnGraph(NodeTypeEnum componentType, String componentId, User modifier, User owner) { - StorageOperationStatus changeRelationLabel = changeRelationLabel(componentType, componentId, owner, GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE); - if (!changeRelationLabel.equals(StorageOperationStatus.OK)) { - return changeRelationLabel; - } - - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - - StorageOperationStatus createUserToResourceRelation = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props); - if (!createUserToResourceRelation.equals(StorageOperationStatus.OK)) { - return createUserToResourceRelation; - } - return StorageOperationStatus.OK; - } - - @Override - public Either certifyComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction) { - Either result = null; - - try { - String resourceIdBeforeCertify = component.getUniqueId(); - String[] versionParts = component.getVersion().split(VERSION_DELIMETER_REGEXP); - Integer majorVersion = Integer.parseInt(versionParts[0]); - - // update old certified resource - if (majorVersion > 0) { - StorageOperationStatus updateLastCertifiedResource = StorageOperationStatus.OK; - updateLastCertifiedResource = updateLastCertifiedComponent(component, majorVersion); - if (!updateLastCertifiedResource.equals(StorageOperationStatus.OK)) { - return Either.right(updateLastCertifiedResource); - } - } - - // clone the resource - Either createResourceResult = Either.right(StorageOperationStatus.GENERAL_ERROR); - switch (nodeType) { - case Service: - case Resource: - createResourceResult = cloneComponentForCertified(component, modifier, majorVersion); - break; - default: - log.error("component object is with type {} . It's not supported type"); - result = Either.right(StorageOperationStatus.BAD_REQUEST); - return result; - } - - if (createResourceResult.isRight()) { - log.error("failed to create new resource version for checkout."); - result = createResourceResult; - return createResourceResult; - } - - Component certifiedResource = createResourceResult.left().value(); - - // add rfc relation to preserve follower information - StorageOperationStatus addRfcRelation = addRfcRelationToCertfiedComponent(nodeType, resourceIdBeforeCertify, certifiedResource.getUniqueId()); - if (!addRfcRelation.equals(StorageOperationStatus.OK)) { - result = Either.right(addRfcRelation); - return result; - } - - result = Either.left(certifiedResource); - - } 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; - } - - @Override - public Either deleteOldComponentVersions(NodeTypeEnum nodeType, String componentName, String uuid, boolean inTransaction) { - - Either result = null; - ComponentOperation componentOperation = getComponentOperation(nodeType); - - try { - Either, StorageOperationStatus> oldVersionsToDelete = getComponentTempVersions(nodeType, uuid); - - if (oldVersionsToDelete.isRight()) { - result = Either.right(oldVersionsToDelete.right().value()); - return result; - } - - for (Component resourceToDelete : oldVersionsToDelete.left().value()) { - - Either updateResource = componentOperation.markComponentToDelete(resourceToDelete, inTransaction); - if (updateResource.isRight()) { - result = Either.right(updateResource.right().value()); - return result; - } - } - result = Either.left(true); - 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 StorageOperationStatus addRfcRelationToCertfiedComponent(NodeTypeEnum componentType, String resourceIdBeforeCertify, String uniqueId) { - - // get user of certification request - UniqueIdData componentV = new UniqueIdData(componentType, resourceIdBeforeCertify); - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - Either rfcRelationResponse = titanGenericDao.getIncomingRelationByCriteria(componentV, GraphEdgeLabels.LAST_STATE, props); - if (rfcRelationResponse.isRight()) { - TitanOperationStatus status = rfcRelationResponse.right().value(); - log.error("failed to find rfc relation for component {}. status=", resourceIdBeforeCertify, status); - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - GraphRelation rfcRelation = rfcRelationResponse.left().value(); - rfcRelation.setTo(new RelationEndPoint(componentType, GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId)); - - Either createRelationResponse = titanGenericDao.createRelation(rfcRelation); - if (createRelationResponse.isRight()) { - TitanOperationStatus status = createRelationResponse.right().value(); - log.error("failed to create rfc relation for component {}. status=", uniqueId, status); - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - return StorageOperationStatus.OK; - - } - - private StorageOperationStatus updateLastCertifiedComponent(Component component, Integer majorVersion) { - - NodeTypeEnum nodeType = component.getComponentType().getNodeType(); - ComponentOperation componentOperation = getComponentOperation(nodeType); - Map additionalQueryParams = null; - if (nodeType == NodeTypeEnum.Resource) { - ResourceTypeEnum resourceType = ((Resource) component).getResourceType(); - additionalQueryParams = new HashMap(); - additionalQueryParams.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType.name()); - } - Either getLastCertifiedResponse = componentOperation.getComponentByNameAndVersion(component.getName(), majorVersion + VERSION_DELIMETER + "0", additionalQueryParams, true); - - if (getLastCertifiedResponse.isRight()) { - log.error("failed to update last certified resource. status={}", getLastCertifiedResponse.right().value()); - return getLastCertifiedResponse.right().value(); - } - - Component lastCertified = getLastCertifiedResponse.left().value(); - lastCertified.setHighestVersion(false); - Either updateResource = componentOperation.updateComponent(lastCertified, true); - if (updateResource.isRight()) { - log.error("failed to update last certified resource. status={}", updateResource.right().value()); - return updateResource.right().value(); - } - return StorageOperationStatus.OK; - } - - private Either cloneComponentForCheckout(Component component, NodeTypeEnum nodeType, User modifier) { - - ComponentOperation componentOperation = getComponentOperation(nodeType); - String prevId = component.getUniqueId(); - // set new version - Either nextVersion = getNextVersion(component.getVersion()); - if (nextVersion.isRight()) { - return Either.right(nextVersion.right().value()); - } - - // if checkout on certified service - init distribution status back - if (nodeType == NodeTypeEnum.Service && component.getLifecycleState().equals(LifecycleStateEnum.CERTIFIED)) { - ((Service) component).setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - } - - String version = nextVersion.left().value(); - component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - component.setLastUpdateDate(null); - component.setLastUpdaterUserId(modifier.getUserId()); - component.setHighestVersion(true); - - // check version of resource does not exist. Note that resource type VF - // can have same name as resource type VFC - Map additionalQueryParams = null; - if (nodeType == NodeTypeEnum.Resource) { - ResourceTypeEnum resourceType = ((Resource) component).getResourceType(); - additionalQueryParams = new HashMap(); - additionalQueryParams.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType.name()); - } - String name = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - Either alreadyExistResult = componentOperation.getComponentByNameAndVersion(name, version, additionalQueryParams, true); - if (alreadyExistResult.isLeft()) { - log.debug("Component with name {} and version {} already exist", name, version); - return Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS); - - } - - StorageOperationStatus storageOperationStatus = alreadyExistResult.right().value(); - if (storageOperationStatus != StorageOperationStatus.NOT_FOUND) { - log.debug("Unexpected error when checking if component with name {} and version {} already exist, error: {}", name, version, storageOperationStatus); - return Either.right(storageOperationStatus); - } - - Either cloneComponentResponse = componentOperation.cloneComponent(component, version, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, true); - - return cloneComponentResponse; - } - - private Either getNextVersion(String currVersion) { - String[] versionParts = currVersion.split(VERSION_DELIMETER_REGEXP); - if (versionParts == null || versionParts.length != 2) { - log.error("invalid version {}", currVersion); - return Either.right(StorageOperationStatus.BAD_REQUEST); - } - - Integer minorVersion = Integer.parseInt(versionParts[1]) + 1; - String newVersion = versionParts[0] + VERSION_DELIMETER + minorVersion; - return Either.left(newVersion); - } - - private StorageOperationStatus setRelationForCancelCertification(LifecycleStateEnum nextState, NodeTypeEnum componentType, String componentId) { - - StorageOperationStatus result = StorageOperationStatus.GENERAL_ERROR; - Map props = new HashMap(); - UniqueIdData componentData = new UniqueIdData(componentType, componentId); - - // delete relation CERTIFICATION_IN_PROGRESS - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - - Either deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.STATE, props); - if (deleteResult.isRight()) { - log.debug("failed to update last state relation"); - result = StorageOperationStatus.INCONSISTENCY; - return result; - } - - // delete relation READY_FOR_CERTIFICATION (LAST_STATE) - props.put(GraphPropertiesDictionary.STATE.getProperty(), nextState); - - deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE, props); - if (deleteResult.isRight()) { - log.debug("failed to update last state relation"); - result = StorageOperationStatus.INCONSISTENCY; - return result; - } - GraphRelation origRelation = deleteResult.left().value(); - - // create relation READY_FOR_CERTIFICATION (STATE) - UserData user = new UserData(); - user.setUserId((String) origRelation.getFrom().getIdValue()); - Either createRelationResult = titanGenericDao.createRelation(user, componentData, GraphEdgeLabels.STATE, origRelation.toGraphMap()); - - if (createRelationResult.isRight()) { - log.error("failed to update last state relation. status={}", createRelationResult.right().value()); - result = StorageOperationStatus.INCONSISTENCY; - return result; - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus setRelationForFailCertification(LifecycleStateEnum nextState, NodeTypeEnum componentType, String componentId) { - - StorageOperationStatus result = null; - Map props = new HashMap(); - UniqueIdData componentData = new UniqueIdData(componentType, componentId); - - // delete relation CERTIFICATION_IN_PROGRESS - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - - Either deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.STATE, props); - if (deleteResult.isRight()) { - log.debug("failed to update last state relation"); - result = StorageOperationStatus.INCONSISTENCY; - return result; - } - - // delete relation READY_FOR_CERTIFICATION - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - - deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE, props); - if (deleteResult.isRight()) { - log.debug("failed to update last state relation"); - result = StorageOperationStatus.INCONSISTENCY; - return result; - } - - // delete relation NOT_CERTIFIED_CHECKIN (in order to change to STATE) - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE, props); - if (deleteResult.isRight()) { - log.debug("failed to update last state relation"); - result = StorageOperationStatus.INCONSISTENCY; - return result; - } - - // create new STATE relation NOT_CERTIFIED_CHECKIN - GraphRelation origRelation = deleteResult.left().value(); - UserData user = new UserData(); - user.setUserId((String) origRelation.getFrom().getIdValue()); - Either createRelationResult = titanGenericDao.createRelation(user, componentData, GraphEdgeLabels.STATE, origRelation.toGraphMap()); - - if (createRelationResult.isRight()) { - log.debug("failed to update last state relation"); - result = StorageOperationStatus.INCONSISTENCY; - return result; - } - - // delete relation LAST_MODIFIER (in order to change tester to designer) - deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_MODIFIER, null); - if (deleteResult.isRight()) { - log.debug("failed to update last modifier relation"); - result = StorageOperationStatus.INCONSISTENCY; - return result; - } - - // create new LAST_MODIFIER relation - origRelation = deleteResult.left().value(); - createRelationResult = titanGenericDao.createRelation(user, componentData, GraphEdgeLabels.LAST_MODIFIER, origRelation.toGraphMap()); - if (createRelationResult.isRight()) { - log.debug("failed to update last state relation"); - result = StorageOperationStatus.INCONSISTENCY; - return result; - } - - return StorageOperationStatus.OK; - } - - /** - * update service metadata - lastUpdater and state - * - * @param component - * @param modifier - * @param nextState - * @return - */ - private Either updateComponentMD(Component component, User modifier, LifecycleStateEnum nextState, NodeTypeEnum nodeType, ComponentParametersView returnedComponentParametersViewFilter) { - - if (returnedComponentParametersViewFilter == null) { - returnedComponentParametersViewFilter = new ComponentParametersView(); - } - - Either result = Either.right(StorageOperationStatus.GENERAL_ERROR); - component.setLastUpdateDate(null); - component.setLastUpdaterUserId(modifier.getUserId()); - - ComponentOperation componentOperation = getComponentOperation(nodeType); - ComponentParametersView filterParametersView = buildFilterForFetchComponentAfterChangeState(); - log.debug("updateComponentMD::updateComponentFilterResult start"); - result = componentOperation.updateComponentFilterResult(component, true, filterParametersView); - log.debug("updateComponentMD::updateComponentFilterResult end"); - if (result.isRight()) { - log.debug("Failed to update component for certification request, error: {}", result.right().value()); - return result; - } - log.debug("updateComponentMD::getAndUpdateMetadata start"); - // get service MD - Either componentDataResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), component.getUniqueId(), ComponentMetadataData.class); - if (componentDataResult.isRight()) { - log.debug("failed to get service data from graph"); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentDataResult.right().value())); - } - - // set state on resource - ComponentMetadataData componentData = componentDataResult.left().value(); - componentData.getMetadataDataDefinition().setState(nextState.name()); - component.setLifecycleState(nextState); - Either updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class); - log.debug("updateComponentMD::getAndUpdateMetadata end"); - if (updateNode.isRight()) { - log.error("Failed to update component {}. status is {}", component.getUniqueId(), updateNode.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); - return result; - } - log.debug("updateComponentMD::getAndUpdateMetadata start"); - Either serviceAfterChange = componentOperation.getComponent(component.getUniqueId(), returnedComponentParametersViewFilter, true); - log.debug("updateComponentMD::getAndUpdateMetadata end"); - if (serviceAfterChange.isRight()) { - log.error("Failed to get component {} after change. status is {}", component.getUniqueId(), updateNode.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); - return result; - } - return Either.left((Component) serviceAfterChange.left().value()); - } - - /** - * update resouce metadata - lastUpdater and state - * - * @param resource - * @param modifier - * @param nextState - * @return - */ - private Either updateResourceMD(Resource resource, User modifier, LifecycleStateEnum nextState) { - - Either result; - resource.setLastUpdateDate(null); - resource.setLastUpdaterUserId(modifier.getUserId()); - - result = resourceOperation.updateResource(resource, true); - if (result.isRight()) { - log.debug("failed to update resource for certification request."); - return result; - } - // get resource MD - Either resourceDataResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId(), ResourceMetadataData.class); - if (resourceDataResult.isRight()) { - log.debug("failed to get resource data from graph"); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceDataResult.right().value())); - } - - // set state on resource - ResourceMetadataData resourceData = resourceDataResult.left().value(); - resourceData.getMetadataDataDefinition().setState(nextState.name()); - resource.setLifecycleState(nextState); - Either updateNode = titanGenericDao.updateNode(resourceData, ResourceMetadataData.class); - - if (updateNode.isRight()) { - log.error("Failed to update resource {}. status is {}", resource.getUniqueId(), updateNode.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); - return result; - } - return Either.left(resource); - } - - private Either, StorageOperationStatus> getComponentTempVersions(NodeTypeEnum nodeType, String uuid) { - - Either, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR); - List componentList = new ArrayList(); - ComponentOperation componentOperation = getComponentOperation(nodeType); - - Map hasProps = new HashMap(); - Map hasNotProps = new HashMap(); - - createOldVersionsCriteria(nodeType, uuid, hasProps, hasNotProps); - - Either, TitanOperationStatus> getByCriteria = titanGenericDao.getByCriteria(nodeType, hasProps, hasNotProps, ComponentMetadataData.class); - - if (getByCriteria.isRight()) { - log.error("failed to get old versions for component, type:{}, id: {}", nodeType, uuid); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getByCriteria.right().value())); - return result; - } - - List oldVersionComponents = getByCriteria.left().value(); - for (ComponentMetadataData component : oldVersionComponents) { - Either resourceRes = componentOperation.getComponent(component.getMetadataDataDefinition().getUniqueId(), true); - if (resourceRes.isRight()) { - result = Either.right(resourceRes.right().value()); - return result; - } else { - componentList.add(resourceRes.left().value()); - } - } - result = Either.left(componentList); - return result; - } - - /* - * private Either, StorageOperationStatus> getServiceTempVersions(NodeTypeEnum nodeType, String uuid) { - * - * Either, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR); List resourceList = new ArrayList(); - * - * Map hasProps = new HashMap(); Map hasNotProps = new HashMap(); - * - * createOldVersionsCriteria(nodeType, uuid, hasProps, hasNotProps); - * - * Either, TitanOperationStatus> getByCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, hasProps, hasNotProps, ServiceMetadataData.class); - * - * if (getByCriteria.isRight()) { log.error("failed to get old versions for {}", uuid); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus( getByCriteria.right().value())); return result; } - * - * List oldVersionResources = getByCriteria.left().value(); for (ServiceMetadataData resource : oldVersionResources) { Either resourceRes = serviceOperation.getService((String) - * resource.getUniqueId(), true); if (resourceRes.isRight()) { result = Either.right(resourceRes.right().value()); return result; } else { resourceList.add(resourceRes.left().value()); } } result = Either.left(resourceList); return result; } - */ - private void createOldVersionsCriteria(NodeTypeEnum nodeType, String uuid, Map hasProps, Map hasNotProps) { - - hasProps.put(GraphPropertiesDictionary.UUID.getProperty(), uuid); - hasProps.put(GraphPropertiesDictionary.LABEL.getProperty(), nodeType.name().toLowerCase()); - hasNotProps.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); - } - - private Either updateOldComponentBeforeUndoCheckout(ComponentOperation componentOperation, Component prevComponent, Component currentComponent, String previousVersion, NodeTypeEnum nodeType, - boolean inTransaction) { - - log.debug("update previous version of component"); - Map additionalQueryParams = new HashMap(); - - if (nodeType == NodeTypeEnum.Resource) { - ResourceTypeEnum resourceType = ((Resource) currentComponent).getResourceType(); - - additionalQueryParams.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType.name()); - } - ComponentMetadataDataDefinition metadataDataDefinition = currentComponent.getComponentMetadataDefinition().getMetadataDataDefinition(); - Either getOlderCompResult = componentOperation.getComponentByNameAndVersion(metadataDataDefinition.getName(), previousVersion, additionalQueryParams, true); - - // if previous version exist - set it as current version - if (getOlderCompResult.isRight()) { - if (StorageOperationStatus.NOT_FOUND.equals(getOlderCompResult.right().value())) { - log.debug("No components by name and version: {} - {}", metadataDataDefinition.getName(), previousVersion); - log.debug("Name may have changed, since the version isn't certified try to fetch by UUID {}", metadataDataDefinition.getUUID()); - additionalQueryParams.clear(); - additionalQueryParams.put(GraphPropertiesDictionary.UUID.getProperty(), metadataDataDefinition.getUUID()); - additionalQueryParams.put(GraphPropertiesDictionary.VERSION.getProperty(), previousVersion); - - Either, TitanOperationStatus> byUUID = titanGenericDao.getByCriteria(nodeType, additionalQueryParams, ComponentMetadataData.class); - if (byUUID.isRight()) { - log.debug("Failed to fetch by UUID {}", metadataDataDefinition.getUUID()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byUUID.right().value())); - } - String prevVersionId = (String) byUUID.left().value().get(0).getUniqueId(); - Either component = componentOperation.getComponent(prevVersionId, inTransaction); - if (component.isRight()) { - log.debug("Failed to fetch previous component by ID {}", prevVersionId); - return Either.right(component.right().value()); - } - prevComponent = component.left().value(); - } else { - log.error("failed to find previous version. status={} ", getOlderCompResult.right().value()); - return getOlderCompResult; - } - } else { - prevComponent = getOlderCompResult.left().value(); - } - - // if last resource is certified - don't touch it. - if (prevComponent.getVersion().endsWith(".0")) { - return Either.left(prevComponent); - } - - prevComponent.setHighestVersion(true); - Either updateCompResult = componentOperation.updateComponent(prevComponent, inTransaction); - if (updateCompResult.isRight()) { - log.debug("failed to update prev version of component"); - return updateCompResult; - } - - User user = new User(); - user.setUserId(prevComponent.getLastUpdaterUserId()); - StorageOperationStatus changeStateRelation = changeStateRelation(nodeType, prevComponent.getUniqueId(), user, GraphEdgeLabels.LAST_STATE, GraphEdgeLabels.STATE); - if (!changeStateRelation.equals(StorageOperationStatus.OK)) { - return Either.right(changeStateRelation); - } - - return Either.left(prevComponent); - } - - private StorageOperationStatus changeStateRelation(NodeTypeEnum nodeType, String componentId, User currentOwner, GraphEdgeLabels from, GraphEdgeLabels to) { - UniqueIdData componentData = new UniqueIdData(nodeType, componentId); - UserData userData = new UserData(); - userData.setUserId(currentOwner.getUserId()); - Either replaceRelationLabelResult = titanGenericDao.replaceRelationLabel(userData, componentData, from, to); - if (replaceRelationLabelResult.isRight()) { - TitanOperationStatus titanStatus = replaceRelationLabelResult.right().value(); - log.error("failed to replace label from {} to {}. status = {}", from, to, titanStatus); - StorageOperationStatus storageStatus = StorageOperationStatus.INCONSISTENCY; - if (!titanStatus.equals(TitanOperationStatus.INVALID_ID)) { - storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); - } - return storageStatus; - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus removeUserToResourceRelation(NodeTypeEnum componentType, String idFrom, String idTo, GraphEdgeLabels label) { - - UniqueIdData componentV = new UniqueIdData(componentType, idTo); - UserData userV = new UserData(); - userV.setUserId(idFrom); - // delete relation - Either deleteRelationResult = titanGenericDao.deleteRelation(userV, componentV, label); - if (deleteRelationResult.isRight()) { - log.error("failed to delete relation. status={}", deleteRelationResult.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteRelationResult.right().value()); - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus createUserToResourceRelation(NodeTypeEnum componentType, String idFrom, String idTo, GraphEdgeLabels label, Map props) { - - UniqueIdData componentV = new UniqueIdData(componentType, idTo); - UserData userV = new UserData(); - userV.setUserId(idFrom); - // create relation - Either createRelationResult = titanGenericDao.createRelation(userV, componentV, label, props); - if (createRelationResult.isRight()) { - log.error("failed to create relation. status={}", createRelationResult.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(createRelationResult.right().value()); - } - return StorageOperationStatus.OK; - } - - @Override - public Either cancelOrFailCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, LifecycleStateEnum nextState, boolean inTransaction) { - - Either result = Either.right(StorageOperationStatus.GENERAL_ERROR); - try { - - ComponentParametersView componentParametersView = buildFilterForFetchComponentAfterChangeState(); - result = updateComponentMD(component, modifier, nextState, nodeType, componentParametersView); - if (result.isRight()) { - log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), nextState, result.right().value()); - return result; - } - StorageOperationStatus status = StorageOperationStatus.OK; - // cancel certification process - if (nextState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) { - status = setRelationForCancelCertification(nextState, nodeType, component.getUniqueId()); - - } // fail certification - else if (nextState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN)) { - status = setRelationForFailCertification(nextState, nodeType, component.getUniqueId()); - } - - if (!status.equals(StorageOperationStatus.OK)) { - result = Either.right(status); - } - } 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; - } - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java deleted file mode 100644 index 3d4fba36df..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java +++ /dev/null @@ -1,957 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Collectors; -import java.util.Set; - -import com.thinkaurelius.titan.core.TitanTransaction; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; -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.datatypes.category.CategoryDataDefinition; -import org.openecomp.sdc.be.datatypes.category.GroupingDataDefinition; -import org.openecomp.sdc.be.datatypes.category.SubCategoryDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ProductMetadataDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.category.GroupingDefinition; -import org.openecomp.sdc.be.model.category.SubCategoryDefinition; -import org.openecomp.sdc.be.model.operations.api.IProductOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.resources.data.ComponentMetadataData; -import org.openecomp.sdc.be.resources.data.ProductMetadataData; -import org.openecomp.sdc.be.resources.data.ServiceMetadataData; -import org.openecomp.sdc.be.resources.data.UserData; -import org.openecomp.sdc.be.resources.data.category.CategoryData; -import org.openecomp.sdc.be.resources.data.category.GroupingData; -import org.openecomp.sdc.be.resources.data.category.SubCategoryData; -import org.openecomp.sdc.common.util.ValidationUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.thinkaurelius.titan.core.TitanGraph; - -import fj.data.Either; - -@org.springframework.stereotype.Component("product-operation") -public class ProductOperation extends ComponentOperation implements IProductOperation { - - private static Logger log = LoggerFactory.getLogger(ProductOperation.class.getName()); - - public ProductOperation() { - log.debug("ProductOperation created"); - } - - @Override - protected ComponentMetadataData getMetaDataFromComponent(Component component) { - return getProductMetadataDataFromProduct((Product) component); - } - - @SuppressWarnings("unchecked") - @Override - public Either getComponent(String id, boolean inTransaction) { - return (Either) getProduct(id, inTransaction); - } - - // public Either getComponent_tx(String id, - // boolean inTransaction) { - // return (Either) getProduct_tx(id, - // inTransaction); - // } - - @SuppressWarnings("unchecked") - @Override - protected Either getComponentByNameAndVersion(String name, String version, Map additionalParams, boolean inTransaction) { - return (Either) getByNamesAndVersion(GraphPropertiesDictionary.NAME.getProperty(), name, version, additionalParams, inTransaction); - } - - @Override - public Either getLightComponent(String id, boolean inTransaction) { - return getLightComponent(id, NodeTypeEnum.Product, inTransaction); - } - - @Override - public Either, StorageOperationStatus> getFilteredComponents(Map filters, boolean inTransaction) { - return getFilteredComponents(filters, inTransaction, NodeTypeEnum.Product); - } - - private Product convertProductDataToProduct(ProductMetadataData productData) { - ProductMetadataDefinition productMetadataDefinition = new ProductMetadataDefinition((ProductMetadataDataDefinition) productData.getMetadataDataDefinition()); - - Product product = new Product(productMetadataDefinition); - - return product; - } - - @SuppressWarnings("unchecked") - @Override - public Either updateComponent(T component, boolean inTransaction) { - return (Either) updateComponent((Component) component, inTransaction, titanGenericDao, Product.class, NodeTypeEnum.Product); - } - - @SuppressWarnings("unchecked") - @Override - public Either deleteComponent(String id, boolean inTransaction) { - return (Either) (Either) deleteProduct(id, inTransaction); - } - - @Override - public Either, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } - - @SuppressWarnings("unchecked") - @Override - public Either getComponent(String id, Class clazz) { - return (Either) getProduct(id, false); - } - - @Override - /** - * Deletes the product node - */ - public Either deleteProduct(String productId, boolean inTransaction) { - - Either result = Either.right(StorageOperationStatus.GENERAL_ERROR); - - try { - - Either graphResult = titanGenericDao.getGraph(); - if (graphResult.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); - return result; - } - - Either productNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Product), productId, ProductMetadataData.class); - if (productNode.isRight()) { - TitanOperationStatus status = productNode.right().value(); - log.error("Failed to find product {}. status is {}", productId, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - Either productRes = getProduct(productId, true); - if (productRes.isRight()) { - StorageOperationStatus status = productRes.right().value(); - log.error("Failed to find product {}.status is {}", productId, status); - result = Either.right(status); - return result; - } - Product product = productRes.left().value(); - - Either, StorageOperationStatus> deleteAllInstancesRes = componentInstanceOperation.deleteAllComponentInstances(productId, NodeTypeEnum.Product, true); - log.debug("After deleting instances under product {}.Result is {}", productId, deleteAllInstancesRes); - if (deleteAllInstancesRes.isRight()) { - StorageOperationStatus status = deleteAllInstancesRes.right().value(); - if (status != StorageOperationStatus.NOT_FOUND) { - log.error("Failed to delete instances under product {}.status is {}", productId, status); - result = Either.right(status); - return result; - } - } - - Either deleteProductNodeRes = titanGenericDao.deleteNode(productNode.left().value(), ProductMetadataData.class); - if (deleteProductNodeRes.isRight()) { - TitanOperationStatus status = deleteProductNodeRes.right().value(); - log.error("Failed to delete product node {}. status is {}", productId, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - result = Either.left(product); - - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.error("deleteProduct operation : Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("deleteProduct operation : Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - @Override - public Either, StorageOperationStatus> getProductCatalogData(boolean inTransaction) { - - long start = System.currentTimeMillis(); - try { - /* - * Map propertiesToMatch = new HashMap<>(); - * - * propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty (), LifecycleStateEnum.CERTIFIED.name()); Either, TitanOperationStatus> lastVersionNodes = getLastVersion(NodeTypeEnum.Product, - * propertiesToMatch, ProductMetadataData.class); if (lastVersionNodes.isRight() && lastVersionNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus - * (lastVersionNodes.right().value())); } List notCertifiedHighest = (lastVersionNodes.isLeft() ? lastVersionNodes.left().value() : new ArrayList()); - * - * propertiesToMatch.put(GraphPropertiesDictionary. IS_HIGHEST_VERSION.getProperty(), true); Either, TitanOperationStatus> componentsNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Product, propertiesToMatch, - * ProductMetadataData.class); if (componentsNodes.isRight() && componentsNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus - * (componentsNodes.right().value())); } List certifiedHighest = (componentsNodes.isLeft() ? componentsNodes.left().value() : new ArrayList()); Set names = new HashSet(); for - * (ProductMetadataData data : notCertifiedHighest) { String name = data.getMetadataDataDefinition().getName(); names.add(name); } - * - * for (ProductMetadataData data : certifiedHighest) { String productName = data.getMetadataDataDefinition().getName(); if (!names.contains(productName)) { notCertifiedHighest.add(data); } } - */ - Either, TitanOperationStatus> listOfHighestComponents = this.getListOfHighestComponents(NodeTypeEnum.Product, ProductMetadataData.class); - if (listOfHighestComponents.isRight() && listOfHighestComponents.right().value() != TitanOperationStatus.NOT_FOUND) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfHighestComponents.right().value())); - } - - List notCertifiedHighest = listOfHighestComponents.left().value(); - - List result = new ArrayList<>(); - - if (notCertifiedHighest != null && false == notCertifiedHighest.isEmpty()) { - - // fetch from cache - long startFetchAllFromCache = System.currentTimeMillis(); - - Map components = notCertifiedHighest.stream().collect(Collectors.toMap(p -> p.getMetadataDataDefinition().getUniqueId(), p -> p.getMetadataDataDefinition().getLastUpdateDate())); - - Either, Set>, ActionStatus> componentsFromCacheForCatalog = this.getComponentsFromCacheForCatalog(components, ComponentTypeEnum.PRODUCT); - if (componentsFromCacheForCatalog.isLeft()) { - ImmutablePair, Set> immutablePair = componentsFromCacheForCatalog.left().value(); - List list = immutablePair.getLeft(); - if (list != null) { - for (Component component : list) { - result.add((Product) component); - } - List addedUids = list.stream().map(p -> p.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId()).collect(Collectors.toList()); - notCertifiedHighest = notCertifiedHighest.stream().filter(p -> false == addedUids.contains(p.getMetadataDataDefinition().getUniqueId())).collect(Collectors.toList()); - } - } - long endFetchAllFromCache = System.currentTimeMillis(); - log.debug("Fetch all catalog products metadata from cache took {} ms", (endFetchAllFromCache - startFetchAllFromCache)); - log.debug("The number of products added to catalog from cache is {}", result.size()); - - log.debug("The number of products needed to be fetch as light component is {}", notCertifiedHighest.size()); - - for (ProductMetadataData data : notCertifiedHighest) { - Either component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction); - if (component.isRight()) { - log.debug("Failed to get product for id = {}, error : {}. skip product", data.getUniqueId(), component.right().value()); - } else { - // get all versions - Product product = component.left().value(); - // setAllVersions(product); - - result.add(product); - } - } - } - return Either.left(result); - } finally { - if (false == inTransaction) { - titanGenericDao.commit(); - } - log.debug("Fetch all catalog products took {} ms", System.currentTimeMillis() - start); - } - } - - @Override - public Either createProduct(Product product) { - return createProduct(product, false); - } - - @Override - public Either createProduct(Product product, boolean inTransaction) { - Either result = null; - - try { - - ProductMetadataData productData = getProductMetadataDataFromProduct(product); - addComponentInternalFields(productData); - String uniqueId = (String) productData.getUniqueId(); - generateUUID(product); - - String userId = product.getCreatorUserId(); - - Either findUser = findUser(userId); - - if (findUser.isRight()) { - TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user {} in the graph. status is {}", userId, status); - return sendError(status, StorageOperationStatus.USER_NOT_FOUND); - } - - UserData creatorUserData = findUser.left().value(); - UserData updaterUserData = creatorUserData; - String updaterUserId = product.getLastUpdaterUserId(); - if (updaterUserId != null && !updaterUserId.equals(userId)) { - findUser = findUser(updaterUserId); - if (findUser.isRight()) { - TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user {} in the graph. status is {}", userId, status); - return sendError(status, StorageOperationStatus.USER_NOT_FOUND); - } else { - updaterUserData = findUser.left().value(); - } - } - - log.trace("Creating tags for product {}", uniqueId); - StorageOperationStatus storageOperationStatus = createTagsForComponent(product); - if (storageOperationStatus != StorageOperationStatus.OK) { - return Either.right(storageOperationStatus); - } - - log.trace("Finding groupings for product {}", uniqueId); - Either, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent(NodeTypeEnum.ProductGrouping, product); - if (findGroupingsForComponent.isRight()) { - return Either.right(findGroupingsForComponent.right().value()); - } - List groupingDataToAssociate = findGroupingsForComponent.left().value(); - - log.debug("try to create product node on graph for id {}", uniqueId); - Either createNode = titanGenericDao.createNode(productData, ProductMetadataData.class); - if (createNode.isRight()) { - TitanOperationStatus status = createNode.right().value(); - log.error("Error returned after creating product data node {}. Status returned is {}", productData, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - log.debug("product node created on graph for id {}", productData.getUniqueId()); - - TitanOperationStatus associateMetadata = associateMetadataToComponent(productData, creatorUserData, updaterUserData, null, null); - if (associateMetadata != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateMetadata)); - return result; - } - - TitanOperationStatus associateCategories = associateCategoriesToProduct(productData, groupingDataToAssociate); - if (associateCategories != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateCategories)); - return result; - } - - result = getProduct(uniqueId, true); - if (result.isRight()) { - log.error("Cannot get full product from the graph. status is {}", result.right().value()); - return Either.right(result.right().value()); - } - - if (log.isDebugEnabled()) { - String json = prettyJson.toJson(result.left().value()); - log.debug("Product retrieved is {}", json); - } - - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - } - - private TitanOperationStatus associateCategoriesToProduct(ProductMetadataData productData, List groupingDataToAssociate) { - for (GroupingData groupingData : groupingDataToAssociate) { - GraphEdgeLabels groupingLabel = GraphEdgeLabels.CATEGORIZED_TO; - Either result = titanGenericDao.createRelation(productData, groupingData, groupingLabel, null); - log.debug("After associating grouping {} to product {}. Edge type is {}", groupingData, productData, groupingLabel); - if (result.isRight()) { - return result.right().value(); - } - } - log.trace("All groupings associated succesfully to product {}", productData); - return TitanOperationStatus.OK; - } - - private TitanOperationStatus dissociateCategoriesFromProduct(ProductMetadataData productData, List groupingDataToDissociate) { - for (GroupingData groupingData : groupingDataToDissociate) { - GraphEdgeLabels groupingLabel = GraphEdgeLabels.CATEGORIZED_TO; - Either result = titanGenericDao.deleteRelation(productData, groupingData, groupingLabel); - log.debug("After dissociating grouping {} from product {}. Edge type is {}", groupingData, productData, groupingLabel); - if (result.isRight()) { - return result.right().value(); - } - } - log.trace("All groupings dissociated succesfully from product {}", productData); - return TitanOperationStatus.OK; - } - - private Either getProduct(String uniqueId, boolean inTransaction) { - ComponentParametersView componentParametersView = new ComponentParametersView(); - return getProduct(uniqueId, componentParametersView, inTransaction); - } - - private Either getProduct(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction) { - Product product = null; - Either result = null; - try { - - NodeTypeEnum productNodeType = NodeTypeEnum.Product; - NodeTypeEnum compInstNodeType = NodeTypeEnum.Service; - - Either getComponentByLabel = getComponentByLabelAndId(uniqueId, productNodeType, ProductMetadataData.class); - if (getComponentByLabel.isRight()) { - result = Either.right(getComponentByLabel.right().value()); - return result; - } - ProductMetadataData productData = getComponentByLabel.left().value(); - - // Try to fetch resource from the cache. The resource will be - // fetched only if the time on the cache equals to - // the time on the graph. - Either componentFromCacheIfUpToDate = this.getComponentFromCacheIfUpToDate(uniqueId, productData, componentParametersView, Product.class, ComponentTypeEnum.PRODUCT); - if (componentFromCacheIfUpToDate.isLeft()) { - Product cachedProduct = componentFromCacheIfUpToDate.left().value(); - log.debug("Product {} with uid {} was fetched from cache.", cachedProduct.getName(), cachedProduct.getUniqueId()); - return Either.left(cachedProduct); - } - - product = convertProductDataToProduct(productData); - - TitanOperationStatus status = null; - if (false == componentParametersView.isIgnoreUsers()) { - status = setComponentCreatorFromGraph(product, uniqueId, productNodeType); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - status = setComponentLastModifierFromGraph(product, uniqueId, productNodeType); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - - } - } - if (false == componentParametersView.isIgnoreCategories()) { - status = setComponentCategoriesFromGraph(product); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - } - - if (false == componentParametersView.isIgnoreComponentInstances() || false == componentParametersView.isIgnoreComponentInstancesProperties() || false == componentParametersView.isIgnoreCapabilities() - || false == componentParametersView.isIgnoreRequirements()) { - status = setComponentInstancesFromGraph(uniqueId, product, productNodeType, compInstNodeType); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - - } - } - if (false == componentParametersView.isIgnoreComponentInstancesProperties()) { - status = setComponentInstancesPropertiesFromGraph(product); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - } - if (false == componentParametersView.isIgnoreCapabilities()) { - status = setCapabilitiesFromGraph(uniqueId, product, NodeTypeEnum.Product); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - } - if (false == componentParametersView.isIgnoreRequirements()) { - status = setRequirementsFromGraph(uniqueId, product, NodeTypeEnum.Product); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - } - - if (false == componentParametersView.isIgnoreAllVersions()) { - status = setAllVersions(product); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - result = Either.left(product); - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - titanGenericDao.rollback(); - } else { - titanGenericDao.commit(); - } - } - } - } - - // private Either getProduct_tx(String - // uniqueId, boolean inTransaction) { - // Product product = null; - // Either result = null; - // try { - // - // NodeTypeEnum productNodeType = NodeTypeEnum.Product; - // NodeTypeEnum compInstNodeType = NodeTypeEnum.Service; - // - // Either getComponentByLabel = - // getComponentByLabelAndId_tx(uniqueId, productNodeType, - // ProductMetadataData.class); - // if (getComponentByLabel.isRight()) { - // result = Either.right(getComponentByLabel.right().value()); - // return result; - // } - // ProductMetadataData productData = getComponentByLabel.left().value(); - // product = convertProductDataToProduct(productData); - // - // TitanOperationStatus status = setComponentCreatorFromGraph(product, - // uniqueId, productNodeType); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // } - // - // status = setComponentLastModifierFromGraph(product, uniqueId, - // productNodeType); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // - // } - // status = setComponentCategoriesFromGraph(product); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // } - // - // status = setComponentInstancesFromGraph(uniqueId, product, - // productNodeType, compInstNodeType); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // - // } - // - // status = setComponentInstancesPropertiesFromGraph(uniqueId, product); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // } - // - // status = setCapabilitiesFromGraph(uniqueId, product, - // NodeTypeEnum.Product); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // } - // - // status = setRequirementsFromGraph( uniqueId, product, - // NodeTypeEnum.Product);; - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // } - // - // - // status = setAllVersions(product); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // result = Either.left(product); - // return result; - // - // } finally { - // if (false == inTransaction) { - // if (result == null || result.isRight()) { - // titanGenericDao.rollback(); - // } else { - // titanGenericDao.commit(); - // } - // } - // } - // } - - private TitanOperationStatus setAllVersions(Product product) { - Either, TitanOperationStatus> res = getVersionList(NodeTypeEnum.Product, product.getVersion(), product, ProductMetadataData.class); - if (res.isRight()) { - return res.right().value(); - } - product.setAllVersions(res.left().value()); - return TitanOperationStatus.OK; - } - - private Either sendError(TitanOperationStatus status, StorageOperationStatus statusIfNotFound) { - Either result; - if (status == TitanOperationStatus.NOT_FOUND) { - result = Either.right(statusIfNotFound); - return result; - } else { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - } - - @Override - TitanOperationStatus setComponentCategoriesFromGraph(Component component) { - Product product = (Product) component; - // Building the cat->subcat->grouping triples - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Product), product.getUniqueId(), GraphEdgeLabels.CATEGORIZED_TO, - NodeTypeEnum.ProductGrouping, GroupingData.class); - if (childrenNodes.isRight()) { - if (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Error when finding groupings for this product, error {}", childrenNodes.right().value()); - return childrenNodes.right().value(); - } else { - log.debug("No groupings found for this product - this might be normal"); - return TitanOperationStatus.OK; - } - } - Map>> categoriesDataStructure = new HashMap<>(); - - List> valueList = childrenNodes.left().value(); - for (ImmutablePair groupPair : valueList) { - GroupingData groupingData = groupPair.getLeft(); - Either, TitanOperationStatus> parentSubCat = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ProductGrouping), (String) groupingData.getUniqueId(), - GraphEdgeLabels.GROUPING, NodeTypeEnum.ProductSubcategory, SubCategoryData.class); - if (parentSubCat.isRight()) { - log.debug("Cannot find subcategory for grouping {}", groupingData.getUniqueId()); - return parentSubCat.right().value(); - } - SubCategoryData subCatData = parentSubCat.left().value().getLeft(); - Either, TitanOperationStatus> parentCat = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ProductSubcategory), (String) subCatData.getUniqueId(), - GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ProductCategory, CategoryData.class); - if (parentCat.isRight()) { - log.debug("Cannot find category for subcategory {}", subCatData.getUniqueId()); - return parentCat.right().value(); - } - - // Building data structure of categories hierarchy - CategoryDataDefinition categoryDefinition = parentCat.left().value().getLeft().getCategoryDataDefinition(); - SubCategoryDataDefinition subDefinition = subCatData.getSubCategoryDataDefinition(); - GroupingDataDefinition groupingDefinition = groupingData.getGroupingDataDefinition(); - - CategoryDefinition categoryDef = new CategoryDefinition(categoryDefinition); - SubCategoryDefinition subDef = new SubCategoryDefinition(subDefinition); - GroupingDefinition groupingDef = new GroupingDefinition(groupingDefinition); - - log.debug("Found category {} -> subcategory {} -> grouping {} for product {}", categoryDefinition.getUniqueId(), subCatData.getUniqueId(), groupingData.getUniqueId(), product.getUniqueId()); - Map> subMap = categoriesDataStructure.get(categoryDef); - if (subMap == null) { - subMap = new HashMap<>(); - categoriesDataStructure.put(categoryDef, subMap); - } - List groupList = subMap.get(subDef); - if (groupList == null) { - groupList = new ArrayList<>(); - subMap.put(subDef, groupList); - } - groupList.add(groupingDef); - } - convertToCategoriesList(product, categoriesDataStructure); - return TitanOperationStatus.OK; - } - - private void convertToCategoriesList(Product product, Map>> categoriesDataStructure) { - List categoryDataList = product.getCategories(); - if (categoryDataList == null) { - categoryDataList = new ArrayList(); - } - for (Entry>> triple : categoriesDataStructure.entrySet()) { - CategoryDefinition categoryDefinition = triple.getKey(); - List subList = new ArrayList<>(); - categoryDefinition.setSubcategories(subList); - Map> value = triple.getValue(); - - for (Entry> pair : value.entrySet()) { - SubCategoryDefinition subCategoryDefinition = pair.getKey(); - List list = pair.getValue(); - subList.add(subCategoryDefinition); - subCategoryDefinition.setGroupings(list); - } - categoryDataList.add(categoryDefinition); - } - product.setCategories(categoryDataList); - log.debug("Fetched categories for product {}, categories: {}", product.getUniqueId(), Arrays.toString(categoryDataList.toArray())); - } - - private ProductMetadataData getProductMetadataDataFromProduct(Product product) { - ProductMetadataData productMetadata = new ProductMetadataData((ProductMetadataDataDefinition) product.getComponentMetadataDefinition().getMetadataDataDefinition()); - return productMetadata; - } - - @Override - public boolean isComponentExist(String id) { - return isComponentExist(id, NodeTypeEnum.Product); - } - - // @SuppressWarnings("unchecked") - // @Override - // public Either cloneComponent(T other, - // String version, boolean inTransaction) { - // return (Either) cloneProduct((Product)other, - // version, inTransaction); - // } - - @SuppressWarnings("unchecked") - @Override - public Either cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) { - return (Either) cloneProduct((Product) other, version, targetLifecycle, inTransaction); - } - - private Either cloneProduct(Product other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) { - Either result = null; - - try { - String origProductId = other.getUniqueId(); - other.setVersion(version); - other.setUniqueId(null); - - Either counterStatus = getComponentInstanceCoutner(origProductId, NodeTypeEnum.Product); - if (counterStatus.isRight()) { - StorageOperationStatus status = counterStatus.right().value(); - log.error("failed to get resource instance counter on product {}. status={}", origProductId, counterStatus); - result = Either.right(status); - return result; - } - - Either createProductMD = createProduct(other, inTransaction); - if (createProductMD.isRight()) { - StorageOperationStatus status = createProductMD.right().value(); - log.debug("Failed to clone product. status= {}", status); - result = Either.right(status); - return result; - } - Product product = createProductMD.left().value(); - - Either, Map>, StorageOperationStatus> cloneInstances = componentInstanceOperation.cloneAllComponentInstancesFromContainerComponent(origProductId, product, - NodeTypeEnum.Product, NodeTypeEnum.Service, targetLifecycle, null); - if (cloneInstances.isRight()) { - result = Either.right(cloneInstances.right().value()); - return result; - } - - Either setResourceInstanceCounter = setComponentInstanceCounter(product.getUniqueId(), NodeTypeEnum.Product, counterStatus.left().value(), inTransaction); - if (setResourceInstanceCounter.isRight()) { - StorageOperationStatus status = setResourceInstanceCounter.right().value(); - log.error("failed to set resource instance counter on product {}. status={}", product.getUniqueId(), setResourceInstanceCounter); - result = Either.right(status); - return result; - } - - result = this.getProduct(product.getUniqueId(), inTransaction); - if (result.isRight()) { - log.error("Cannot get full product from the graph. status is {}", result.right().value()); - return Either.right(result.right().value()); - } - - if (log.isDebugEnabled()) { - String json = prettyJson.toJson(result.left().value()); - log.debug("Product retrieved is {}", json); - } - - return result; - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - } - - private Either getByNamesAndVersion(String nameKey, String nameValue, String version, Map additionalParams, boolean inTransaction) { - Map props = new HashMap(); - props.put(nameKey, nameValue); - props.put(GraphPropertiesDictionary.VERSION.getProperty(), version); - props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Product.getName()); - if (additionalParams != null && !additionalParams.isEmpty()) { - props.putAll(additionalParams); - } - - Either, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Product, props, ProductMetadataData.class); - - if (byCriteria.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value())); - } - List dataList = byCriteria.left().value(); - if (dataList != null && !dataList.isEmpty()) { - if (dataList.size() > 1) { - log.debug("More that one instance of product for name {} and version {}", nameValue, version); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - ProductMetadataData productData = dataList.get(0); - Either product = getProduct(productData.getMetadataDataDefinition().getUniqueId(), inTransaction); - if (product.isRight()) { - log.debug("Failed to fetch product, name {} id {}", productData.getMetadataDataDefinition().getName(), productData.getMetadataDataDefinition().getUniqueId()); - } - return product; - } - return Either.right(StorageOperationStatus.NOT_FOUND); - } - - @Override - public Product getDefaultComponent() { - return new Product(); - } - - @Override - protected StorageOperationStatus updateDerived(org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component currentComponent, ComponentMetadataData componentData, - Class clazz) { - log.debug("Derived class isn't supported for product"); - return StorageOperationStatus.OK; - } - - @Override - public Either increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction) { - return increaseAndGetComponentInstanceCounter(componentId, NodeTypeEnum.Product, inTransaction); - } - - @Override - protected StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type) { - // As agreed with Ella, update categories - delete old and create new - StorageOperationStatus status = StorageOperationStatus.OK; - List newcategories = component.getCategories(); - List currentcategories = currentComponent.getCategories(); - if (newcategories != null) { - if (currentcategories != null && !currentcategories.isEmpty()) { - Either, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent(NodeTypeEnum.ProductGrouping, currentComponent); - if (findGroupingsForComponent.isRight()) { - status = findGroupingsForComponent.right().value(); - } - List groupingDataToDissociate = findGroupingsForComponent.left().value(); - TitanOperationStatus titanStatus = dissociateCategoriesFromProduct((ProductMetadataData) componentData, groupingDataToDissociate); - if (titanStatus != TitanOperationStatus.OK) { - status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); - } - } - if (!newcategories.isEmpty()) { - Either, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent(NodeTypeEnum.ProductGrouping, component); - if (findGroupingsForComponent.isRight()) { - status = findGroupingsForComponent.right().value(); - } - List groupingDataToAssociate = findGroupingsForComponent.left().value(); - TitanOperationStatus titanStatus = associateCategoriesToProduct((ProductMetadataData) componentData, groupingDataToAssociate); - if (titanStatus != TitanOperationStatus.OK) { - status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); - } - } - } - return status; - } - - @Override - @SuppressWarnings("unchecked") - public Either, StorageOperationStatus> getFollowed(String userId, Set lifecycleStates, Set lastStateStates, boolean inTransaction) { - return (Either, StorageOperationStatus>) (Either) getFollowedComponent(userId, lifecycleStates, lastStateStates, inTransaction, titanGenericDao, NodeTypeEnum.Product); - } - - @Override - public Either getMetadataComponent(String id, boolean inTransaction) { - return getMetadataComponent(id, NodeTypeEnum.Product, inTransaction); - } - - @Override - Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData) { - return convertProductDataToProduct((ProductMetadataData) componentMetadataData); - } - - @Override - public Either validateComponentNameExists(String productName) { - return validateComponentNameUniqueness(productName, titanGenericDao, NodeTypeEnum.Product); - } - - @SuppressWarnings("unchecked") - @Override - public Either markComponentToDelete(Component componentToDelete, boolean inTransaction) { - // markComponentToDelete is not defined yet for products - return (Either) (Either) deleteProduct(componentToDelete.getUniqueId(), inTransaction); - } - - @Override - public void rollback() { - titanGenericDao.rollback(); - - } - - @Override - public void commit() { - titanGenericDao.commit(); - } - - @Override - public Either isComponentInUse(String componentId) { - return isComponentInUse(componentId, NodeTypeEnum.Product); - } - - @Override - public Either, StorageOperationStatus> getAllComponentsMarkedForDeletion() { - // markForDeletion for products is not implemented yet - return Either.left(new ArrayList<>()); - } - - public Either getProductByNameAndVersion(String productName, String productVersion, boolean inTransaction) { - return getByNamesAndVersion(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normaliseComponentName(productName), productVersion, null, inTransaction); - } - - @SuppressWarnings("unchecked") - @Override - public Either getComponent(String id, ComponentParametersView componentParametersView, boolean inTransaction) { - return (Either) getProduct(id, false); - } - - public Either updateProduct(Product product, boolean inTransaction, ComponentParametersView filterResultView) { - return (Either) updateComponentFilterResult(product, inTransaction, titanGenericDao, product.getClass(), NodeTypeEnum.Service, filterResultView); - } - - @Override - protected Either updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterResultView) { - return (Either) updateProduct((Product) component, inTransaction, filterResultView); - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java index 9b900b0ae2..6835e813ee 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 @@ -154,24 +154,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return functionPatterns; } - @Override - public Either getPropertyOfResource(String propertyName, String resourceId) { - - String propertyId = UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName); - - Either getResult = this.titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class); - if (getResult.isLeft()) { - PropertyData propertyData = getResult.left().value(); - return Either.left(convertPropertyDataToPropertyDefinition(propertyData, propertyName, resourceId)); - } else { - TitanOperationStatus titanStatus = getResult.right().value(); - log.debug("Node with id {} was not found in the graph. status: {}", propertyId, titanStatus); - StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); - return Either.right(storageOperationStatus); - } - - } - /* * (non-Javadoc) * @@ -2024,8 +2006,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } } - @Override - public Either addDataType(DataTypeDefinition dataTypeDefinition, boolean inTransaction) { + private Either addDataType(DataTypeDefinition dataTypeDefinition, boolean inTransaction) { Either result = null; @@ -2110,8 +2091,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return getDataTypeByNameWithoutDerived(name, true); } - @Override - public Either getDataTypeByNameWithoutDerived(String name, boolean inTransaction) { + private Either getDataTypeByNameWithoutDerived(String name, boolean inTransaction) { Either result = null; try { @@ -2534,8 +2514,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return updateDataType(newDataTypeDefinition, oldDataTypeDefinition, true); } - @Override - public Either updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition, boolean inTransaction) { + private Either updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition, boolean inTransaction) { Either result = null; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java deleted file mode 100644 index a2fe3d61d3..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java +++ /dev/null @@ -1,1419 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import com.thinkaurelius.titan.core.TitanTransaction; -import com.thinkaurelius.titan.core.TitanVertex; - -import org.apache.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.CapabiltyInstance; -import org.openecomp.sdc.be.model.Point; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.RequirementImplDef; -import org.openecomp.sdc.be.model.operations.api.IRequirementOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.resources.data.CapabilityData; -import org.openecomp.sdc.be.resources.data.CapabilityInstData; -import org.openecomp.sdc.be.resources.data.CapabilityTypeData; -import org.openecomp.sdc.be.resources.data.PropertyValueData; -import org.openecomp.sdc.be.resources.data.RequirementData; -import org.openecomp.sdc.be.resources.data.RequirementImplData; -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.springframework.stereotype.Component; - -import fj.data.Either; - -@Component("requirement-operation") -public class RequirementOperation implements IRequirementOperation { - - private static final String NA = "NA"; - - private static final String EQUAL_SIGN = "="; - - private static final String EMPTY_STRING = ""; - - public RequirementOperation() { - super(); - } - - private static Logger log = LoggerFactory.getLogger(RequirementOperation.class.getName()); - - @javax.annotation.Resource - private CapabilityOperation capabilityOperation; - - @javax.annotation.Resource - private CapabilityTypeOperation capabilityTypeOperation; - - @javax.annotation.Resource - private TitanGenericDao titanGenericDao; - - /** - * FOR TEST ONLY - * - * @param titanGenericDao - */ - public void setTitanGenericDao(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; - } - - protected CapabilityTypeDefinition convertCTDataToCTDefinition(CapabilityTypeData capabilityTypeData) { - log.debug("The object returned after create capability is {}", capabilityTypeData); - - CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition(capabilityTypeData.getCapabilityTypeDataDefinition()); - - return capabilityTypeDefResult; - } - - /** - * FOR TEST ONLY - * - * @param capabilityOperation - */ - public void setCapabilityOperation(CapabilityOperation capabilityOperation) { - this.capabilityOperation = capabilityOperation; - } - - public void setCapabilityTypeOperation(CapabilityTypeOperation capabilityTypeOperation) { - this.capabilityTypeOperation = capabilityTypeOperation; - } - - @Override - public Either addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId) { - - return addRequirementToResource(reqName, reqDefinition, resourceId, false); - } - - private Either associateRequirementToRelationshipType(RequirementData reqData, RequirementDefinition reqDefinition) { - - String relationship = reqDefinition.getRelationship(); - - if (relationship == null) { - log.debug("The provided relationship is null."); - return Either.right(TitanOperationStatus.NOT_FOUND); - } - UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.RelationshipType, relationship); - Either createRelation = titanGenericDao.createRelation(reqData, uniqueIdData, GraphEdgeLabels.RELATIONSHIP_TYPE, null); - - return createRelation; - - } - - /** - * Associate the requirement node to its capability type - * - * @param reqData - * @param reqDefinition - * @return - */ - private Either associateRequirementToCapabilityType(RequirementData reqData, RequirementDefinition reqDefinition) { - - String capability = reqDefinition.getCapability(); - - UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.CapabilityType, capability); - Either createRelation = titanGenericDao.createRelation(reqData, uniqueIdData, GraphEdgeLabels.CAPABILITY_TYPE, null); - - log.debug("After associating requirementData {} to capability {}. status is {}", reqData, capability, createRelation); - - return createRelation; - } - - private TitanOperationStatus associateRequirementToCapabilityType(TitanVertex reqData, RequirementDefinition reqDefinition) { - - String capability = reqDefinition.getCapability(); - - UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.CapabilityType, capability); - TitanOperationStatus createRelation = titanGenericDao.createEdge(reqData, uniqueIdData, GraphEdgeLabels.CAPABILITY_TYPE, null); - - log.debug("After associating requirementData {} to capability {}. status is {}", reqData, capability, createRelation); - - return createRelation; - } - - /** - * Associate requirement impl node to capability instance node - * - * @param reqImplData - * @param capabilityInstData - * @param capabilityName - * @return - */ - private Either associateRequirementImplToCapabilityInst(RequirementImplData reqImplData, CapabilityInstData capabilityInstData, String capabilityName) { - - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName); - - log.debug("Before associating requirement impl {} to capability instance {}", reqImplData, capabilityInstData); - Either createRelation = titanGenericDao.createRelation(reqImplData, capabilityInstData, GraphEdgeLabels.CAPABILITY_INST, props); - log.debug("After associating requirement impl {} to capability instance {}.status is {}", reqImplData, capabilityInstData, createRelation); - - return createRelation; - - } - - /** - * Add requirement node to graph - * - * @param resourceId - * @param reqName - * @param reqDefinition - * @return - */ - private Either addRequirementData(String resourceId, String reqName, RequirementDefinition reqDefinition) { - - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(resourceId); - - RequirementData requirementData = buildRequirementData(resourceId, reqName, reqDefinition); - - log.debug("Before adding requirement data to graph {}", requirementData); - Either createNodeResult = titanGenericDao.createNode(requirementData, RequirementData.class); - - log.debug("After adding requirement to graph {}", requirementData); - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add requirement {} [{}] to graph. status is {}", reqName, requirementData, operationStatus); - return Either.right(operationStatus); - } - - TitanOperationStatus status = associateResourceDataToRequirementData(resourceId, reqName, resourceData, requirementData); - if (status != TitanOperationStatus.OK) { - return Either.right(status); - } - - return Either.left(createNodeResult.left().value()); - - } - - private Either addRequirementData(TitanVertex vertex, String resourceId, String reqName, RequirementDefinition reqDefinition) { - - RequirementData requirementData = buildRequirementData(resourceId, reqName, reqDefinition); - - log.debug("Before adding requirement data to graph {}", requirementData); - Either createNodeResult = titanGenericDao.createNode(requirementData); - - log.debug("After adding requirement to graph {}", requirementData); - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add requirement {} [{}] to graph. status is {}", reqName, requirementData, operationStatus); - return Either.right(operationStatus); - } - - TitanOperationStatus status = associateResourceDataToRequirementData(resourceId, reqName, vertex, createNodeResult.left().value()); - if (!status.equals(TitanOperationStatus.OK)) { - return Either.right(status); - } - return Either.left(createNodeResult.left().value()); - } - - /** - * Asssociate resource node to requirement node with REQUIREMENT label and requirement name as property on the edge. - * - * @param resourceId - * @param reqName - * @param resourceData - * @param requirementData - * @return - */ - private TitanOperationStatus associateResourceDataToRequirementData(String resourceId, String reqName, ResourceMetadataData resourceData, RequirementData requirementData) { - - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), reqName); - Either createRelResult = titanGenericDao.createRelation(resourceData, requirementData, GraphEdgeLabels.REQUIREMENT, props); - log.debug("After creatin edge between resource {} to requirement {}", resourceId, requirementData); - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate resource {} to requirement {} [ {} ] in graph. status is {}", resourceId, reqName, requirementData, operationStatus); - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus associateResourceDataToRequirementData(String resourceId, String reqName, TitanVertex resourceVertex, TitanVertex requirementVertex) { - - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), reqName); - TitanOperationStatus createRelResult = titanGenericDao.createEdge(resourceVertex, requirementVertex, GraphEdgeLabels.REQUIREMENT, props); - log.debug("After creatin edge between resource {} to requirement {}", resourceId, requirementVertex); - if (!createRelResult.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate resource {} to requirement {} in graph. status is {}", resourceId, reqName, createRelResult); - } - return TitanOperationStatus.OK; - } - - private RequirementData buildRequirementData(String resourceId, String reqName, RequirementDefinition reqDefinition) { - - RequirementData requirementData = new RequirementData(); - requirementData.setNode(reqDefinition.getNode()); - requirementData.setUniqueId(UniqueIdBuilder.buildRequirementUid(resourceId, reqName)); - Long creationTime = System.currentTimeMillis(); - requirementData.setCreationTime(creationTime); - requirementData.setModificationTime(creationTime); - requirementData.setRelationshipType(reqDefinition.getRelationship()); - requirementData.setMinOccurrences(reqDefinition.getMinOccurrences()); - requirementData.setMaxOccurrences(reqDefinition.getMaxOccurrences()); - - return requirementData; - } - - /** - * build requirement impl node associate it to resource, requirement & implementation resource - * - * [RESOURCE] --> [REQUIREMENT IMPL] --> [ RESOURCE IMPL ] | V [REQUIREMENT] - * - * @param resourceLabel - * @param resourceId - * @param reqName - * @param requirementUid - * @param reqImplDefinition - * @return - */ - private Either addRequirementImplData(NodeTypeEnum resourceLabel, String resourceId, String reqName, String requirementUid, RequirementImplDef reqImplDefinition) { - - RequirementImplData requirementImplData = buildRequirementImplData(resourceId, reqName, reqImplDefinition); - - log.debug("Before adding requirement impl data to graph {}", requirementImplData); - Either createNodeResult = titanGenericDao.createNode(requirementImplData, RequirementImplData.class); - log.debug("After adding requirement to graph {}. status is {}", requirementImplData, createNodeResult); - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add requirement {} [ {} ] to graph. status is {}", reqName, requirementImplData, operationStatus); - return Either.right(operationStatus); - } - - Either createRelResult = associateReqImplRoResource(resourceLabel, resourceId, reqName, requirementImplData); - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate resource {} to requirement impl {} [ {} ] in graph. status is {}", resourceId, requirementImplData, requirementImplData, operationStatus); - return Either.right(operationStatus); - } - - Either associateToResourceImpl = associateReqImplToImplResource(requirementImplData, reqImplDefinition.getNodeId()); - if (associateToResourceImpl.isRight()) { - TitanOperationStatus operationStatus = associateToResourceImpl.right().value(); - log.error("Failed to associate requirement impl {} to resource impl {} [ {} ] in graph. status is {}", requirementImplData, reqImplDefinition.getNodeId(), requirementImplData, operationStatus); - return Either.right(operationStatus); - } - - Either associateToRequirement = associateReqImplToRequirement(requirementImplData, requirementUid); - if (associateToRequirement.isRight()) { - TitanOperationStatus operationStatus = associateToRequirement.right().value(); - log.error("Failed to associate requirement impl {} to requirement {} in graph. status is {}", requirementImplData, reqName, operationStatus); - return Either.right(operationStatus); - } - - return Either.left(createNodeResult.left().value()); - - } - - private RequirementImplData buildRequirementImplData(String resourceId, String reqName, RequirementImplDef reqImplDefinition) { - String reqImplUid = UniqueIdBuilder.buildRequirementImplUid(resourceId, reqName); - RequirementImplData requirementImplData = new RequirementImplData(); - requirementImplData.setName(reqName); - requirementImplData.setUniqueId(reqImplUid); - Long creationTime = System.currentTimeMillis(); - requirementImplData.setCreationTime(creationTime); - requirementImplData.setModificationTime(creationTime); - Point point = reqImplDefinition.getPoint(); - if (point != null) { - requirementImplData.setPosX(point.getX()); - requirementImplData.setPosY(point.getY()); - } - return requirementImplData; - } - - /** - * associate requirement impl node to the source requirement. The source requirement maybe belongs to one of parents. - * - * @param requirementImplData - * @param requirementUid - * @return - */ - private Either associateReqImplToRequirement(RequirementImplData requirementImplData, String requirementUid) { - - UniqueIdData to = new UniqueIdData(NodeTypeEnum.Requirement, requirementUid); - log.debug("Before creating edge between requirement impl {} to requirement {}", requirementImplData, requirementUid); - Either createRelResult = titanGenericDao.createRelation(requirementImplData, to, GraphEdgeLabels.IMPLEMENTATION_OF, null); - log.debug("Before creating edge between requirement impl {} to requirement {}. status is {}", requirementImplData, requirementUid, createRelResult); - - return createRelResult; - } - - /** - * Associate requirement impl node to the node which supply this requirement. - * - * @param requirementImplData - * @param nodeId - * @return - */ - private Either associateReqImplToImplResource(RequirementImplData requirementImplData, String nodeId) { - - UniqueIdData nodeImpl = new UniqueIdData(NodeTypeEnum.Resource, nodeId); - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), nodeId); - log.debug("Before creating edge between requirement impl {} to node impl {}", requirementImplData, nodeId); - Either createRelResult = titanGenericDao.createRelation(requirementImplData, nodeImpl, GraphEdgeLabels.NODE_IMPL, props); - log.debug("After creating edge between requirement {} to node impl {}. status is {}", requirementImplData, nodeId, createRelResult); - - return createRelResult; - } - - /** - * create an edge between the requirement impl node to the implementation resource. - * - * @param resourceLabel - * @param resourceId - * @param reqName - * @param requirementImplData - * @return - */ - private Either associateReqImplRoResource(NodeTypeEnum resourceLabel, String resourceId, String reqName, RequirementImplData requirementImplData) { - - UniqueIdData resource = new UniqueIdData(resourceLabel, resourceId); - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), reqName); - log.debug("Before creating edge between resource {} to requirement impl {}", resourceId, requirementImplData); - Either createRelResult = titanGenericDao.createRelation(resource, requirementImplData, GraphEdgeLabels.REQUIREMENT_IMPL, props); - log.debug("After creating edge between to requirement impl {} to resource {}. status is {}", requirementImplData, resource, createRelResult); - - return createRelResult; - } - - private void validateNodeExists(String node) { - // TODO Auto-generated method stub - - } - - @Override - public Either addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction) { - - Either result = null; - try { - - log.debug("Going to add requirement {} to resource {}. requirement definition is {}", reqName, resourceId, reqDefinition); - - validateNodeExists(reqDefinition.getNode()); - - // 1. add requirement node in graph and associate it to the resource - log.debug("Going to add requirement node in graph and associate it to the resource"); - Either addRequirementData = addRequirementData(resourceId, reqName, reqDefinition); - if (addRequirementData.isRight()) { - log.error("Failed to add requirement {} node to graph. status is {}", reqName, addRequirementData); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addRequirementData.right().value())); - return result; - } - - RequirementData requirementData = addRequirementData.left().value(); - - log.debug("Going to associate the requirement to the appriopriate capability type"); - Either associateReqToCapabilityType = associateRequirementToCapabilityType(requirementData, reqDefinition); - if (associateReqToCapabilityType.isRight()) { - log.error("Failed to associate requirement data node {} to the capability type node {}", requirementData, reqDefinition.getCapability()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateReqToCapabilityType.right().value())); - return result; - } - - // TODO: esofer associate requirement to the relationship type - /* - * Either associateReqToRelshipType = associateRequirementToRelationshipType( requirementData, reqDefinition); - * - * if (associateReqToRelshipType.isRight() && associateReqToRelshipType.right().value() != TitanOperationStatus.NOT_FOUND) { log.error("Failed to associate requirement data node " + requirementData + " to the relationship type node " + - * reqDefinition.getRelationship()); result = Either .right(TitanStatusConverter .convertTitanStatusToStorageStatus(associateReqToRelshipType .right().value())); return result; } - */ - - log.debug("Going to fetch the requirement {} from graph", reqName); - Either requirementDefinitionRes = getRequirement(requirementData.getUniqueId()); - if (requirementDefinitionRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(requirementDefinitionRes.right().value())); - return result; - } - - result = Either.left(requirementDefinitionRes.left().value()); - - 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 StorageOperationStatus addRequirementToResource(TitanVertex metadataVertex, String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction) { - - StorageOperationStatus result = StorageOperationStatus.OK; - try { - - log.debug("Going to add requirement {} to resource . requirement definition is ", reqName, resourceId, reqDefinition); - - validateNodeExists(reqDefinition.getNode()); - - // 1. add requirement node in graph and associate it to the resource - log.debug("Going to add requirement node in graph and associate it to the resource"); - Either addRequirementData = addRequirementData(metadataVertex, resourceId, reqName, reqDefinition); - if (addRequirementData.isRight()) { - log.error("Failed to add requirement {} node to graph. status is {}", reqName, addRequirementData.right().value()); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(addRequirementData.right().value()); - return result; - } - - log.debug("Going to associate the requirement to the appriopriate capability type"); - TitanOperationStatus associateReqToCapabilityType = associateRequirementToCapabilityType(addRequirementData.left().value(), reqDefinition); - if (!associateReqToCapabilityType.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate requirement data node {} to the capability type node {}", reqDefinition.getCapability(), reqDefinition); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(associateReqToCapabilityType); - return result; - } - return result; - - } finally { - if (false == inTransaction) { - if (result == null || !result.equals(TitanOperationStatus.OK)) { - log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - /** - * Fetch requirement from graph - * - * @param uniqueId - * - the uniqueid of the requirement in the graph - * @return - */ - public Either getRequirement(String uniqueId) { - - log.debug("Going to fetch the requirement {} from graph.", uniqueId); - Either reqDataResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), uniqueId, RequirementData.class); - - if (reqDataResult.isRight()) { - log.error("Failed to find requirement node in graph {}. status is {}", uniqueId, reqDataResult); - return Either.right(reqDataResult.right().value()); - } - - log.debug("Going to fetch the capability type associate to requirement {}", uniqueId); - Either, TitanOperationStatus> capabilityTypeRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.CAPABILITY_TYPE, NodeTypeEnum.CapabilityType, - CapabilityTypeData.class); - - if (capabilityTypeRes.isRight()) { - log.error("Cannot find the capability of a given requirement {}. status is {}", uniqueId, capabilityTypeRes); - return Either.right(capabilityTypeRes.right().value()); - } - - ImmutablePair capability = capabilityTypeRes.left().value(); - - String capabilityType = capability.getKey().getCapabilityTypeDataDefinition().getType(); - - // TODO: esofer add relationship as edge - /* - * Either>, TitanOperationStatus> relationshipRes = titanGenericDao .getChildrenNodes( GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.RELATIONSHIP_TYPE, - * NodeTypeEnum.RelationshipType, RelationshipTypeData.class); - * - * if (relationshipRes.isRight() && relationshipRes.right().value() != TitanOperationStatus.NOT_FOUND) { - * return Either.right(relationshipRes.right().value()); } - * - * String relationshipType = null; if (relationshipRes.isLeft()) { List> rstPairs = relationshipRes .left().value(); if (rstPairs == null || true == rstPairs.isEmpty()) { log.error( - * "Cannot find the capability of a given requirement " + uniqueId); return Either.right(TitanOperationStatus.NOT_FOUND); } - * - * ImmutablePair relationship = rstPairs .get(0); relationshipType = relationship.getKey().getType(); } - */ - - log.debug("Going to fetch the capability type associate to requirement {}", uniqueId); - Either, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.REQUIREMENT, NodeTypeEnum.Resource, - ResourceMetadataData.class); - if (parentNode.isRight()) { - log.error("Cannot find the parent resource for a given requirement {}. status is {}", uniqueId, parentNode.right().value()); - return Either.right(parentNode.right().value()); - } - - RequirementData requirementData = reqDataResult.left().value(); - - RequirementDefinition requirementDefinition = new RequirementDefinition(); - requirementDefinition.setOwnerId(parentNode.left().value().getLeft().getMetadataDataDefinition().getUniqueId()); - requirementDefinition.setNode(requirementData.getNode()); - requirementDefinition.setUniqueId(requirementData.getUniqueId()); - requirementDefinition.setCapability(capabilityType); - requirementDefinition.setRelationship(requirementData.getRelationshipType()); - requirementDefinition.setMinOccurrences(requirementData.getMinOccurrences()); - requirementDefinition.setMaxOccurrences(requirementData.getMaxOccurrences()); - - return Either.left(requirementDefinition); - - } - - @Override - public Either getRequirementOfResource(String reqName, String resourceId) { - - return getRequirementOfResource(reqName, resourceId, false); - } - - @Override - public Either getRequirementOfResource(String reqName, String resourceId, boolean inTransaction) { - - Either result = null; - - try { - String reqUniqueId = UniqueIdBuilder.buildRequirementUid(resourceId, reqName); - Either requirementRes = getRequirement(reqUniqueId); - - if (requirementRes.isRight()) { - log.debug("Failed to retrieve requirement {} associated to resource {}", reqName, resourceId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(requirementRes.right().value())); - } else { - result = Either.left(requirementRes.left().value()); - } - - 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 addRequirementImplToResource(String reqName, RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId) { - - return addRequirementImplToResource(reqName, reqDefinition, resourceId, parentReqUniqueId, false); - - } - - @Override - public Either addRequirementImplToResource(String reqName, RequirementImplDef reqImplDefinition, String resourceId, String parentReqUniqueId, boolean inTransaction) { - - Either result = null; - - try { - - // find the requirement defined at the resource itself or under one - // of its parents - Either findReq = getRequirement(parentReqUniqueId); - log.debug("After looking for requirement {}. status is {}", parentReqUniqueId, findReq); - if (findReq.isRight()) { - TitanOperationStatus status = findReq.right().value(); - log.error("The requirment {} was not found in the graph. status is {}", parentReqUniqueId, findReq.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - RequirementDefinition reqDefinition = findReq.left().value(); - String reqNode = reqDefinition.getNode(); - String reqCapability = reqDefinition.getCapability(); - - String nodeIdImpl = reqImplDefinition.getNodeId(); - - checkNodeIdImplementsRequirementNode(nodeIdImpl, reqNode); - - Either addRequirementImplData = addRequirementImplData(NodeTypeEnum.Resource, resourceId, reqName, parentReqUniqueId, reqImplDefinition); - - if (addRequirementImplData.isRight()) { - TitanOperationStatus status = addRequirementImplData.right().value(); - log.error("Failed to add requirement data impl node in the graph. status is {}", addRequirementImplData.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - RequirementImplData requirementImplData = addRequirementImplData.left().value(); - - log.debug("Add the properties of the capabilities of the target node {} to the requirement impl node {} in graph.", nodeIdImpl, requirementImplData.getUniqueId()); - Map requirementPropertiesPerCapability = reqImplDefinition.getRequirementProperties(); - TitanOperationStatus addPropsResult = addCapabilityPropertiesToReqImpl(requirementImplData, reqCapability, nodeIdImpl, requirementPropertiesPerCapability); - - if (addPropsResult != TitanOperationStatus.OK) { - log.error("Failed to add capabilities properties to Requirement impl {}", requirementImplData); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropsResult)); - return result; - } - - result = Either.left(reqDefinition); - - } 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; - } - - private Either getRequirementImplOfResource(String reqName, String resourceId) { - - RequirementImplDef requirementImplDef = new RequirementImplDef(); - - Either>, TitanOperationStatus> reqImplNodesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.REQUIREMENT_IMPL, - NodeTypeEnum.RequirementImpl, RequirementImplData.class); - log.debug("After looking for requirement impl edge of resource {}", resourceId); - if (reqImplNodesRes.isRight()) { - TitanOperationStatus status = reqImplNodesRes.right().value(); - return Either.right(status); - } - - boolean found = false; - List> reqImplNodes = reqImplNodesRes.left().value(); - for (ImmutablePair entry : reqImplNodes) { - GraphEdge graphEdge = entry.getValue(); - String edgeType = (String) graphEdge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty()); - if (reqName.equals(edgeType)) { - found = true; - RequirementImplData requirementImplData = entry.getKey(); - - requirementImplDef.setUniqueId(requirementImplData.getUniqueId()); - - Either, TitanOperationStatus> nodeImplRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RequirementImpl), requirementImplData.getUniqueId(), - GraphEdgeLabels.NODE_IMPL, NodeTypeEnum.Resource, ResourceMetadataData.class); - - if (nodeImplRes.isRight()) { - TitanOperationStatus status = nodeImplRes.right().value(); - log.debug("No implementation resource was found under requirement impl {}. status is {}", requirementImplData.getUniqueId(), status); - - return Either.right(status); - } - String nodeImpl = nodeImplRes.left().value().getKey().getMetadataDataDefinition().getUniqueId(); - requirementImplDef.setNodeId(nodeImpl); - - String posX = requirementImplData.getPosX(); - String posY = requirementImplData.getPosY(); - if (posX != null && posY != null) { - Point point = new Point(posX, posY); - requirementImplDef.setPoint(point); - } - - Either>, TitanOperationStatus> capaInstDataRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RequirementImpl), requirementImplData.getUniqueId(), - GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class); - if (capaInstDataRes.isRight()) { - TitanOperationStatus status = capaInstDataRes.right().value(); - log.debug("No capability instance was found under requirement impl {}. status is {}", requirementImplData.getUniqueId(), status); - - return Either.right(status); - } - - Map requirementProperties = new HashMap(); - - List> list = capaInstDataRes.left().value(); - for (ImmutablePair capabilityInst : list) { - CapabilityInstData capabilityInstData = capabilityInst.getKey(); - GraphEdge edge = capabilityInst.getValue(); - Map properties = edge.getProperties(); - if (properties == null) { - log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), edge); - return Either.right(TitanOperationStatus.INVALID_ELEMENT); - } - String capabilityName = (String) properties.get(GraphPropertiesDictionary.NAME.getProperty()); - if (capabilityName == null) { - log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), edge); - return Either.right(TitanOperationStatus.INVALID_ELEMENT); - } - - // List keyValuePropertiesList = capabilityInstData - // .getProperties(); - // Map actualValues = new HashMap(); - // fillMapFromKeyValueList(keyValuePropertiesList, - // actualValues); - CapabiltyInstance capabiltyInstance = new CapabiltyInstance(); - capabiltyInstance.setUniqueId(capabilityInstData.getUniqueId()); - // capabiltyInstance.setProperties(actualValues); - requirementProperties.put(capabilityName, capabiltyInstance); - - Either>, TitanOperationStatus> propertyValueNodesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), - capabilityInstData.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class); - - if (propertyValueNodesRes.isRight()) { - TitanOperationStatus status = propertyValueNodesRes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find the property values of capability instance {}. status is {}", capabilityInstData, status); - return Either.right(status); - } - } else { - List> propertyValueNodes = propertyValueNodesRes.left().value(); - - if (propertyValueNodes != null) { - - Map actualValues = new HashMap(); - TitanOperationStatus fillPropertiesResult = fillPropertiesMapFromNodes(propertyValueNodes, actualValues); - - if (fillPropertiesResult != TitanOperationStatus.OK) { - log.error("Failed to fetch properties of capability {}", capabilityName); - return Either.right(fillPropertiesResult); - } - - if (false == actualValues.isEmpty()) { - capabiltyInstance.setProperties(actualValues); - } - } - } - - } - - requirementImplDef.setRequirementProperties(requirementProperties); - - break; - } else { - continue; - } - } - - if (false == found) { - log.debug("Cannot find requirement impl under resource {}", resourceId); - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - return Either.left(requirementImplDef); - } - - private void fillMapFromKeyValueList(List keyValuePropertiesList, Map actualValues) { - - if (keyValuePropertiesList != null) { - for (String keyValue : keyValuePropertiesList) { - int equalSignLocation = keyValue.indexOf(EQUAL_SIGN); - if (equalSignLocation > -1) { - String key = keyValue.substring(0, equalSignLocation); - String value = EMPTY_STRING; - if (equalSignLocation + 1 < keyValue.length()) { - value = keyValue.substring(equalSignLocation + 1); - } - actualValues.put(key, value); - } - } - } - - } - - private TitanOperationStatus fillPropertiesMapFromNodes(List> propertyValueNodes, Map actualValues) { - if (propertyValueNodes != null) { - for (ImmutablePair propertyValuePair : propertyValueNodes) { - PropertyValueData propertyValueData = propertyValuePair.getKey(); - GraphEdge propertyValueEdge = propertyValuePair.getValue(); - Map propertyEdgeProps = propertyValueEdge.getProperties(); - if (propertyEdgeProps == null) { - log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), propertyValueEdge); - return TitanOperationStatus.INVALID_ELEMENT; - } - String paramName = (String) propertyEdgeProps.get(GraphPropertiesDictionary.NAME.getProperty()); - if (paramName == null) { - log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), propertyValueEdge); - return TitanOperationStatus.INVALID_ELEMENT; - } - actualValues.put(paramName, propertyValueData.getValue()); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus addCapabilityPropertiesToReqImpl(RequirementImplData reqImplData, String reqCapability, String nodeIdImpl, Map propertiesValuePerCapability) { - - TitanOperationStatus result = null; - - Either>, TitanOperationStatus> allCapabilities = capabilityOperation.getAllCapabilitiesPairs(nodeIdImpl); - log.trace("Atter looking for the capabilities of resource {}. result is {}", nodeIdImpl, allCapabilities); - if (allCapabilities.isRight()) { - TitanOperationStatus status = allCapabilities.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find capabilities of resource {}. status is {}", nodeIdImpl, status); - return status; - } - } else { - - List> capabilitiesValue = allCapabilities.left().value(); - checkImplNodeContainsReqCapability(reqCapability, capabilitiesValue); - - for (ImmutablePair entry : capabilitiesValue) { - - CapabilityData capabilityData = entry.getKey(); - - GraphEdge graphEdge = entry.getValue(); - - Either capabilityNameResult = findCapabilityName(capabilityData, graphEdge); - - if (capabilityNameResult.isRight()) { - TitanOperationStatus status = capabilityNameResult.right().value(); - log.error("Failed to find capability name from the edge associated to capability {}", capabilityData); - return status; - } - - String capabilityName = capabilityNameResult.left().value(); - log.debug("Going to set properties of capability {}", capabilityName); - String cabilityDataUid = capabilityData.getUniqueId(); - - Either ctDataResult = capabilityOperation.getCapabilityTypeOfCapability(cabilityDataUid); - - if (ctDataResult.isRight()) { - log.error("Cannot find capability type of capbility {}. status is {}", cabilityDataUid, ctDataResult); - TitanOperationStatus status = ctDataResult.right().value(); - return status; - } - - CapabilityTypeData capabilityTypeData = ctDataResult.left().value(); - - Either, TitanOperationStatus> propertiesStatus = findPropertiesOfCapability(capabilityTypeData); - if (propertiesStatus.isRight()) { - TitanOperationStatus status = propertiesStatus.right().value(); - log.error("Failed to fetch properties definitions from capability. status is {}", status); - return status; - } - - Map properties = propertiesStatus.left().value(); - - CapabiltyInstance capabiltyInstance = null; - if (propertiesValuePerCapability != null) { - capabiltyInstance = propertiesValuePerCapability.get(capabilityName); - } - - Either createCapabilityInstanceNode = createCapabilityInstanceNode(capabilityName, reqImplData); - if (createCapabilityInstanceNode.isRight()) { - TitanOperationStatus status = createCapabilityInstanceNode.right().value(); - log.error("Failed to create capability instance node ({}) in graph. status is {}", capabilityName, status); - - return status; - } - CapabilityInstData capabilityInstData = createCapabilityInstanceNode.left().value(); - - Either, TitanOperationStatus> instanceProperties = addPropertiesToCapabilityInstance(properties, capabiltyInstance, capabilityInstData); - - if (instanceProperties.isRight()) { - TitanOperationStatus status = instanceProperties.right().value(); - log.debug("Failed to add properties to capability instance. status is {}", status); - return status; - } - - Either associateCapabilityInstToCapabilityType = associateCapabilityInstToCapabilityType(capabilityInstData, capabilityTypeData); - if (associateCapabilityInstToCapabilityType.isRight()) { - TitanOperationStatus status = associateCapabilityInstToCapabilityType.right().value(); - log.error("Failed to associate capability instance {} to capability type node {} in graph. status is {}", capabilityInstData, capabilityTypeData, status); - - return status; - } - - Either associateCapabilityInst = associateRequirementImplToCapabilityInst(reqImplData, capabilityInstData, capabilityName); - if (associateCapabilityInst.isRight()) { - TitanOperationStatus status = associateCapabilityInst.right().value(); - log.error("Failed to associate requirement impl {} to capability instance node {} of capability {}) in graph. status is {}", reqImplData, capabilityInstData, capabilityName, status); - - return status; - } - - } - result = TitanOperationStatus.OK; - } - return result; - } - - private Either, TitanOperationStatus> findPropertiesOfCapability(CapabilityTypeData capabilityTypeData) { - String capabilityTypeUid = capabilityTypeData.getUniqueId(); - - Either capabilityTypeResult = capabilityTypeOperation.getCapabilityTypeByUid(capabilityTypeUid); - - if (capabilityTypeResult.isRight()) { - log.error("Failed to find capabilityType {} in the graph. status is {}", capabilityTypeUid, capabilityTypeResult); - return Either.right(capabilityTypeResult.right().value()); - } - - CapabilityTypeDefinition capabilityTypeDef = capabilityTypeResult.left().value(); - Map properties = capabilityTypeDef.getProperties(); - - return Either.left(properties); - } - - private Either findCapabilityName(CapabilityData capabilityData, GraphEdge graphEdge) { - Map edgeProps = graphEdge.getProperties(); - String capabilityName = (String) edgeProps.get(GraphPropertiesDictionary.NAME.getProperty()); - - if (capabilityName == null) { - log.debug("Cannot find the name of the capability associated to node {}", capabilityData); - return Either.right(TitanOperationStatus.NOT_FOUND); - } - return Either.left(capabilityName); - } - - private Either associateCapabilityInstToCapabilityType(CapabilityInstData capabilityInstData, CapabilityTypeData capabilityTypeData) { - - Either createRelation = titanGenericDao.createRelation(capabilityInstData, capabilityTypeData, GraphEdgeLabels.INSTANCE_OF, null); - - return createRelation; - - } - - /** - * add property value node with default value of override value and associate it to the capability instance node - * - * @param properties - * - properties definition. old also default value - * @param capabilityInstance - * - hold also properties new value(if exists) - * @param capabilityInstData - * - the graph node which we associate the properties value node to. - * @return - */ - private Either, TitanOperationStatus> addPropertiesToCapabilityInstance(Map properties, CapabiltyInstance capabilityInstance, CapabilityInstData capabilityInstData) { - - List relationsResult = new ArrayList(); - - if (properties != null) { - for (Entry entry : properties.entrySet()) { - - String paramName = entry.getKey(); - - PropertyDefinition propertyDefinition = entry.getValue(); - - String propertyValue = setPropertyValue(capabilityInstance, paramName, propertyDefinition); - - PropertyValueData propertyValueData = buildPropertyValueData(capabilityInstData.getUniqueId(), paramName, propertyValue); - - log.debug("Before creating property value data node {} in graph.", propertyValueData); - Either createNode = titanGenericDao.createNode(propertyValueData, PropertyValueData.class); - log.debug("Before creating property value data node {} in graph. status is {}", propertyValueData, createNode); - if (createNode.isRight()) { - TitanOperationStatus status = createNode.right().value(); - log.error("Failed to create property value node in graph {}. status is {}", propertyValueData, status); - return Either.right(status); - } - - PropertyValueData propertyValueDataCreated = createNode.left().value(); - - Either createRelation = associateCapabilityInstToPropertyValue(capabilityInstData, paramName, propertyValueDataCreated); - - if (createRelation.isRight()) { - TitanOperationStatus status = createNode.right().value(); - log.error("Failed to create relation between capability instance {} to property value {} in graph. status is {}", capabilityInstData.getUniqueId(), propertyValueDataCreated.getUniqueId(), status); - return Either.right(status); - } - - relationsResult.add(createRelation.left().value()); - - } - } - - return Either.left(relationsResult); - } - - private Either associateCapabilityInstToPropertyValue(CapabilityInstData capabilityInstData, String paramName, PropertyValueData propertyValueDataCreated) { - - Map edgeProps = new HashMap(); - edgeProps.put(GraphPropertiesDictionary.NAME.getProperty(), paramName); - log.debug("Begin creating relation between capability instance {} to property value {} in graph.", capabilityInstData, propertyValueDataCreated); - Either createRelation = titanGenericDao.createRelation(capabilityInstData, propertyValueDataCreated, GraphEdgeLabels.PROPERTY_VALUE, edgeProps); - log.debug("After creating relation between capability instance {} to property value {} in graph. status is {}", capabilityInstData, propertyValueDataCreated, createRelation); - - return createRelation; - } - - private String setPropertyValue(CapabiltyInstance capabilityInstance, String paramName, PropertyDefinition propertyDefinition) { - String propertyValue = NA; - if (propertyDefinition.getDefaultValue() != null) { - propertyValue = propertyDefinition.getDefaultValue(); - } - Map propertiesValue = null; - if (capabilityInstance != null) { - propertiesValue = capabilityInstance.getProperties(); - if (propertiesValue != null) { - String tmpValue = propertiesValue.get(paramName); - if (tmpValue != null) { - propertyValue = tmpValue; - } - } - } - return propertyValue; - } - - private String buildPropertykeyValue(String paramName, String paramValue) { - return paramName + EQUAL_SIGN + paramValue; - } - - private PropertyValueData buildPropertyValueData(String capabilityInstDataUid, String paramName, String propertyValue) { - PropertyValueData propertyValueData = new PropertyValueData(); - propertyValueData.setValue(propertyValue); - String uid = UniqueIdBuilder.buildPropertyValueUniqueId(capabilityInstDataUid, paramName); - propertyValueData.setUniqueId(uid); - Long creationDate = System.currentTimeMillis(); - propertyValueData.setCreationTime(creationDate); - propertyValueData.setModificationTime(creationDate); - return propertyValueData; - } - - private Either createCapabilityInstanceNode(String capabilityName, RequirementImplData reqImplData) { - - CapabilityInstData capabilityInstData = new CapabilityInstData(); - String uniqueId = UniqueIdBuilder.buildCapabilityInstanceUid(reqImplData.getUniqueId(), capabilityName); - - capabilityInstData.setUniqueId(uniqueId); - // capabilityInstData.setProperties(instanceProperties); - Long creationDate = System.currentTimeMillis(); - capabilityInstData.setCreationTime(creationDate); - capabilityInstData.setModificationTime(creationDate); - - log.debug("Before creating capability instance node in graph {}", capabilityInstData); - Either createNode = titanGenericDao.createNode(capabilityInstData, CapabilityInstData.class); - log.debug("After creating capability instance node in graph {}. status is {}", capabilityInstData, createNode); - - return createNode; - } - - private void checkNodeIdImplementsRequirementNode(String nodeIdImpl, String reqNode) { - // TODO Auto-generated method stub - - } - - private void checkImplNodeContainsReqCapability(String reqCapability, List> capabilitiesValue) { - // TODO Auto-generated method stub - - } - - public Either>, StorageOperationStatus> getAllRequirementsOfResourceOnly(String resourceId, boolean inTransaction) { - - Either>, StorageOperationStatus> result = null; - - try { - - Map requirements = new HashMap(); - Set caseInsensitiveReqNames = new HashSet<>(); - TitanOperationStatus status = findAllRequirementsNonRecursive(resourceId, requirements, caseInsensitiveReqNames); - - if (status != TitanOperationStatus.OK) { - log.error("Failed to get all requirements of resource {}. status is {}", resourceId, status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } else { - // TODO handle requirementImpl - result = Either.left(convertRequirementMap(requirements, null, null)); - } - 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, TitanOperationStatus> getResourceRequirements(String resourceId) { - - Either, TitanOperationStatus> result = null; - - Map requirements = new HashMap(); - Set caseInsensitiveReqNames = new HashSet<>(); - - TitanOperationStatus status = findAllRequirementsRecursively(resourceId, requirements, caseInsensitiveReqNames); - if (status != TitanOperationStatus.OK) { - log.error("Failed to get all requirements of resource {}. status is {}", resourceId, status); - return Either.right(status); - } else { - log.debug("The requirements returned for resource {} are {}", resourceId, requirements); - - if (requirements != null) { - for (Entry entry : requirements.entrySet()) { - String reqName = entry.getKey(); - Either reqImplRes = this.getRequirementImplOfResource(reqName, resourceId); - if (reqImplRes.isRight()) { - - TitanOperationStatus reqImplResStatus = reqImplRes.right().value(); - if (reqImplResStatus == TitanOperationStatus.NOT_FOUND) { - log.debug("Cannot find implementation of requirement {} under resource {}", reqName, resourceId); - } else { - log.error("Cannot find implementation of requirement {} under resource {}", reqName, resourceId); - return Either.right(reqImplResStatus); - } - } else { - RequirementDefinition requirementDefinition = entry.getValue(); - // RequirementImplDef requirementImplDef = - // reqImplRes.left().value(); - // requirementDefinition.setRequirementImpl(requirementImplDef); - } - } - } - log.debug("The requirements returned for resource {} after fetching requirement impl are {}", resourceId, requirements); - - result = Either.left(requirements); - - return result; - } - - } - - @Override - public Either, StorageOperationStatus> getAllResourceRequirements(String resourceId, boolean inTransaction) { - - Either, StorageOperationStatus> result = null; - - try { - - Either, TitanOperationStatus> internalResult = getResourceRequirements(resourceId); - if (internalResult.isRight()) { - TitanOperationStatus status = internalResult.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to fetch requirements of resource {} . status is {}", resourceId, status); - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - Map value = internalResult.left().value(); - - result = Either.left(value); - 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(); - } - } - } - - } - - public Either, StorageOperationStatus> getAllResourceRequirements(String resourceId) { - - return getAllResourceRequirements(resourceId, false); - - } - - public TitanOperationStatus findAllRequirementsRecursively(String resourceId, Map requirements, Set caseInsensitiveReqNames) { - - TitanOperationStatus nonRecursiveResult = findAllRequirementsNonRecursive(resourceId, requirements, caseInsensitiveReqNames); - if (!nonRecursiveResult.equals(TitanOperationStatus.OK) && !nonRecursiveResult.equals(TitanOperationStatus.NOT_FOUND)) { - return nonRecursiveResult; - } - - Either, 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 requirements"); - return TitanOperationStatus.OK; - } else { - log.error("Failed to find parent requirements of resource {} . status is {}", resourceId, parentNodesStatus); - return parentNodesStatus; - } - } - ImmutablePair parnetNodePair = parentNodes.left().value(); - String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - TitanOperationStatus addParentReqStatus = findAllRequirementsRecursively(parentUniqueId, requirements, caseInsensitiveReqNames); - - if (addParentReqStatus != TitanOperationStatus.OK) { - log.error("Failed to fetch all requirements of resource {}", parentUniqueId); - return addParentReqStatus; - } - - return TitanOperationStatus.OK; - } - - private TitanOperationStatus findAllRequirementsNonRecursive(String resourceId, Map requirements, Set caseInsensitiveReqNames) { - Either>, TitanOperationStatus> requirementNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.REQUIREMENT, - NodeTypeEnum.Requirement, RequirementData.class); - - if (requirementNodes.isRight()) { - TitanOperationStatus status = requirementNodes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - return status; - } - } else { - List> requirementList = requirementNodes.left().value(); - if (requirementList != null) { - for (ImmutablePair requirementPair : requirementList) { - String reqUniqueId = requirementPair.getKey().getUniqueId(); - Map edgeProps = requirementPair.getValue().getProperties(); - String reqName = null; - if (edgeProps != null) { - reqName = (String) edgeProps.get(GraphPropertiesDictionary.NAME.getProperty()); - if (reqName == null) { - log.error("The requirement name is missing on the edge of requirement {}", reqUniqueId); - return TitanOperationStatus.INVALID_ELEMENT; - } - } else { - log.error("The requirement name is missing on the edge of requirement {}", reqUniqueId); - return TitanOperationStatus.INVALID_ELEMENT; - } - Either requirementDefRes = this.getRequirement(reqUniqueId); - if (requirementDefRes.isRight()) { - TitanOperationStatus status = requirementDefRes.right().value(); - log.error("Failed to get requirement properties of requirement {}", reqUniqueId); - return status; - } - - RequirementDefinition requirementDefinition = requirementDefRes.left().value(); - requirementDefinition.setName(reqName); - // US631462 - if (caseInsensitiveReqNames.contains(reqName.toLowerCase())) { - log.debug("The requirement {} was already defined in derived resource (case insensitive). Ignore {} from resource {}", reqName, reqName, resourceId); - } else { - requirements.put(reqName, requirementDefinition); - caseInsensitiveReqNames.add(reqName.toLowerCase()); - } - - } - } - } - return TitanOperationStatus.OK; - } - - public StorageOperationStatus deleteRequirementFromGraph(String requirementId) { - log.debug("Before deleting requirement from graph {}", requirementId); - Either deleteNodeStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementId, RequirementData.class); - if (deleteNodeStatus.isRight()) { - log.error("failed to delete requirement with id {}. status={}", requirementId, deleteNodeStatus.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteNodeStatus.right().value()); - } - return StorageOperationStatus.OK; - } - - public Either, StorageOperationStatus> deleteAllRequirements(String resourceId) { - - return getAllResourceRequirements(resourceId, false); - - } - - public Either, StorageOperationStatus> deleteAllRequirements(String resourceId, boolean inTransaction) { - - Either, StorageOperationStatus> result = null; - - try { - Either, TitanOperationStatus> deleteAllRes = deleteAllRequirementsOfResource(resourceId); - if (deleteAllRes.isRight()) { - TitanOperationStatus status = deleteAllRes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to delete requirements of resource {}. status is {}", resourceId, status); - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - Map value = deleteAllRes.left().value(); - result = Either.left(value); - - 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, TitanOperationStatus> deleteAllRequirementsOfResource(String resourceId) { - - Map requirements = new HashMap(); - Set caseInsensitiveReqNames = new HashSet<>(); - TitanOperationStatus requirementsRes = findAllRequirementsNonRecursive(resourceId, requirements, caseInsensitiveReqNames); - if (requirementsRes != TitanOperationStatus.OK) { - return Either.right(requirementsRes); - } - - if (requirements.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - for (Entry entry : requirements.entrySet()) { - RequirementDefinition requirementDefinition = entry.getValue(); - - String requirementUid = requirementDefinition.getUniqueId(); - - Either deleteNodeRes = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementUid, RequirementData.class); - if (deleteNodeRes.isRight()) { - TitanOperationStatus status = deleteNodeRes.right().value(); - log.error("Failed to delete requirement {} of resource ", requirementUid, resourceId); - return Either.right(status); - } - } - - return Either.left(requirements); - - } - - public Map> convertRequirementMap(Map requirementMap, String ownerId, String ownerName) { - - Map> typeToRequirementMap = new HashMap>(); - requirementMap.forEach((reqName, requirement) -> { - // requirement.setOwnerId(ownerId); - // requirement.setOwnerName(ownerName); - if (typeToRequirementMap.containsKey(requirement.getCapability())) { - typeToRequirementMap.get(requirement.getCapability()).add(requirement); - } else { - List list = new ArrayList(); - list.add(requirement); - typeToRequirementMap.put(requirement.getCapability(), list); - } - }); - return typeToRequirementMap; - } - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java deleted file mode 100644 index 2cc78eade2..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java +++ /dev/null @@ -1,3040 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; -import fj.data.Either; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; -import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; -import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint; -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.components.ResourceMetadataDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.cache.ComponentCache; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.category.SubCategoryDefinition; -import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation; -import org.openecomp.sdc.be.model.operations.api.IArtifactOperation; -import org.openecomp.sdc.be.model.operations.api.IAttributeOperation; -import org.openecomp.sdc.be.model.operations.api.IElementOperation; -import org.openecomp.sdc.be.model.operations.api.IResourceOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.migration.MigrationMalformedDataLogger; -import org.openecomp.sdc.be.model.operations.utils.GraphDeleteUtil; -import org.openecomp.sdc.be.resources.data.ComponentMetadataData; -import org.openecomp.sdc.be.resources.data.PropertyData; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import org.openecomp.sdc.be.resources.data.TagData; -import org.openecomp.sdc.be.resources.data.UniqueIdData; -import org.openecomp.sdc.be.resources.data.UserData; -import org.openecomp.sdc.be.resources.data.category.CategoryData; -import org.openecomp.sdc.be.resources.data.category.SubCategoryData; -import org.openecomp.sdc.common.api.ArtifactTypeEnum; -import org.openecomp.sdc.common.datastructure.Wrapper; -import org.openecomp.sdc.common.util.PairUtils; -import org.openecomp.sdc.common.util.ValidationUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.function.Predicate; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -@org.springframework.stereotype.Component("resource-operation") -@Deprecated -public class ResourceOperation extends ComponentOperation implements IResourceOperation { - - public ResourceOperation() { - super(); - } - - private static Logger log = LoggerFactory.getLogger(ResourceOperation.class.getName()); - - @javax.annotation.Resource - private PropertyOperation propertyOperation; - - @javax.annotation.Resource - private IAttributeOperation attributeOperation; - - @javax.annotation.Resource - private RequirementOperation requirementOperation; - - @javax.annotation.Resource - private CapabilityOperation capabilityOperation; - - @javax.annotation.Resource - private InterfaceLifecycleOperation interfaceLifecycleOperation; - - @javax.annotation.Resource - private IElementOperation elementOperation; - - @javax.annotation.Resource - private IAdditionalInformationOperation addioAdditionalInformationOperation; - - @javax.annotation.Resource - private GroupOperation groupOperation; - - @javax.annotation.Resource - private ComponentCache componentCache; - - private Gson prettyJson = new GsonBuilder().setPrettyPrinting().create(); - - private GraphDeleteUtil graphDeleteUtil = new GraphDeleteUtil(); - - public static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1"); - public static Pattern uuidNormativeNewVersion = Pattern.compile("^\\d{1,}.0"); - - @Override - public Either createResource(Resource resource) { - return createResource(resource, false); - } - - @Override - public Either createResource(Resource resource, boolean inTransaction) { - - Either result = null; - - try { - generateUUID(resource); - - ResourceMetadataData resourceData = getResourceMetaDataFromResource(resource); - String resourceUniqueId = resource.getUniqueId(); - if (resourceUniqueId == null) { - resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId(); - resourceData.getMetadataDataDefinition().setUniqueId(resourceUniqueId); - } - resourceData.getMetadataDataDefinition().setHighestVersion(true); - - String userId = resource.getCreatorUserId(); - - Either findUser = findUserVertex(userId); - - if (findUser.isRight()) { - TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user {} in the graph. status is {}", userId, status); - return sendError(status, StorageOperationStatus.USER_NOT_FOUND); - } - - TitanVertex creatorVertex = findUser.left().value(); - TitanVertex updaterVertex = creatorVertex; - String updaterUserId = resource.getLastUpdaterUserId(); - if (updaterUserId != null && !updaterUserId.equals(userId)) { - findUser = findUserVertex(updaterUserId); - if (findUser.isRight()) { - TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user {} in the graph. status is {}", userId, status); - return sendError(status, StorageOperationStatus.USER_NOT_FOUND); - } else { - updaterVertex = findUser.left().value(); - } - } - - // get derived from resources - List derivedResources = null; - Either, StorageOperationStatus> derivedResourcesResult = findDerivedResources(resource); - if (derivedResourcesResult.isRight()) { - result = Either.right(derivedResourcesResult.right().value()); - return result; - } else { - derivedResources = derivedResourcesResult.left().value(); - } - - List tags = resource.getTags(); - if (tags != null && false == tags.isEmpty()) { - Either, StorageOperationStatus> tagsResult = createNewTagsList(tags); - if (tagsResult.isRight()) { - result = Either.right(tagsResult.right().value()); - return result; - } - List tagsToCreate = tagsResult.left().value(); - StorageOperationStatus status = createTagNodesOnGraph(tagsToCreate); - if (!status.equals(StorageOperationStatus.OK)) { - result = Either.right(status); - return result; - } - } - - Either createdVertex = titanGenericDao.createNode(resourceData); - if (createdVertex.isRight()) { - TitanOperationStatus status = createdVertex.right().value(); - log.error("Error returned after creating resource data node {}. status returned is ", resourceData, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - TitanVertex metadataVertex = createdVertex.left().value(); - - TitanOperationStatus associateMetadata = associateMetadataToResource(resourceData, creatorVertex, updaterVertex, derivedResources, metadataVertex); - if (associateMetadata != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateMetadata)); - return result; - } - StorageOperationStatus associateCategory = assosiateMetadataToCategory(resource, resourceData); - if (associateCategory != StorageOperationStatus.OK) { - result = Either.right(associateCategory); - return result; - } - - TitanOperationStatus associateProperties = associatePropertiesToResource(metadataVertex, resourceUniqueId, resource.getProperties(), derivedResources); - if (associateProperties != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateProperties)); - return result; - } - - TitanOperationStatus associateAttributes = associateAttributesToResource(metadataVertex, resource.getAttributes(), resourceUniqueId); - if (associateAttributes != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateAttributes)); - return result; - } - - TitanOperationStatus associateInputs = associateInputsToComponent(metadataVertex, resourceUniqueId, resource.getInputs()); - if (associateInputs != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateInputs)); - return result; - } - - StorageOperationStatus associateRequirements = associateRequirementsToResource(metadataVertex, resourceUniqueId, resource.getRequirements()); - if (associateRequirements != StorageOperationStatus.OK) { - result = Either.right(associateRequirements); - return result; - } - - StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(metadataVertex, resourceUniqueId, resource.getCapabilities()); - if (associateCapabilities != StorageOperationStatus.OK) { - result = Either.right(associateCapabilities); - return result; - } - - StorageOperationStatus associateInterfaces = associateInterfacesToResource(resourceData, resource.getInterfaces(), metadataVertex); - if (associateInterfaces != StorageOperationStatus.OK) { - result = Either.right(associateInterfaces); - return result; - } - - Map resourceArtifacts = resource.getArtifacts(); - Map deploymentArtifacts = resource.getDeploymentArtifacts(); - Map toscaArtifacts = resource.getToscaArtifacts(); - if (resourceArtifacts != null) { - if (deploymentArtifacts != null) { - resourceArtifacts.putAll(deploymentArtifacts); - } - } else { - resourceArtifacts = deploymentArtifacts; - } - if (toscaArtifacts != null) { - if (resourceArtifacts != null) { - resourceArtifacts.putAll(toscaArtifacts); - } else { - resourceArtifacts = toscaArtifacts; - } - } - - StorageOperationStatus associateArtifacts = associateArtifactsToResource(metadataVertex, resourceUniqueId, resourceArtifacts); - if (associateArtifacts != StorageOperationStatus.OK) { - result = Either.right(associateArtifacts); - return result; - } - - List additionalInformation = resource.getAdditionalInformation(); - StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(metadataVertex, resourceUniqueId, additionalInformation); - if (addAdditionalInformation != StorageOperationStatus.OK) { - result = Either.right(addAdditionalInformation); - return result; - } - - result = this.getResource(resourceUniqueId, true); - if (result.isRight()) { - log.error("Cannot get full resource from the graph. status is {}", result.right().value()); - return Either.right(result.right().value()); - } - - if (log.isDebugEnabled()) { - String json = prettyJson.toJson(result.left().value()); - log.debug("Resource retrieved is {}", json); - } - - 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 StorageOperationStatus assosiateMetadataToCategory(Resource resource, ResourceMetadataData resourceData) { - // get category - String categoryName = resource.getCategories().get(0).getName(); - String subcategoryName = resource.getCategories().get(0).getSubcategories().get(0).getName(); - - CategoryData categoryData = null; - Either categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class); - if (categoryResult.isRight()) { - StorageOperationStatus status = categoryResult.right().value(); - log.error("Cannot find category {} in the graph. status is {}", categoryName, status); - return categoryResult.right().value(); - } - categoryData = categoryResult.left().value(); - if (categoryData != null) { - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(), - GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class); - if (childrenNodes.isRight()) { - log.debug("Faield to fetch sub categories for resource category {}", categoryData.getCategoryDataDefinition().getName()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(childrenNodes.right().value()); - } - for (ImmutablePair pair : childrenNodes.left().value()) { - SubCategoryData subcategoryData = pair.left; - if (subcategoryData.getSubCategoryDataDefinition().getName().equals(subcategoryName)) { - Either result = titanGenericDao.createRelation(resourceData, subcategoryData, GraphEdgeLabels.CATEGORY, null); - log.debug("After associating resource {} to subcategory {}. Edge type is {}", resourceData.getUniqueId(), subcategoryData, GraphEdgeLabels.CATEGORY); - if (result.isRight()) { - log.error("Faield to associate resource {} to category {}. Edge type is {}", resourceData.getUniqueId(), categoryData, GraphEdgeLabels.CATEGORY); - return DaoStatusConverter.convertTitanStatusToStorageStatus(result.right().value()); - } - - } - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus addAdditionalInformationToResource(TitanVertex metadataVertex, String resourceUniqueId, List additionalInformation) { - - StorageOperationStatus result = null; - if (additionalInformation == null || true == additionalInformation.isEmpty()) { - result = super.addAdditionalInformation(NodeTypeEnum.Resource, resourceUniqueId, null, metadataVertex); - } else { - if (additionalInformation.size() == 1) { - result = super.addAdditionalInformation(NodeTypeEnum.Resource, resourceUniqueId, additionalInformation.get(0)); - } else { - result = StorageOperationStatus.BAD_REQUEST; - log.info("Cannot create resource with more than one additional information object. The number of received object is {}", additionalInformation.size()); - } - } - return result; - } - - private void generateUUID(Resource resource) { - String prevUUID = resource.getUUID(); - String version = resource.getVersion(); - if ((prevUUID == null && uuidNormativeNewVersion.matcher(version).matches()) || uuidNewVersion.matcher(version).matches()) { - UUID uuid = UUID.randomUUID(); - resource.setUUID(uuid.toString()); - MDC.put("serviceInstanceID", uuid.toString()); - } - } - - @Override - public Either overrideResource(Resource resource, Resource resourceSaved, boolean inTransaction) { - Either result = null; - try { - String resourceId = resourceSaved.getUniqueId(); - - // override interfaces to copy only resource's interfaces and not - // derived interfaces - Either, StorageOperationStatus> interfacesOfResourceOnly = interfaceLifecycleOperation.getAllInterfacesOfResource(resourceSaved.getUniqueId(), false, true); - if (interfacesOfResourceOnly.isRight()) { - log.error("failed to get interfaces of resource. resourceId {} status is {}", resourceId, interfacesOfResourceOnly.right().value()); - result = Either.right(interfacesOfResourceOnly.right().value()); - return result; - } - resource.setInterfaces(interfacesOfResourceOnly.left().value()); - resource.setArtifacts(resourceSaved.getArtifacts()); - resource.setDeploymentArtifacts(resourceSaved.getDeploymentArtifacts()); - resource.setGroups(resourceSaved.getGroups()); - resource.setInputs(null); - resource.setLastUpdateDate(null); - resource.setHighestVersion(true); - - // delete former resource - Either deleteResource = deleteResource(resourceId, true); - if (deleteResource.isRight()) { - log.error("failed to delete old resource with id {}. status = {}", resourceId, deleteResource.right().value()); - result = deleteResource; - return result; - } - - Either createResource = createResource(resource, true); - if (createResource.isRight()) { - log.error("failed to create new version of resource {} status = {}", resourceId, createResource.right().value()); - result = createResource; - return result; - } - Resource newResource = createResource.left().value(); - - Either, StorageOperationStatus> cloneGroupEither = cloneGroups(resource, newResource, null, inTransaction); - if (cloneGroupEither.isLeft()) { - newResource.setGroups(cloneGroupEither.left().value()); - } else if (cloneGroupEither.right().value() != StorageOperationStatus.OK) { - log.error("failed to clone group of resource {} status = {}", resourceId, cloneGroupEither.right().value()); - result = Either.right(cloneGroupEither.right().value()); - return result; - } - - result = Either.left(newResource); - 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 StorageOperationStatus associateCapabilitiesToResource(TitanVertex metadataVertex, String resourceIda, Map> capabilities) { - StorageOperationStatus addCapabilityToResource = null; - if (capabilities != null) { - for (Entry> entry : capabilities.entrySet()) { - - List capDefinition = entry.getValue(); - for (CapabilityDefinition item : capDefinition) { - addCapabilityToResource = capabilityOperation.addCapability(metadataVertex, resourceIda, item.getName(), item, true); - if (!addCapabilityToResource.equals(StorageOperationStatus.OK)) { - return addCapabilityToResource; - } - - } - } - - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateRequirementsToResource(TitanVertex metadataVertex, String resourceId, Map> requirements) { - - if (requirements != null) { - for (Entry> entry : requirements.entrySet()) { - - List reqDefinition = entry.getValue(); - for (RequirementDefinition item : reqDefinition) { - StorageOperationStatus addRequirementToResource = requirementOperation.addRequirementToResource(metadataVertex, item.getName(), item, resourceId, true); - - if (!addRequirementToResource.equals(StorageOperationStatus.OK)) { - return addRequirementToResource; - } - } - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateArtifactsToResource(TitanVertex metadataVertex, String resourceId, Map artifacts) { - - StorageOperationStatus status = StorageOperationStatus.OK; - if (artifacts != null) { - Map heatEnvMap = new HashMap(); - for (Entry entry : artifacts.entrySet()) { - - ArtifactDefinition artifactDefinition = entry.getValue(); - - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactDefinition.getArtifactType()); - if(artifactType != ArtifactTypeEnum.HEAT_ENV){ - status = artifactOperation.addArifactToComponent(artifactDefinition, resourceId, NodeTypeEnum.Resource, false, metadataVertex); - }else{ - Optional op = artifacts.values().stream().filter(p -> p.getUniqueId().equals(artifactDefinition.getGeneratedFromId())).findAny(); - if(op.isPresent()){ - heatEnvMap.put(artifactDefinition, op.get()); - } - - - } - - if (!status.equals(StorageOperationStatus.OK)) { - return status; - } - } - for(Entry entry : heatEnvMap.entrySet()){ - Either addHeatEnvArtifact = artifactOperation.addHeatEnvArtifact(entry.getKey(), entry.getValue(), resourceId, NodeTypeEnum.Resource, false); - if (addHeatEnvArtifact.isRight()) { - log.debug("failed to create heat env artifact on resource instance"); - return addHeatEnvArtifact.right().value(); - } - } - } - return status; - - } - - private StorageOperationStatus associateInterfacesToResource(ResourceMetadataData resourceData, Map interfaces, TitanVertex metadataVertex) { - - if (interfaces != null) { - for (Entry entry : interfaces.entrySet()) { - - InterfaceDefinition interfaceDefinition = entry.getValue(); - StorageOperationStatus status; - if (((ResourceMetadataDataDefinition) resourceData.getMetadataDataDefinition()).isAbstract()) { - status = interfaceLifecycleOperation.associateInterfaceToNode(resourceData, interfaceDefinition, metadataVertex); - } else { - status = interfaceLifecycleOperation.createInterfaceOnResource(interfaceDefinition, resourceData.getMetadataDataDefinition().getUniqueId(), interfaceDefinition.getType(), false, true, metadataVertex); - } - - if (!status.equals(StorageOperationStatus.OK)) { - return status; - } - } - } - return StorageOperationStatus.OK; - - } - - private Either sendError(TitanOperationStatus status, StorageOperationStatus statusIfNotFound) { - Either result; - if (status == TitanOperationStatus.NOT_FOUND) { - result = Either.right(statusIfNotFound); - return result; - } else { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - } - - private TitanOperationStatus associatePropertiesToResource(TitanVertex metadatVertex, String resourceId, List properties, List derivedResources) { - - Either, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - log.debug("Cannot find any data type. Status is {}.", status); - return status; - } - - Map convertedProperties = new HashMap<>(); - - if (properties != null) { - for (PropertyDefinition propertyDefinition : properties) { - convertedProperties.put(propertyDefinition.getName(), propertyDefinition); - } - - Either, TitanOperationStatus> getPropertiesOfAllDerivedFromRes = getPropertiesOfAllDerivedFrom(derivedResources); - - if(getPropertiesOfAllDerivedFromRes.isRight()){ - TitanOperationStatus status = getPropertiesOfAllDerivedFromRes.right().value(); - log.debug("Cannot fetch properties of all derived from resources. Status is {}.", status); - return status; - } - - Map allDerivedFromProperties = getPropertiesOfAllDerivedFromRes.left().value(); - - TitanOperationStatus validatePropertyNamesUniqunessStatus = validatePropertyNamesUniquness(properties, allDerivedFromProperties); - - if(validatePropertyNamesUniqunessStatus != TitanOperationStatus.OK){ - return validatePropertyNamesUniqunessStatus; - } - - return propertyOperation.addPropertiesToGraph(metadatVertex, convertedProperties, allDataTypes.left().value(), resourceId); - } - - return TitanOperationStatus.OK; - - } - - private TitanOperationStatus validatePropertyNamesUniquness(List properties, Map allDerivedFromProperties) { - - TitanOperationStatus result = TitanOperationStatus.OK; - Optional propertyOptional= properties.stream() - //filters out properties with the same name and different type - .filter(prop -> allDerivedFromProperties.containsKey(prop.getName()) && !prop.getType().equals(allDerivedFromProperties.get(prop.getName()).getType())) - //Searches for any matching value - .findAny(); - if(propertyOptional.isPresent()){ - log.error("Property with name {} and type {} already exists in derived from resource. ", propertyOptional.get().getName(), allDerivedFromProperties.get( propertyOptional.get().getName()).getType()); - result = TitanOperationStatus.ALREADY_EXIST; - } - return result; - } - - private Either, TitanOperationStatus> getPropertiesOfAllDerivedFrom(List derivedResources) { - Map allDerivedProperties = new HashMap<>(); - Either, TitanOperationStatus> getPropertiesOfAllDerivedFromRes = Either.left(allDerivedProperties); - String currResourceName = null ; - if(!CollectionUtils.isEmpty(derivedResources)){ - try{ - for(int i = derivedResources.size() - 1; i >= 0 ; --i){ - ResourceMetadataData currDerivedResource = derivedResources.get(i); - currResourceName = currDerivedResource.getMetadataDataDefinition().getName(); - Either>, TitanOperationStatus> res = - titanGenericDao.getChildrenNodes( currDerivedResource.getUniqueIdKey(), (String)currDerivedResource.getUniqueId(), GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property, PropertyData.class); - if(res.isRight() && res.right().value() != TitanOperationStatus.NOT_FOUND){ - getPropertiesOfAllDerivedFromRes = Either.right(res.right().value()); - break; - }else if(res.isLeft()){ - allDerivedProperties.putAll(res.left().value().stream() - //Maps PropertyData converted to PropertyDefinition - .map(pair-> propertyOperation.convertPropertyDataToPropertyDefinition(pair.getLeft(), (String)pair.getRight().getProperties().get(GraphPropertiesDictionary.NAME.getProperty()), (String)currDerivedResource.getUniqueId())) - //and collects it to a map - .collect(Collectors.toMap(entry->entry.getName(), entry->entry))); - } - } - } - catch(Exception e){ - log.error("Exception occured during fetch properties of resource {}. ", currResourceName); - } - } - return getPropertiesOfAllDerivedFromRes; - } - - private TitanOperationStatus associateAttributesToResource(TitanVertex metadataVertex, List attributes, String resourceId) { - TitanOperationStatus operationStatus = TitanOperationStatus.OK; - - Either, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - log.debug("Cannot find any data type. Status is {}.", status); - return status; - } - - if (attributes != null) { - Map convertedAttributes = attributes.stream().collect(Collectors.toMap(e -> e.getName(), e -> e)); - operationStatus = attributeOperation.addAttributesToGraph(metadataVertex, convertedAttributes, resourceId, allDataTypes.left().value()); - } - return operationStatus; - } - - private TitanOperationStatus associateMetadataToResource(ResourceMetadataData resourceData, TitanVertex creatorVertex, TitanVertex updaterVertex, List derivedResources, TitanVertex metadataVertex) { - - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.STATE.getProperty(), resourceData.getMetadataDataDefinition().getState()); - - TitanOperationStatus result = titanGenericDao.createEdge(updaterVertex, metadataVertex, GraphEdgeLabels.STATE, props); - log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, resourceData.getUniqueId(), GraphEdgeLabels.STATE); - if (!result.equals(TitanOperationStatus.OK)) { - return result; - } - result = titanGenericDao.createEdge(updaterVertex, metadataVertex, GraphEdgeLabels.LAST_MODIFIER, null); - log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, resourceData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER); - if (!result.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate user {} to resource {}. Edge type is {}", updaterVertex, resourceData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER); - return result; - } - - result = titanGenericDao.createEdge(creatorVertex, metadataVertex, GraphEdgeLabels.CREATOR, null); - log.debug("After associating user {} to resource {}. Edge type is {} ", creatorVertex, resourceData.getUniqueId(), GraphEdgeLabels.CREATOR); - if (!result.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate user {} to resource {}. Edge type is {} ", creatorVertex, resourceData.getUniqueId(), GraphEdgeLabels.CREATOR); - return result; - } - // TODO Evg : need to change too.. - if (derivedResources != null) { - for (ResourceMetadataData derivedResource : derivedResources) { - log.debug("After associating resource {} to parent resource {}. Edge type is {}", resourceData.getUniqueId(), derivedResource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM); - Either createRelationResult = titanGenericDao.createRelation(resourceData, derivedResource, GraphEdgeLabels.DERIVED_FROM, null); - if (createRelationResult.isRight()) { - log.error("Failed to associate resource {} to derived ", resourceData.getUniqueId()); - return createRelationResult.right().value(); - } - } - } - - return TitanOperationStatus.OK; - } - - public Either, StorageOperationStatus> findDerivedResources(Resource resource) { - - List derivedResources = new ArrayList(); - List derivedFromResources = resource.getDerivedFrom(); - if (derivedFromResources != null && false == derivedFromResources.isEmpty()) { - - for (String parentResource : derivedFromResources) { - - Map propertiesToMatch = new HashMap(); - propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); - // propertiesToMatch.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), - // true); - propertiesToMatch.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), parentResource); - propertiesToMatch.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - - Either, TitanOperationStatus> getParentResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class); - List resources = null; - if (getParentResources.isRight()) { - /* - * log.debug( "Cannot find parent resource by tosca resource name {} in the graph. Try to find by name", parentResource); - * Map propertiesWithResourceNameToMatch = new HashMap(); - * propertiesWithResourceNameToMatch.put( GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); propertiesWithResourceNameToMatch.put( GraphPropertiesDictionary.NAME.getProperty(), parentResource); - * propertiesWithResourceNameToMatch.put( GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty( ), true); - * - * getParentResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesWithResourceNameToMatch, ResourceData.class); if (getParentResources.isRight()) { log.error( - * "Cannot find parent resource by tosca resource name" + parentResource + " in the graph."); return Either.right(StorageOperationStatus. PARENT_RESOURCE_NOT_FOUND); }else{ resources = getParentResources.left().value(); - * hea - * } - */ - log.error("Cannot find parent resource by tosca resource name {} in the graph.", parentResource); - return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND); - - } else { - resources = getParentResources.left().value(); - if (resources == null || resources.size() == 0) { - log.error("Cannot find parent resource by tosc name {} in the graph. resources size is empty", parentResource); - return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND); - } else { - if (resources.size() > 1) { - log.error("Multiple parent resources called {} found in the graph.", parentResource); - return Either.right(StorageOperationStatus.MULTIPLE_PARENT_RESOURCE_FOUND); - } - ResourceMetadataData parentResourceData = resources.get(0); - derivedResources.add(parentResourceData); - } - - } - - } - } - return Either.left(derivedResources); - } - - private ResourceMetadataData getResourceMetaDataFromResource(Resource resource) { - ResourceMetadataData resourceData = new ResourceMetadataData((ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()); - if (resource.getNormalizedName() == null || resource.getNormalizedName().isEmpty()) { - resourceData.getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(resource.getName())); - } - if (resource.getSystemName() == null || resource.getSystemName().isEmpty()) { - resourceData.getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(resource.getName())); - } - - LifecycleStateEnum lifecycleStateEnum = resource.getLifecycleState(); - if (lifecycleStateEnum == null) { - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - } - long currentDate = System.currentTimeMillis(); - if (resource.getCreationDate() == null) { - resourceData.getMetadataDataDefinition().setCreationDate(currentDate); - } - resourceData.getMetadataDataDefinition().setLastUpdateDate(currentDate); - - return resourceData; - } - - private ResourceMetadataData getResourceMetaDataForUpdate(Resource resource) { - // PA - please note: if you add here any fields, make sure they are - // validated (if needed) - // at ResourceBusinessLogic.validateResourceFieldsBeforeUpdate() and - // tested at ResourceBusinessLogicTest. - ResourceMetadataData resourceData = getResourceMetaDataFromResource(resource); - // resourceData.setLastUpdateDate(System.currentTimeMillis()); - // resourceData.setHighestVersion(resource.isHighestVersion()); - // resourceData.setNormalizedName(resource.getNormalizedName()); - // resourceData.setResourceType(resource.getResourceType().name()); - - return resourceData; - } - - public Either getResource(String uniqueId) { - return getResource(uniqueId, false); - } - - public Either getResource(String uniqueId, boolean inTransaction) { - ComponentParametersView componentParametersView = new ComponentParametersView(); - return getResource(uniqueId, componentParametersView, inTransaction); - } - - private TitanOperationStatus setComponentInstancesAttributesFromGraph(String uniqueId, Resource component) { - Map> resourceInstancesAttributes = new HashMap<>(); - TitanOperationStatus status = TitanOperationStatus.OK; - List componentInstances = component.getComponentInstances(); - if (componentInstances != null) { - for (ComponentInstance resourceInstance : componentInstances) { - Either, TitanOperationStatus> eitherRIAttributes = attributeOperation.getAllAttributesOfResourceInstance(resourceInstance); - if (eitherRIAttributes.isRight()) { - status = eitherRIAttributes.right().value(); - break; - } else { - resourceInstancesAttributes.put(resourceInstance.getUniqueId(), eitherRIAttributes.left().value()); - } - } - - component.setComponentInstancesAttributes(resourceInstancesAttributes); - } - - return status; - - } - - private StorageOperationStatus setResourceAdditionalInformationFromGraph(String uniqueId, Resource resource) { - - List additionalInformation = new ArrayList<>(); - - Either either = additionalInformationOperation.getAllAdditionalInformationParameters(NodeTypeEnum.Resource, uniqueId, true, true); - - if (either.isRight()) { - StorageOperationStatus status = either.right().value(); - if (status == StorageOperationStatus.NOT_FOUND) { - return StorageOperationStatus.OK; - } - return status; - } - - AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); - additionalInformation.add(additionalInformationDefinition); - - resource.setAdditionalInformation(additionalInformation); - - return StorageOperationStatus.OK; - - } - - private StorageOperationStatus setResourceInterfacesFromGraph(String uniqueId, Resource resource) { - - Either, StorageOperationStatus> statusRes = interfaceLifecycleOperation.getAllInterfacesOfResource(uniqueId, true, true); - if (statusRes.isRight()) { - return statusRes.right().value(); - } - Map value = statusRes.left().value(); - - resource.setInterfaces(value); - - return StorageOperationStatus.OK; - } - - private StorageOperationStatus setResourceCapabilitiesFromGraph(String uniqueId, Resource resource) { - StorageOperationStatus retStatus; - Either, StorageOperationStatus> result = capabilityOperation.getAllCapabilitiesOfResource(uniqueId, true, true); - if (result.isRight()) { - StorageOperationStatus status = result.right().value(); - if (status != StorageOperationStatus.NOT_FOUND) { - retStatus = status; - } else { - retStatus = StorageOperationStatus.OK; - } - } else { - Map capabilities = result.left().value(); - if (capabilities != null && !capabilities.isEmpty() && resource.getResourceType().equals(ResourceTypeEnum.VF)) { - MigrationMalformedDataLogger.reportMalformedVF(resource.getUniqueId(), String.format("VF %s with id %s has direct capabilities.!!!!!!!!!!!!!", resource.getName(), resource.getUniqueId())); - } - if (capabilities == null || capabilities.isEmpty() || resource.getResourceType().equals(ResourceTypeEnum.VF)) { - Either>, TitanOperationStatus> eitherCapabilities = super.getCapabilities(resource, NodeTypeEnum.Resource, true); - if (eitherCapabilities.isLeft()) { - retStatus = StorageOperationStatus.OK; - Map> calculatedCapabilities = eitherCapabilities.left().value(); - resource.setCapabilities(calculatedCapabilities); - } else { - retStatus = StorageOperationStatus.GENERAL_ERROR; - } - - } else { - retStatus = StorageOperationStatus.OK; - resource.setCapabilities(capabilityOperation.convertCapabilityMap(capabilities, null, null)); - } - - } - return retStatus; - - } - - public Either>, TitanOperationStatus> getCapabilities(org.openecomp.sdc.be.model.Component component, NodeTypeEnum componentTypeEnum, boolean inTransaction) { - - try { - Either, StorageOperationStatus> result = capabilityOperation.getAllCapabilitiesOfResource(component.getUniqueId(), true, true); - if (result.isRight() || result.left().value().isEmpty()) { - final Either>, TitanOperationStatus> eitherCapabilities = super.getCapabilities(component, componentTypeEnum, inTransaction); - return eitherCapabilities; - } else { - return Either.left(capabilityOperation.convertCapabilityMap(result.left().value(), null, null)); - } - } finally { - if (inTransaction == false) { - titanGenericDao.commit(); - } - } - } - - public Either>, TitanOperationStatus> getRequirements(org.openecomp.sdc.be.model.Component component, NodeTypeEnum componentTypeEnum, boolean inTransaction) { - try { - Either, StorageOperationStatus> result = requirementOperation.getAllResourceRequirements(component.getUniqueId(), true); - if (result.isRight() || result.left().value().isEmpty()) { - final Either>, TitanOperationStatus> eitherCapabilities = super.getRequirements(component, componentTypeEnum, true); - return eitherCapabilities; - } else { - return Either.left(requirementOperation.convertRequirementMap(result.left().value(), null, null)); - } - } finally { - if (inTransaction == false) { - titanGenericDao.commit(); - } - } - - } - - private StorageOperationStatus setResourceRequirementsFromGraph(String uniqueId, Resource resource, boolean inTransaction) { - StorageOperationStatus retStatus; - Either, StorageOperationStatus> result = requirementOperation.getAllResourceRequirements(uniqueId, inTransaction); - ; - if (result.isRight()) { - StorageOperationStatus status = result.right().value(); - if (status != StorageOperationStatus.NOT_FOUND) { - retStatus = status; - } else { - retStatus = StorageOperationStatus.OK; - } - } else { - Map requirements = result.left().value(); - if (requirements != null && !requirements.isEmpty() && resource.getResourceType().equals(ResourceTypeEnum.VF)) { - MigrationMalformedDataLogger.reportMalformedVF(resource.getUniqueId(), String.format("VF %s with id %s has direct requirements.!!!!!!!!!!!!!", resource.getName(), resource.getUniqueId())); - } - if (requirements == null || requirements.isEmpty() || resource.getResourceType() == ResourceTypeEnum.VF) { - Either>, TitanOperationStatus> eitherCapabilities = super.getRequirements(resource, NodeTypeEnum.Resource, true); - if (eitherCapabilities.isLeft()) { - retStatus = StorageOperationStatus.OK; - Map> calculatedCapabilities = eitherCapabilities.left().value(); - resource.setRequirements(calculatedCapabilities); - } else { - retStatus = StorageOperationStatus.GENERAL_ERROR; - } - - } else { - retStatus = StorageOperationStatus.OK; - resource.setRequirements(requirementOperation.convertRequirementMap(requirements, null, null)); - } - - } - return retStatus; - } - - private TitanOperationStatus setResourcePropertiesFromGraph(String uniqueId, Resource resource) { - - List properties = new ArrayList<>(); - TitanOperationStatus status = propertyOperation.findAllResourcePropertiesRecursively(uniqueId, properties); - if (status == TitanOperationStatus.OK) { - resource.setProperties(properties); - } - - return status; - - } - - private TitanOperationStatus setResourceAttributesFromGraph(String uniqueId, Resource resource) { - - List attributes = new ArrayList<>(); - TitanOperationStatus status = attributeOperation.findAllResourceAttributesRecursively(uniqueId, attributes); - if (status == TitanOperationStatus.OK) { - resource.setAttributes(attributes); - } - - return status; - - } - - private TitanOperationStatus setResourceDerivedFromGraph(String uniqueId, Resource resource) { - List derivedFromList = new ArrayList(); - - TitanOperationStatus listFromGraphStatus = fillResourceDerivedListFromGraph(uniqueId, derivedFromList); - if (!TitanOperationStatus.OK.equals(listFromGraphStatus)) { - return listFromGraphStatus; - } - - if (false == derivedFromList.isEmpty()) { - if (derivedFromList.size() > 1) { - List lastDerivedFrom = new ArrayList(); - lastDerivedFrom.add(derivedFromList.get(1)); - resource.setDerivedFrom(lastDerivedFrom); - resource.setDerivedList(derivedFromList); - } else { - resource.setDerivedFrom(null); - resource.setDerivedList(derivedFromList); - } - - } - - return TitanOperationStatus.OK; - } - - public TitanOperationStatus fillResourceDerivedListFromGraph(String uniqueId, List derivedFromList) { - // Either>, - // TitanOperationStatus> childrenNodes = - // titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), - // uniqueId, GraphEdgeLabels.DERIVED_FROM, - // NodeTypeEnum.Resource, ResourceMetadataData.class); - // - // if (childrenNodes.isRight() && (childrenNodes.right().value() != - // TitanOperationStatus.NOT_FOUND)) { - // return childrenNodes.right().value(); - // } else if (childrenNodes.isLeft()) { - // - // List> pairList = - // childrenNodes.left().value(); - // for (ImmutablePair pair : pairList) - // { - // derivedFromList.add(pair.left.getMetadataDataDefinition().getName()); - // return - // fillResourceDerivedListFromGraph(pair.left.getMetadataDataDefinition().getUniqueId(), - // derivedFromList); - // } - // } - List derivedData = new ArrayList(); - TitanOperationStatus findResourcesPathRecursively = findResourcesPathRecursively(uniqueId, derivedData); - if (!findResourcesPathRecursively.equals(TitanOperationStatus.OK)) { - return findResourcesPathRecursively; - } - derivedData.forEach(resourceData -> derivedFromList.add(((ResourceMetadataDataDefinition) resourceData.getMetadataDataDefinition()).getToscaResourceName())); - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setResourceLastModifierFromGraph(Resource resource, String resourceId) { - - Either, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.LAST_MODIFIER, NodeTypeEnum.User, - UserData.class); - if (parentNode.isRight()) { - return parentNode.right().value(); - } - - ImmutablePair value = parentNode.left().value(); - if (log.isDebugEnabled()) - log.debug("Found parent node {}", value); - UserData userData = value.getKey(); - - if (log.isDebugEnabled()) - log.debug("Build resource : set last modifier userId to {}", userData.getUserId()); - String fullName = buildFullName(userData); - if (log.isDebugEnabled()) - log.debug("Build resource : set last modifier full name to {}", fullName); - resource.setLastUpdaterUserId(userData.getUserId()); - resource.setLastUpdaterFullName(fullName); - - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setResourceCreatorFromGraph(Resource resource, String resourceId) { - - Either, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.CREATOR, NodeTypeEnum.User, UserData.class); - if (parentNode.isRight()) { - log.debug("Failed to find the creator of resource {}", resourceId); - return parentNode.right().value(); - } - - ImmutablePair value = parentNode.left().value(); - if (log.isDebugEnabled()) - log.debug("Found parent node {}", value); - UserData userData = value.getKey(); - if (log.isDebugEnabled()) - log.debug("Build resource : set creator userId to {}", userData.getUserId()); - String fullName = buildFullName(userData); - if (log.isDebugEnabled()) - log.debug("Build resource : set creator full name to {}", fullName); - resource.setCreatorUserId(userData.getUserId()); - resource.setCreatorFullName(fullName); - - return TitanOperationStatus.OK; - } - - @Override - TitanOperationStatus setComponentCategoriesFromGraph(Component resource) { - String uniqueId = resource.getUniqueId(); - Either>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqueId, GraphEdgeLabels.CATEGORY, - NodeTypeEnum.ResourceSubcategory, SubCategoryData.class); - if (parentNode.isRight()) { - return parentNode.right().value(); - } - - List> listValue = parentNode.left().value(); - log.debug("Result after looking for subcategory nodes pointed by resource {}. status is {}", uniqueId, listValue); - if (listValue.size() > 1) { - log.error("Multiple edges foud between resource {} to subcategory nodes.", uniqueId); - } - ImmutablePair value = listValue.get(0); - log.debug("Found parent node {}", value); - - SubCategoryData subcategoryData = value.getKey(); - - Either, TitanOperationStatus> categoryNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceSubcategory), (String) subcategoryData.getUniqueId(), - GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceNewCategory, CategoryData.class); - if (categoryNode.isRight()) { - return categoryNode.right().value(); - } - - CategoryData categoryData = categoryNode.left().value().left; - CategoryDefinition catDef = new CategoryDefinition(categoryData.getCategoryDataDefinition()); - SubCategoryDefinition subcatDef = new SubCategoryDefinition(subcategoryData.getSubCategoryDataDefinition()); - - resource.addCategory(catDef, subcatDef); - return TitanOperationStatus.OK; - } - - public String buildFullName(UserData userData) { - - String fullName = userData.getFirstName(); - if (fullName == null) { - fullName = ""; - } else { - fullName = fullName + " "; - } - String lastName = userData.getLastName(); - if (lastName != null) { - fullName += lastName; - } - return fullName; - } - - private Resource convertResourceDataToResource(ResourceMetadataData resourceData) { - - ResourceMetadataDefinition resourceMetadataDataDefinition = new ResourceMetadataDefinition((ResourceMetadataDataDefinition) resourceData.getMetadataDataDefinition()); - - Resource resource = new Resource(resourceMetadataDataDefinition); - - return resource; - } - - @Override - public Either deleteResource(String resourceId) { - return deleteResource(resourceId, false); - } - - @Override - public Either updateResource(Resource resource) { - - return updateResource(resource, false); - - } - - @Override - public Either getNumberOfResourcesByName(String resourceName) { - - Map propertiesToMatch = new HashMap(); - propertiesToMatch.put(GraphPropertiesDictionary.NAME.getProperty(), resourceName); - - Either, TitanOperationStatus> getParentResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class); - log.debug("result after searching for resources called {} is {}", resourceName, getParentResources); - if (getParentResources.isRight()) { - TitanOperationStatus titanStatus = getParentResources.right().value(); - if (titanStatus == TitanOperationStatus.NOT_FOUND) { - log.debug("Number of returned resources is 0."); - return Either.left(0); - } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus)); - } else { - List value = getParentResources.left().value(); - int numberOFResources = (value == null ? 0 : value.size()); - log.debug("The number of resources returned after searching for resource called {} is {}", resourceName, numberOFResources); - return Either.left(numberOFResources); - } - } - - public PropertyOperation getPropertyOperation() { - return propertyOperation; - } - - public void setPropertyOperation(PropertyOperation propertyOperation) { - this.propertyOperation = propertyOperation; - } - - public RequirementOperation getRequirementOperation() { - return requirementOperation; - } - - public void setRequirementOperation(RequirementOperation requirementOperation) { - this.requirementOperation = requirementOperation; - } - - public CapabilityOperation getCapabilityOperation() { - return capabilityOperation; - } - - public void setCapabilityOperation(CapabilityOperation capabilityOperation) { - this.capabilityOperation = capabilityOperation; - } - - public IArtifactOperation getArtifactOperation() { - return artifactOperation; - } - - public void setArtifactOperation(IArtifactOperation artifactOperation) { - this.artifactOperation = artifactOperation; - } - - public InterfaceLifecycleOperation getInterfaceLifecycleOperation() { - return interfaceLifecycleOperation; - } - - public void setInterfaceLifecycleOperation(InterfaceLifecycleOperation interfaceLifecycleOperation) { - this.interfaceLifecycleOperation = interfaceLifecycleOperation; - } - - public TitanGenericDao getTitanGenericDao() { - return titanGenericDao; - } - - public IElementOperation getElementOperation() { - return elementOperation; - } - - public void setElementOperation(IElementOperation elementOperation) { - this.elementOperation = elementOperation; - } - - /** - * FOR TEST ONLY - * - * @param titanGenericDao - */ - public void setTitanGenericDao(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; - } - - @Override - public Either, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract) { - - return getAllCertifiedResources(isAbstract, null); - - } - - @Override - /** - * Deletes the resource node, property nodes and relation to artifacts. MUST handle deletion of artifact from artifacts repository outside this method (in catalog-be) - */ - public Either deleteResource(String resourceId, boolean inTransaction) { - - Either result = Either.right(StorageOperationStatus.GENERAL_ERROR); - try { - - Either graphResult = titanGenericDao.getGraph(); - if (graphResult.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); - return result; - } - - TitanGraph titanGraph = graphResult.left().value(); - Iterable vertecies = titanGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId).vertices(); - Either resourceEither = getResource(resourceId, true); - Resource resource = resourceEither.left().value(); - if (vertecies != null && resourceEither.isLeft()) { - Iterator iterator = vertecies.iterator(); - if (iterator != null && iterator.hasNext()) { - Vertex rootVertex = iterator.next(); - TitanOperationStatus deleteChildrenNodes = graphDeleteUtil.deleteChildrenNodes(rootVertex, GraphEdgeLabels.PROPERTY); - log.debug("After deleting properties nodes in the graph. status is {}", deleteChildrenNodes); - if (deleteChildrenNodes != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteChildrenNodes)); - return result; - } - StorageOperationStatus removeInterfacesFromResource = removeInterfacesFromResource(resource); - log.debug("After deleting interfaces nodes in the graph. status is {}", removeInterfacesFromResource); - if (!removeInterfacesFromResource.equals(StorageOperationStatus.OK)) { - result = Either.right(removeInterfacesFromResource); - return result; - } - StorageOperationStatus removeArtifactsFromResource = removeArtifactsFromResource(resource); - log.debug("After deleting artifacts nodes in the graph. status is {}", removeArtifactsFromResource); - if (!removeArtifactsFromResource.equals(StorageOperationStatus.OK)) { - result = Either.right(removeArtifactsFromResource); - return result; - } - StorageOperationStatus removeCapabilitiesFromResource = removeCapabilitiesFromResource(resource); - log.debug("After deleting capabilities nodes in the graph. status is {}", removeCapabilitiesFromResource); - if (!removeCapabilitiesFromResource.equals(StorageOperationStatus.OK)) { - result = Either.right(removeCapabilitiesFromResource); - return result; - } - - StorageOperationStatus removeRequirementsFromResource = removeRequirementsFromResource(resource); - log.debug("After deleting requirements nodes in the graph. status is {}", removeRequirementsFromResource); - if (!removeRequirementsFromResource.equals(StorageOperationStatus.OK)) { - result = Either.right(removeRequirementsFromResource); - return result; - } - - StorageOperationStatus removeRIsFromResource = removeResourceInstanceFromResource(resource); - log.debug("After deleting resource instance nodes in the graph. status is {}", removeRIsFromResource); - if (!removeRIsFromResource.equals(StorageOperationStatus.OK)) { - result = Either.right(removeRIsFromResource); - return result; - } - - StorageOperationStatus removeAttributesFromResource = removeAttributesFromResource(resource); - log.debug("After deleting requirements nodes in the graph. status is {}", removeRequirementsFromResource); - if (removeAttributesFromResource != StorageOperationStatus.OK) { - result = Either.right(removeAttributesFromResource); - return result; - } - - StorageOperationStatus removeInputsFromResource = removeInputsFromComponent(NodeTypeEnum.Resource, resource); - log.debug("After deleting requirements nodes in the graph. status is {}", removeInputsFromResource); - if (removeInputsFromResource != StorageOperationStatus.OK) { - result = Either.right(removeInputsFromResource); - return result; - } - - StorageOperationStatus removeAdditionalInformationFromResource = super.deleteAdditionalInformation(NodeTypeEnum.Resource, resource.getUniqueId()); - log.debug("After deleting additional information node in the graph. status is {}", removeAdditionalInformationFromResource); - if (!removeAdditionalInformationFromResource.equals(StorageOperationStatus.OK)) { - result = Either.right(removeAdditionalInformationFromResource); - return result; - } - - StorageOperationStatus removeGroupsFromResource = super.deleteGroups(NodeTypeEnum.Resource, resource.getUniqueId()); - log.debug("After deleting group nodes in the graph. status is {}", removeGroupsFromResource); - if (!removeGroupsFromResource.equals(StorageOperationStatus.OK)) { - result = Either.right(removeGroupsFromResource); - return result; - } - - rootVertex.remove(); - - } else { - result = Either.right(StorageOperationStatus.NOT_FOUND); - return result; - } - } else { - result = Either.right(StorageOperationStatus.NOT_FOUND); - return result; - } - - result = Either.left(resource); - return result; - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.error("deleteResource operation : Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("deleteResource operation : Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - private StorageOperationStatus removeAttributesFromResource(Resource resource) { - Either, StorageOperationStatus> deleteAllAttributeAssociatedToNode = attributeOperation.deleteAllAttributeAssociatedToNode(NodeTypeEnum.Resource, resource.getUniqueId()); - return deleteAllAttributeAssociatedToNode.isRight() ? deleteAllAttributeAssociatedToNode.right().value() : StorageOperationStatus.OK; - } - - private StorageOperationStatus removeArtifactsFromResource(Resource resource) { - - String resourceId = resource.getUniqueId(); - Map allArtifacts = new HashMap(); - if (resource.getArtifacts() != null) { - allArtifacts.putAll(resource.getArtifacts()); - } - if (resource.getDeploymentArtifacts() != null) { - allArtifacts.putAll(resource.getDeploymentArtifacts()); - } - if (allArtifacts != null) { - for (Entry entry : allArtifacts.entrySet()) { - - ArtifactDefinition artifactDefinition = entry.getValue(); - Either removeArifactFromResource = artifactOperation.removeArifactFromResource(resourceId, artifactDefinition.getUniqueId(), NodeTypeEnum.Resource, true, true); - if (removeArifactFromResource.isRight()) { - return removeArifactFromResource.right().value(); - } - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus removeInterfacesFromResource(Resource resource) { - - String resourceId = resource.getUniqueId(); - // delete only interfaces of this resource (not interfaces derived) - Either, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(resourceId, false, true); - if (allInterfacesOfResource.isRight()) { - log.error("failed to get interfaces for resource {}. status is {}", resourceId, allInterfacesOfResource.right().value()); - return allInterfacesOfResource.right().value(); - } - Map interfaces = allInterfacesOfResource.left().value(); - if (interfaces != null) { - for (Entry entry : interfaces.entrySet()) { - Boolean isAbstract = resource.isAbstract(); - - InterfaceDefinition interfaceDefinition = entry.getValue(); - // esofer - in case the resource is abstract, we deleting only - // the edge to the interface. - if (isAbstract != null && true == isAbstract.booleanValue()) { - log.debug("Going to dissociate resource {} from interface {}", resourceId, interfaceDefinition.getUniqueId()); - UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.Resource, resourceId); - Either dissociateInterfaceFromNode = interfaceLifecycleOperation.dissociateInterfaceFromNode(uniqueIdData, interfaceDefinition); - if (dissociateInterfaceFromNode.isRight()) { - log.error("failed to dissociate resource {} from interface {}. status is {}", resourceId, interfaceDefinition.getUniqueId(), dissociateInterfaceFromNode.right().value()); - return dissociateInterfaceFromNode.right().value(); - } - } else { - Either deleteInterfaceOfResourceOnGraph = interfaceLifecycleOperation.deleteInterfaceOfResourceOnGraph(resourceId, interfaceDefinition, true); - if (deleteInterfaceOfResourceOnGraph.isRight()) { - return deleteInterfaceOfResourceOnGraph.right().value(); - } - } - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus removeCapabilitiesFromResource(Resource resource) { - - String resourceId = resource.getUniqueId(); - - Either, StorageOperationStatus> deleteAllRes = capabilityOperation.deleteAllCapabilities(resourceId, true); - if (deleteAllRes.isRight()) { - StorageOperationStatus status = deleteAllRes.right().value(); - if (status == StorageOperationStatus.NOT_FOUND) { - return StorageOperationStatus.OK; - } - return status; - } - - return StorageOperationStatus.OK; - - } - - private StorageOperationStatus removeRequirementsFromResource(Resource resource) { - - String resourceId = resource.getUniqueId(); - - Either, StorageOperationStatus> deleteAllRes = requirementOperation.deleteAllRequirements(resourceId, true); - - if (deleteAllRes.isRight()) { - StorageOperationStatus status = deleteAllRes.right().value(); - if (status == StorageOperationStatus.NOT_FOUND) { - return StorageOperationStatus.OK; - } - return status; - } - - return StorageOperationStatus.OK; - - } - - private StorageOperationStatus removeResourceInstanceFromResource(Resource resource) { - String resourceId = resource.getUniqueId(); - - Either, StorageOperationStatus> deleteAllResourceInstancesRes = componentInstanceOperation.deleteAllComponentInstances(resourceId, NodeTypeEnum.Resource, true); - if (deleteAllResourceInstancesRes.isRight()) { - StorageOperationStatus status = deleteAllResourceInstancesRes.right().value(); - if (status == StorageOperationStatus.NOT_FOUND) { - return StorageOperationStatus.OK; - } - return status; - } - return StorageOperationStatus.OK; - } - - @Override - public Either updateResource(Resource resource, boolean inTransaction) { - return (Either) updateComponent(resource, inTransaction, titanGenericDao, resource.getClass(), NodeTypeEnum.Resource); - - } - - @Override - protected StorageOperationStatus updateDerived(Component component, Component currentComponent, ComponentMetadataData updatedResourceData, Class clazz) { - Resource resource = (Resource) component; - Resource currentResource = (Resource) currentComponent; - if (resource.getDerivedFrom() != null) {// meaning derived from changed - - Either, StorageOperationStatus> findDerivedResourcesOld = findDerivedResources(currentResource); - if (findDerivedResourcesOld.isRight()) { - log.debug("Couldn't find derived resource {} for current resource in the graph", currentResource.getDerivedFrom().get(0)); - return findDerivedResourcesOld.right().value(); - } - - List oldDerived = findDerivedResourcesOld.left().value(); - if (oldDerived.isEmpty()) { - log.debug("Derived from list fetched from DB for current resource is empty"); - return StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND; - } - - Either, StorageOperationStatus> findDerivedResourcesNew = findDerivedResources((Resource) resource); - if (findDerivedResourcesNew.isRight()) { - log.debug("Couldn't find derived resource {} for update resource in the graph", resource.getDerivedFrom().get(0)); - return findDerivedResourcesNew.right().value(); - } - - List newDerived = findDerivedResourcesNew.left().value(); - if (newDerived.isEmpty()) { - log.debug("Derived from list fetched from DB for updated resource is empty"); - return StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND; - } - - Either reassociateDerivedFrom = reassociateDerivedFrom((ResourceMetadataData) updatedResourceData, oldDerived, newDerived); - if (reassociateDerivedFrom.isRight()) { - log.debug("Couldn't change derived from for the resoure"); - return DaoStatusConverter.convertTitanStatusToStorageStatus(reassociateDerivedFrom.right().value()); - } - } - return StorageOperationStatus.OK; - } - - private Either reassociateDerivedFrom(ResourceMetadataData resourceData, List oldDerived, List newDerived) { - ResourceMetadataData oldDerivedNode = oldDerived.get(0); - log.debug("Dissociating resource {} from old parent resource {}", resourceData.getUniqueId(), oldDerivedNode.getUniqueId()); - Either deleteRelation = titanGenericDao.deleteRelation(resourceData, oldDerivedNode, GraphEdgeLabels.DERIVED_FROM); - if (deleteRelation.isRight()) { - log.debug("Failed to dissociate resource {} from old parent resource {}", resourceData.getUniqueId(), oldDerivedNode.getUniqueId()); - return Either.right(deleteRelation.right().value()); - } - ResourceMetadataData newDerivedNode = newDerived.get(0); - log.debug("Associating resource {} with new parent resource {}", resourceData.getUniqueId(), newDerivedNode.getUniqueId()); - Either addRelation = titanGenericDao.createRelation(resourceData, newDerivedNode, GraphEdgeLabels.DERIVED_FROM, null); - if (addRelation.isRight()) { - log.debug("Failed to associate resource {} with new parent resource {}", resourceData.getUniqueId(), newDerivedNode.getUniqueId()); - return Either.right(addRelation.right().value()); - } - - return Either.left(true); - } - - private StorageOperationStatus moveCategoryEdge(Resource resource, ResourceMetadataData resourceData, CategoryDefinition newCategory) { - - StorageOperationStatus result = StorageOperationStatus.OK; - - GraphRelation categoryRelation = new GraphRelation(); - categoryRelation.setType(GraphEdgeLabels.CATEGORY.getProperty()); - RelationEndPoint relationEndPoint = new RelationEndPoint(NodeTypeEnum.Resource, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId()); - categoryRelation.setFrom(relationEndPoint); - Either deleteOutgoingRelation = titanGenericDao.deleteOutgoingRelation(categoryRelation); - if (deleteOutgoingRelation.isRight()) { - log.error("Failed to delete category from resource {}. Edge type is {}", resourceData.getUniqueId(), GraphEdgeLabels.CATEGORY); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteOutgoingRelation.right().value()); - return result; - } - - log.debug("After removing edge from graph {}", deleteOutgoingRelation); - - return assosiateMetadataToCategory(resource, resourceData); - } - - private StorageOperationStatus moveLastModifierEdge(Resource resource, ResourceMetadataData resourceData, UserData modifierUserData) { - - StorageOperationStatus result = StorageOperationStatus.OK; - - GraphRelation lastModifierRelation = new GraphRelation(); - lastModifierRelation.setType(GraphEdgeLabels.LAST_MODIFIER.getProperty()); - RelationEndPoint relationEndPoint = new RelationEndPoint(NodeTypeEnum.Resource, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId()); - lastModifierRelation.setTo(relationEndPoint); - Either deleteIncomingRelation = titanGenericDao.deleteIncomingRelation(lastModifierRelation); - if (deleteIncomingRelation.isRight()) { - log.error("Failed to delete user from resource {}. Edge type is {}", resourceData.getUniqueId(),GraphEdgeLabels.LAST_MODIFIER); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteIncomingRelation.right().value()); - return result; - } - - Either createRelation = titanGenericDao.createRelation(modifierUserData, resourceData, GraphEdgeLabels.LAST_MODIFIER, null); - log.debug("After associating user {} to resource {}. Edge type is {}", modifierUserData, resourceData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER); - if (createRelation.isRight()) { - log.error("Failed to associate user {} to resource {}. Edge type is {}", modifierUserData, resourceData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value()); - return result; - } - - return result; - } - - private Either findResource(String resourceId) { - - String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource); - Either findResource = titanGenericDao.getNode(key, resourceId, ResourceMetadataData.class); - - return findResource; - } - - private StorageOperationStatus setArtifactFromGraph(String uniqueId, Resource resource) { - StorageOperationStatus result = StorageOperationStatus.OK; - Either, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(uniqueId, NodeTypeEnum.Resource, true); - if (artifacts.isRight()) { - result = artifacts.right().value(); - } else { - createSpecificArtifactList(resource, artifacts.left().value()); - } - return result; - } - - @Override - public Either getComponent(String id, Class clazz) { - - Either component = getResource(id); - if (component.isRight()) { - return Either.right(component.right().value()); - } - return Either.left(clazz.cast(component.left().value())); - } - - @Override - public Either validateResourceNameExists(String resourceName, ResourceTypeEnum resourceType) { - if (resourceType != null) { - Map properties = new HashMap(); - properties.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name()); - if (resourceType.equals(ResourceTypeEnum.VF)) { - return validateResourceNameUniqueness(resourceName, properties, null, titanGenericDao); - } else { - return validateResourceNameUniqueness(resourceName, null, properties, titanGenericDao); - } - - } else { - return validateResourceNameUniqueness(resourceName, null, null, titanGenericDao); - } - - } - - public Either validateToscaResourceNameExists(String templateName) { - return validateToscaResourceNameUniqueness(templateName, titanGenericDao); - } - - //Tal G for US815447 - public Either validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) { - - String currentTemplateNameChecked = templateNameExtends; - - while(currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)){ - Either latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked, true); - - if(latestByToscaResourceName.isRight()){ - return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value()); - } - - Resource value = latestByToscaResourceName.left().value(); - - if(value.getDerivedFrom() != null){ - currentTemplateNameChecked = value.getDerivedFrom().get(0); - } else { - currentTemplateNameChecked = null; - } - } - - return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false); - } - - public Either, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction) { - List artifacts = new ArrayList<>(); - - Either, StorageOperationStatus> interfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(resourceId, false, true); - if (interfacesOfResource.isRight()) { - log.error("failed to get all resource interfaces. resource id={}. status ={}", resourceId, interfacesOfResource.right().value()); - return Either.right(interfacesOfResource.right().value()); - } - - Map interfaces = interfacesOfResource.left().value(); - if (interfaces != null && !interfaces.isEmpty()) { - for (Entry entry : interfaces.entrySet()) { - - InterfaceDefinition interfaceDefinition = entry.getValue(); - Map operations = interfaceDefinition.getOperationsMap(); - if (operations != null && !operations.isEmpty()) { - for (Entry opEntry : operations.entrySet()) { - - Operation operation = opEntry.getValue(); - ArtifactDefinition artifactDefinition = operation.getImplementationArtifact(); - if (artifactDefinition != null) { - artifacts.add(artifactDefinition); - } - } - } - } - } - return Either.left(artifacts); - } - - @SuppressWarnings("unchecked") - public Either, StorageOperationStatus> getFollowed(String userId, Set lifecycleStates, Set lastStateStates, boolean inTransaction) { - return (Either, StorageOperationStatus>) (Either) getFollowedComponent(userId, lifecycleStates, lastStateStates, inTransaction, titanGenericDao, NodeTypeEnum.Resource); - } - - @SuppressWarnings("unchecked") - @Override - public Either getComponent(String id, boolean inTransaction) { - return (Either) getResource(id, inTransaction); - } - - // @Override - // public Either getComponent_tx(String id, - // boolean inTransaction) { - // return (Either) getResource_tx(id, - // inTransaction); - // } - - private Optional> validateCategoryHierarcy(List> childNodes, String subCategoryName) { - Predicate> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName().equals(subCategoryName); - return childNodes.stream().filter(matchName).findAny(); - } - - private Either>, StorageOperationStatus> getAllSubCategories(String categoryName) { - Either categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class); - if (categoryResult.isRight()) { - return Either.right(categoryResult.right().value()); - } - CategoryData categoryData = categoryResult.left().value(); - - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(), - GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class); - if (childrenNodes.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenNodes.right().value())); - } - return Either.left(childrenNodes.left().value()); - } - - @Override - public Either, StorageOperationStatus> getFilteredComponents(Map filters, boolean inTransaction) { - - String subCategoryName = filters.get(FilterKeyEnum.SUB_CATEGORY); - String categoryName = filters.get(FilterKeyEnum.CATEGORY); - ResourceTypeEnum resourceType = ResourceTypeEnum.getType( filters.get(FilterKeyEnum.RESOURCE_TYPE)); - Either>, StorageOperationStatus> subcategories = null; - Optional> subCategoryData; - - if (categoryName != null) { - subcategories = getAllSubCategories(categoryName); - if (subcategories.isRight()) { - filters.remove(FilterKeyEnum.SUB_CATEGORY); - return Either.right(subcategories.right().value()); - } - } - if (subCategoryName != null) { // primary filter - if (categoryName != null) { - subCategoryData = validateCategoryHierarcy(subcategories.left().value(), subCategoryName); - if (!subCategoryData.isPresent()) { - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - return fetchByCategoryOrSubCategoryUid((String) subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, - ResourceMetadataData.class, resourceType); - } - - return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class, resourceType); - } - if(subcategories != null){ - return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType); - } - return fetchByResourceType(NodeTypeEnum.Resource, filters.get(FilterKeyEnum.RESOURCE_TYPE), ResourceMetadataData.class, inTransaction); - } - - @SuppressWarnings("unchecked") - private Either, StorageOperationStatus> fetchByResourceType(NodeTypeEnum nodeType, String resourceType, - Class clazz, boolean inTransaction) { - List components = null; - TitanOperationStatus status; - Wrapper statusWrapper = new Wrapper<>(); - Either, StorageOperationStatus> result; - try { - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType); - props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - Either, TitanOperationStatus> getResources = titanGenericDao.getByCriteria(nodeType, props, clazz); - if (getResources.isRight()) { - status = getResources.right().value(); - if(status != TitanOperationStatus.NOT_FOUND){ - statusWrapper.setInnerElement(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - }else{ - components = new ArrayList<>(); - } - }else{ - components = getResources.left().value().stream(). - map(c->(T)convertComponentMetadataDataToComponent(c)).collect(Collectors.toList()); - } - if(!statusWrapper.isEmpty()){ - result = Either.right(statusWrapper.getInnerElement()); - }else{ - result = Either.left(components); - } - return result; - } finally { - if (!inTransaction) { - titanGenericDao.commit(); - } - } - } - - private Either, StorageOperationStatus> fetchByMainCategory(List> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) { - List components = new ArrayList<>(); - - for (ImmutablePair subCategory : subcategories) { - Either, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid((String) subCategory.getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, - inTransaction, ResourceMetadataData.class, resourceType); - if (fetched.isRight()) { - // return fetched; - continue; - } - components.addAll(fetched.left().value()); - } - return Either.left(components); - } - - @Override - public Either getLightComponent(String id, boolean inTransaction) { - return getLightComponent(id, NodeTypeEnum.Resource, inTransaction); - } - - // will be implement later - @Override - protected ComponentMetadataData getMetaDataFromComponent(Component component) { - return getResourceMetaDataFromResource((Resource) component); - } - - @Override - public Either, StorageOperationStatus> getCatalogData(Map propertiesToMatch, boolean inTransaction) { - return getComponentCatalogData(NodeTypeEnum.Resource, propertiesToMatch, Resource.class, ResourceMetadataData.class, inTransaction); - } - - @Override - public Either, StorageOperationStatus> getAllDerivedResources(Resource resource) { - try { - Either>, TitanOperationStatus> childrenNodes = getDerivingChildren(resource); - return childrenNodes.either((childrenPairs) -> convertToResources(PairUtils.leftSequence(childrenPairs)), - (status) -> Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status))); - } finally { - titanGenericDao.commit(); - } - } - - @Override - public Either, StorageOperationStatus> getRootResources() { - Map rootToscaResource = new HashMap<>(); - rootToscaResource.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), Resource.ROOT_RESOURCE); - return getResourceListByCriteria(rootToscaResource, false); - } - - @Override - public Either, StorageOperationStatus> getVFResources() { - Map rootToscaResource = new HashMap<>(); - rootToscaResource.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF); - return getResourceListByCriteria(rootToscaResource, false); - } - - private Either>, TitanOperationStatus> getDerivingChildren(Resource resource) { - return titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class); - } - - private Either, StorageOperationStatus> convertToResources(List resourcesMetaData) { - List resources = new ArrayList<>(); - for (ResourceMetadataData resourceMetadataData : resourcesMetaData) { - String uniqueId = resourceMetadataData.getMetadataDataDefinition().getUniqueId(); - Either resource = this.getResource(uniqueId); - if (resource.isRight()) { - StorageOperationStatus status = resource.right().value(); - log.error("Failed to fetch resource {} . status is {}", uniqueId, status); - return Either.right(status); - } - resources.add(resource.left().value()); - } - return Either.left(resources); - } - - protected TitanOperationStatus findResourcesPathRecursively(String resourceId, List resourcesPathList) { - - Either nodeRes = this.titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, ResourceMetadataData.class); - - if (nodeRes.isRight()) { - TitanOperationStatus status = nodeRes.right().value(); - log.error("Failed to fetch resource {} . status is {}", resourceId, status); - return status; - } - - ResourceMetadataData resourceData = nodeRes.left().value(); - resourcesPathList.add(resourceData); - Either, TitanOperationStatus> parentResourceRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, - NodeTypeEnum.Resource, ResourceMetadataData.class); - - while (parentResourceRes.isLeft()) { - - ImmutablePair value = parentResourceRes.left().value(); - ResourceMetadataData parentResourceData = value.getKey(); - - resourcesPathList.add(parentResourceData); - - parentResourceRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), parentResourceData.getMetadataDataDefinition().getUniqueId(), GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, - ResourceMetadataData.class); - } - - TitanOperationStatus operationStatus = parentResourceRes.right().value(); - - if (operationStatus != TitanOperationStatus.NOT_FOUND) { - return operationStatus; - } else { - return TitanOperationStatus.OK; - } - - } - - @SuppressWarnings("unchecked") - @Override - public Either updateComponent(T component, boolean inTransaction) { - return (Either) updateResource((Resource) component, inTransaction); - } - - @SuppressWarnings("unchecked") - @Override - public Either deleteComponent(String id, boolean inTransaction) { - return (Either) (Either) deleteResource(id, inTransaction); - } - - @Override - public Either getLatestByToscaResourceName(String toscaResourceName, boolean inTransaction) { - return getLatestByName(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), toscaResourceName, inTransaction); - - } - - @Override - public Either getLatestByName(String resourceName, boolean inTransaction) { - return getLatestByName(GraphPropertiesDictionary.NAME.getProperty(), resourceName, inTransaction); - - } - - private Either getLatestByName(String property, String resourceName, boolean inTransaction) { - Either result = null; - try { - Map props = new HashMap(); - props.put(property, resourceName); - props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - - Either, TitanOperationStatus> highestResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); - if (highestResources.isRight()) { - TitanOperationStatus status = highestResources.right().value(); - log.debug("failed to find resource with name {}. status={} ", resourceName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - List resources = highestResources.left().value(); - double version = 0.0; - ResourceMetadataData highestResource = null; - for (ResourceMetadataData resource : resources) { - double resourceVersion = Double.parseDouble(resource.getMetadataDataDefinition().getVersion()); - if (resourceVersion > version) { - version = resourceVersion; - highestResource = resource; - } - } - result = getResource(highestResource.getMetadataDataDefinition().getUniqueId(), true); - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.error("getLatestByName operation : Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("getLatestByName operation : Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - - } - } - - @SuppressWarnings("unchecked") - @Override - public Either, StorageOperationStatus> getTesterFollowed(String userId, Set lifecycleStates, boolean inTransaction) { - return (Either, StorageOperationStatus>) (Either) getTesterFollowedComponent(userId, lifecycleStates, inTransaction, NodeTypeEnum.Resource); - } - - @Override - public Either, StorageOperationStatus> getResourceCatalogData(boolean inTransaction) { - return getResourceCatalogData(inTransaction, null); - } - - private Either, StorageOperationStatus> getResourceCatalogData(boolean inTransaction, Map otherToMatch) { - - long start = System.currentTimeMillis(); - - long startFetchAllStates = System.currentTimeMillis(); - Map propertiesToMatchHigest = new HashMap<>(); - propertiesToMatchHigest.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - propertiesToMatchHigest.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), false); - Either, TitanOperationStatus> allHighestStates = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatchHigest, ResourceMetadataData.class); - if (allHighestStates.isRight() && allHighestStates.right().value() != TitanOperationStatus.NOT_FOUND) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allHighestStates.right().value())); - } - - if (allHighestStates.isRight()) { - return Either.left(new ArrayList<>()); - } - List list = allHighestStates.left().value(); - - List certified = new ArrayList<>(); - List noncertified = new ArrayList<>(); - for (ResourceMetadataData reData : list) { - if (reData.getMetadataDataDefinition().getState().equals(LifecycleStateEnum.CERTIFIED.name())) { - certified.add(reData); - } else { - noncertified.add(reData); - } - } - - long endFetchAll = System.currentTimeMillis(); - log.debug("Fetch catalog resources all states: certified {}, noncertified {}", certified.size(), noncertified.size()); - log.debug("Fetch catalog resources all states from graph took {} ms", endFetchAll - startFetchAllStates); - - try { - List notCertifiedHighest = noncertified; - List certifiedHighestList = certified; - - HashMap VFNames = new HashMap<>(); - HashMap VFCNames = new HashMap<>(); - for (ResourceMetadataData data : notCertifiedHighest) { - String serviceName = data.getMetadataDataDefinition().getName(); - if (((ResourceMetadataDataDefinition) data.getMetadataDataDefinition()).getResourceType().equals(ResourceTypeEnum.VF)) { - VFNames.put(serviceName, serviceName); - } else { - VFCNames.put(serviceName, serviceName); - } - } - - for (ResourceMetadataData data : certifiedHighestList) { - String serviceName = data.getMetadataDataDefinition().getName(); - if (((ResourceMetadataDataDefinition) data.getMetadataDataDefinition()).getResourceType().equals(ResourceTypeEnum.VF)) { - if (!VFNames.containsKey(serviceName)) { - notCertifiedHighest.add(data); - } - } else { - if (!VFCNames.containsKey(serviceName)) { - notCertifiedHighest.add(data); - } - } - } - - long endFetchAllFromGraph = System.currentTimeMillis(); - log.debug("Fetch all catalog resources metadata from graph took {} ms", endFetchAllFromGraph - start); - - long startFetchAllFromCache = System.currentTimeMillis(); - - List result = new ArrayList<>(); - - Map components = notCertifiedHighest.stream().collect(Collectors.toMap(p -> p.getMetadataDataDefinition().getUniqueId(), p -> p.getMetadataDataDefinition().getLastUpdateDate())); - - Either, Set>, ActionStatus> componentsForCatalog = componentCache.getComponentsForCatalog(components, ComponentTypeEnum.RESOURCE); - if (componentsForCatalog.isLeft()) { - ImmutablePair, Set> immutablePair = componentsForCatalog.left().value(); - List foundComponents = immutablePair.getLeft(); - if (foundComponents != null) { - foundComponents.forEach(p -> result.add((Resource) p)); - log.debug("The number of resources added to catalog from cache is {}", foundComponents.size()); - - List foundComponentsUid = foundComponents.stream().map(p -> p.getUniqueId()).collect(Collectors.toList()); - notCertifiedHighest = notCertifiedHighest.stream().filter(p -> false == foundComponentsUid.contains(p.getUniqueId())).collect(Collectors.toList()); - } - Set nonCachedComponents = immutablePair.getRight(); - int numberNonCached = nonCachedComponents == null ? 0 : nonCachedComponents.size(); - log.debug("The number of left resources for catalog is {}", numberNonCached); - - } - - long endFetchAllFromCache = System.currentTimeMillis(); - log.debug("Fetch all catalog resources metadata from cache took {} ms", (endFetchAllFromCache - startFetchAllFromCache)); - - long startFetchFromGraph = System.currentTimeMillis(); - log.debug("The number of resources needed to be fetch as light component is {}", notCertifiedHighest.size()); - for (ResourceMetadataData data : notCertifiedHighest) { - String uniqueId = data.getMetadataDataDefinition().getUniqueId(); - log.trace("Fetch catalog resource non cached {} {}", uniqueId, data.getMetadataDataDefinition().getName()); - Either component = getLightComponent(uniqueId, inTransaction); - if (component.isRight()) { - log.debug("Failed to get Service for id = {} error : {} skip resource", data.getUniqueId(), component.right().value()); - } else { - result.add(component.left().value()); - } - } - long endFetchFromGraph = System.currentTimeMillis(); - log.debug("Fetch catalog resources from graph took {} ms", (endFetchFromGraph - startFetchFromGraph)); - - return Either.left(result); - - } finally { - long end = System.currentTimeMillis(); - log.debug("Fetch all catalog resources took {} ms", end - start); - if (false == inTransaction) { - titanGenericDao.commit(); - } - } - } - - public Either, StorageOperationStatus> getResourceCatalogDataVFLatestCertifiedAndNonCertified(boolean inTransaction) { - Map propertiesToMatch = new HashMap<>(); - propertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name()); - - return getResourceCatalogDataLatestCertifiedAndNonCertified(inTransaction, propertiesToMatch); - } - - public Either, StorageOperationStatus> getResourceCatalogDataLatestCertifiedAndNonCertified(boolean inTransaction, Map otherToMatch) { - Map propertiesToMatch = new HashMap<>(); - - if (otherToMatch != null) { - propertiesToMatch.putAll(otherToMatch); - } - - propertiesToMatch.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - - Either, TitanOperationStatus> lastVersionNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class); - - List result = new ArrayList<>(); - - if (lastVersionNodes.isRight() && lastVersionNodes.right().value() != TitanOperationStatus.NOT_FOUND) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(lastVersionNodes.right().value())); - } - - List listOfHighest; - - if (lastVersionNodes.isLeft()) { - listOfHighest = lastVersionNodes.left().value(); - } else { - return Either.left(result); - } - - for (ResourceMetadataData data : listOfHighest) { - Either component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction); - if (component.isRight()) { - log.debug("Failed to get Service for id = {} error : {} skip resource", data.getUniqueId(), component.right().value()); - } else { - result.add(component.left().value()); - } - } - return Either.left(result); - } - - private Either, StorageOperationStatus> getResourceListByCriteria(Map props, boolean inTransaction) { - - props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName()); - - Either, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); - - if (byCriteria.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value())); - } - List resources = new ArrayList<>(); - List resourcesDataList = byCriteria.left().value(); - for (ResourceMetadataData data : resourcesDataList) { - buildResource(inTransaction, resources, data); - } - return Either.left(resources); - } - - private void buildResource(boolean inTransaction, List resources, ResourceMetadataData data) { - Either resource = getResource(data.getMetadataDataDefinition().getUniqueId(), inTransaction); - if (resource.isLeft()) { - resources.add(resource.left().value()); - } else { - log.debug("Failed to fetch resource for name = {} and id = {}", data.getUniqueId(), data.getMetadataDataDefinition().getName()); - } - } - - public Either, StorageOperationStatus> getResourceListByUuid(String uuid, boolean inTransaction) { - return getLatestResourceByUuid(uuid, false, inTransaction); - } - - public Either, StorageOperationStatus> getLatestResourceByUuid(String uuid, boolean inTransaction) { - return getLatestResourceByUuid(uuid, true, inTransaction); - } - - private Either, StorageOperationStatus> getLatestResourceByUuid(String uuid, boolean isLatest, boolean inTransaction) { - Map props = new HashMap(); - if (isLatest) { - props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), isLatest); - } - props.put(GraphPropertiesDictionary.UUID.getProperty(), uuid); - return getResourceListByCriteria(props, inTransaction); - } - - public Either, StorageOperationStatus> getResourceListBySystemName(String systemName, boolean inTransaction) { - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), systemName); - return getResourceListByCriteria(props, inTransaction); - } - - public Either, StorageOperationStatus> getResourceListByToscaName(String toscaName, boolean inTransaction) { - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), toscaName); - return getResourceListByCriteria(props, inTransaction); - } - - public Either, StorageOperationStatus> getResourceByNameAndVersion(String name, String version, boolean inTransaction) { - return getByNamesAndVersion(GraphPropertiesDictionary.NAME.getProperty(), name, version, null, inTransaction); - } - - @Override - public Either, StorageOperationStatus> getResourceByNameAndVersion(String name, String version) { - return getResourceByNameAndVersion(name, version, false); - } - - protected Either, StorageOperationStatus> getByNamesAndVersion(String nameKey, String nameValue, String version, Map additionalParams, boolean inTransaction) { - Map props = new HashMap(); - props.put(nameKey, nameValue); - props.put(GraphPropertiesDictionary.VERSION.getProperty(), version); - props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName()); - if (additionalParams != null && !additionalParams.isEmpty()) { - props.putAll(additionalParams); - } - - Either, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); - List resourcesList = new ArrayList(); - if (byCriteria.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value())); - } - List dataList = byCriteria.left().value(); - if (dataList != null && !dataList.isEmpty()) { - for (ResourceMetadataData resourceData : dataList) { - // ResourceMetadataData resourceData = dataList.get(0); - Either resource = getResource(resourceData.getMetadataDataDefinition().getUniqueId(), inTransaction); - if (resource.isRight()) { - log.debug("Failed to fetch resource for name = {} and id = {}", resourceData.getMetadataDataDefinition().getName(), resourceData.getUniqueId()); - return Either.right(resource.right().value()); - } - resourcesList.add(resource.left().value()); - } - // return resource; - return Either.left(resourcesList); - } else { - return Either.right(StorageOperationStatus.NOT_FOUND); - } - } - - @Override - protected Either getComponentByNameAndVersion(String name, String version, Map additionalParams, boolean inTransaction) { - return (Either) getResourceBySystemNameAndVersion(name, version, additionalParams, inTransaction); - } - - @Override - public Either getResourceBySystemNameAndVersion(String name, String version, Map additionalParams, boolean inTransaction) { - Either, StorageOperationStatus> byNamesAndVersion = getByNamesAndVersion(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normaliseComponentName(name), version, additionalParams, inTransaction); - if (byNamesAndVersion.isRight()) { - return Either.right(byNamesAndVersion.right().value()); - } - List resourcesList = byNamesAndVersion.left().value(); - if (resourcesList.size() > 1) { - log.debug("More that one instance of resource for name = {} and version = {}", name, version); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - return Either.left(resourcesList.get(0)); - } - - private TitanOperationStatus setAllVersions(Resource resource) { - Either, TitanOperationStatus> res = getVersionList(NodeTypeEnum.Resource, resource.getVersion(), resource, ResourceMetadataData.class); - if (res.isRight()) { - return res.right().value(); - } - resource.setAllVersions(res.left().value()); - return TitanOperationStatus.OK; - } - - @Override - protected Either, TitanOperationStatus> getVersionList(NodeTypeEnum type, String version, Component component, Class clazz) { - Map props = new HashMap(); - Map hasNotProps = new HashMap(); - - if (version.startsWith("0")) { - props.put(GraphPropertiesDictionary.UUID.getProperty(), component.getUUID()); - } else { - props.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), component.getSystemName()); - props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ((Resource) component).getResourceType().name()); - } - hasNotProps.put(GraphPropertiesDictionary.IS_DELETED.getProperty(), true); - Either, TitanOperationStatus> result = titanGenericDao.getByCriteria(type, props, hasNotProps, clazz); - - Map versionMap = new HashMap(); - if (result.isRight()) { - if (!result.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - return Either.right(result.right().value()); - } - - } else { - List components = (List) result.left().value(); - for (ResourceMetadataData data : components) { - versionMap.put(data.getMetadataDataDefinition().getVersion(), (String) data.getUniqueId()); - } - } - - return Either.left(versionMap); - } - - /** - * update only the resource object itself without tag, derived from or any other neighbours. - * - * @param resource - * @param inTransaction - * @return - */ - protected Either updateResourceMetadata(Resource resource, boolean inTransaction) { - - Either result = null; - - try { - - log.debug("In updateResource. received resource = {}", (resource == null ? null : resource.toString())); - if (resource == null) { - log.error("Resource object is null"); - result = Either.right(StorageOperationStatus.BAD_REQUEST); - return result; - } - - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(resource.getUniqueId()); - resourceData.getMetadataDataDefinition().setHighestVersion(resource.isHighestVersion()); - log.debug("After converting resource to ResourceData. ResourceData = {}", resourceData); - - if (resourceData.getUniqueId() == null) { - log.error("Resource id is missing in the request."); - return Either.right(StorageOperationStatus.BAD_REQUEST); - } - - Either updateNode = titanGenericDao.updateNode(resourceData, ResourceMetadataData.class); - - if (updateNode.isRight()) { - log.error("Failed to update resource {}. status is {}", resource.getUniqueId(), updateNode.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); - return result; - } - - Either updatedResource = getResource(resource.getUniqueId(), true); - if (updatedResource.isRight()) { - log.error("Resource id is missing in the request. status is {}", updatedResource.right().value()); - result = Either.right(StorageOperationStatus.BAD_REQUEST); - return result; - } - - Resource updatedResourceValue = updatedResource.left().value(); - result = Either.left(updatedResourceValue); - - if (log.isDebugEnabled()) { - String json = prettyJson.toJson(result.left().value()); - log.debug("Resource retrieved after update is {}", json); - } - - return result; - - } finally { - if (false == inTransaction) { - 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, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) { - - try { - List result = new ArrayList<>(); - Map propertiesToMatch = new HashMap<>(); - propertiesToMatch.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), isAbstract); - propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); - - if (isHighest != null) { - propertiesToMatch.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), isHighest.booleanValue()); - } - - Either, TitanOperationStatus> resourceNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class); - - titanGenericDao.commit(); - if (resourceNodes.isRight()) { - // in case of NOT_FOUND from Titan client return to UI empty - // list - if (resourceNodes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - return Either.left(result); - } else { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceNodes.right().value())); - } - } else { - List resourceDataList = resourceNodes.left().value(); - for (ResourceMetadataData resourceData : resourceDataList) { - Either resource = getResource(resourceData.getMetadataDataDefinition().getUniqueId()); - if (resource.isRight()) { - log.debug("Failed to fetch resource for id = {} error is {}", resourceData.getUniqueId(), resource.right().value()); - return Either.right(resource.right().value()); - } - result.add(resource.left().value()); - } - return Either.left(result); - } - } finally { - titanGenericDao.commit(); - } - - } - - public Either getLatestCertifiedByToscaResourceName(String toscaResourceName, boolean inTransaction) { - return getLatestCertifiedByCriteria(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), toscaResourceName, inTransaction); - - } - - public Either getLatestCertifiedByCriteria(String property, String resourceName, boolean inTransaction) { - Either result = null; - try { - Map props = new HashMap(); - props.put(property, resourceName); - props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); - - Either, TitanOperationStatus> highestResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); - if (highestResources.isRight()) { - TitanOperationStatus status = highestResources.right().value(); - log.debug("failed to find resource with name {}. status={} ", resourceName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - List resources = highestResources.left().value(); - double version = 0.0; - ResourceMetadataData highestResource = null; - for (ResourceMetadataData resource : resources) { - double resourceVersion = Double.parseDouble(resource.getMetadataDataDefinition().getVersion()); - if (resourceVersion > version) { - version = resourceVersion; - highestResource = resource; - } - } - result = getResource(highestResource.getMetadataDataDefinition().getUniqueId(), true); - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.error("getLatestByName operation : Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("getLatestByName operation : Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - - } - } - - public Either, StorageOperationStatus> findLastCertifiedResourceByName(Resource resource) { - - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), resource.getName()); - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); - return getResourceListByCriteria(props, false); - - } - - public Either, StorageOperationStatus> findLastCertifiedResourceByUUID(Resource resource) { - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.UUID.getProperty(), resource.getUUID()); - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); - return getResourceListByCriteria(props, false); - - } - - @Override - public boolean isComponentExist(String resourceId) { - return isComponentExist(resourceId, NodeTypeEnum.Resource); - } - - @Override - public Either cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) { - return (Either) cloneResource((Resource) other, version, targetLifecycle, inTransaction); - } - - @Override - public Either increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction) { - return increaseAndGetComponentInstanceCounter(componentId, NodeTypeEnum.Resource, inTransaction); - } - - private Either cloneResource(Resource other, String version, boolean inTransaction) { - return cloneResource(other, version, null, inTransaction); - } - - private Either cloneResource(Resource other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) { - Either result = null; - - try { - String origRsourceId = other.getUniqueId(); - - StorageOperationStatus overrideStatus = overrideRecursiveMembers(other, origRsourceId); - if (!overrideStatus.equals(StorageOperationStatus.OK)) { - return Either.right(overrideStatus); - } - other.setVersion(version); - other.setUniqueId(null); - - List inputs = other.getInputs(); - Map> inputsPropMap = new HashMap>(); - - if(inputs != null){ - for(InputDefinition input: inputs){ - - Either, TitanOperationStatus> inputPropStatus = inputOperation.getComponentInstancePropertiesByInputId(input.getUniqueId()); - if(inputPropStatus.isLeft()){ - if(inputPropStatus.left().value() != null) - inputsPropMap.put(input.getName(), inputPropStatus.left().value()); - - } - - - } - } - - Either createResourceMD = createResource(other, inTransaction); - if (createResourceMD.isRight()) { - StorageOperationStatus status = createResourceMD.right().value(); - log.error("failed to clone resource. status= {}", status); - result = Either.right(status); - return result; - } - Resource resource = createResourceMD.left().value(); - Either metadataVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resource.getUniqueId()); - if (metadataVertexEither.isRight()) { - TitanOperationStatus error = metadataVertexEither.right().value(); - log.debug("Failed to fetch vertex of metadata {} error {}", resource.getUniqueId(), error); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - return result; - } - - TitanVertex metadataVertex = metadataVertexEither.left().value(); - Either, Map>, StorageOperationStatus> cloneInstances = componentInstanceOperation.cloneAllComponentInstancesFromContainerComponent(origRsourceId, resource.getUniqueId(), - NodeTypeEnum.Resource, NodeTypeEnum.Resource, targetLifecycle, metadataVertex, other, resource, inputsPropMap); - if (cloneInstances.isRight()) { - result = Either.right(cloneInstances.right().value()); - return result; - } - - Either counterStatus = getComponentInstanceCoutner(origRsourceId, NodeTypeEnum.Resource); - if (counterStatus.isRight()) { - StorageOperationStatus status = counterStatus.right().value(); - log.error("failed to get resource instance counter on service {}. status={}", origRsourceId, counterStatus); - result = Either.right(status); - return result; - } - - Either setResourceInstanceCounter = setComponentInstanceCounter(resource.getUniqueId(), NodeTypeEnum.Resource, counterStatus.left().value(), true); - if (setResourceInstanceCounter.isRight()) { - StorageOperationStatus status = setResourceInstanceCounter.right().value(); - log.error("failed to set resource instance counter on service {}. status={}", resource.getUniqueId(), status); - result = Either.right(status); - return result; - } - - Either, StorageOperationStatus> clonedGroups = cloneGroups(other, resource, cloneInstances.left().value(), true); - if (clonedGroups.isRight()) { - StorageOperationStatus status = clonedGroups.right().value(); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - return result; - } - } - - result = this.getResource(resource.getUniqueId(), true); - if (result.isRight()) { - log.error("Cannot get full service from the graph. status is {}", result.right().value()); - return Either.right(result.right().value()); - } - - return result; - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - } - - private StorageOperationStatus overrideRecursiveMembers(Resource resource, String prevId) { - // override requirements to copy only resource's requirements and not - // derived requirements - Either>, StorageOperationStatus> requirementsOfResourceOnly = getRequirementOperation().getAllRequirementsOfResourceOnly(prevId, true); - if (requirementsOfResourceOnly.isRight()) { - log.error("failed to get requirements of resource. resourceId {} status is {}", prevId, requirementsOfResourceOnly.right().value()); - return requirementsOfResourceOnly.right().value(); - } - resource.setRequirements(requirementsOfResourceOnly.left().value()); - - // override capabilities to copy only resource's requirements and not - // derived requirements - Either>, StorageOperationStatus> capabilitiesOfResourceOnly = getResourceCapabilitiesMap(prevId); - - resource.setCapabilities(capabilitiesOfResourceOnly.left().value()); - - // override interfaces to copy only resource's interfaces and not - // derived interfaces - Either, StorageOperationStatus> interfacesOfResourceOnly = getInterfaceLifecycleOperation().getAllInterfacesOfResource(prevId, false, true); - if (interfacesOfResourceOnly.isRight()) { - log.error("failed to get interfaces of resource. resourceId {} status is {}", prevId, interfacesOfResourceOnly.right().value()); - return interfacesOfResourceOnly.right().value(); - } - resource.setInterfaces(interfacesOfResourceOnly.left().value()); - - List attributes = new ArrayList<>(); - TitanOperationStatus status = attributeOperation.findNodeNonInheretedAttribues(prevId, NodeTypeEnum.Resource, attributes); - if (status != TitanOperationStatus.OK) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } else { - resource.setAttributes(attributes); - } - - // override properties to copy only resource's properties and not - // derived properties - Either, TitanOperationStatus> propertiesOfResourceOnly = getPropertyOperation().findPropertiesOfNode(NodeTypeEnum.Resource, prevId); - - List resourceProperties = null; - if (propertiesOfResourceOnly.isRight()) { - TitanOperationStatus titanStatus = propertiesOfResourceOnly.right().value(); - if (titanStatus != TitanOperationStatus.NOT_FOUND) { - log.error("failed to get properties of resource. resourceId {} status is {}", prevId, propertiesOfResourceOnly.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); - } - } else { - Map propertiesMap = propertiesOfResourceOnly.left().value(); - if (propertiesMap != null) { - resourceProperties = new ArrayList(); - resourceProperties.addAll(propertiesMap.values()); - } - } - resource.setProperties(resourceProperties); - - return StorageOperationStatus.OK; - } - - private Either>, StorageOperationStatus> getResourceCapabilitiesMap(String prevId) { - - Either, StorageOperationStatus> capabilitiesOfResourceOnly = getCapabilityOperation().getAllCapabilitiesOfResource(prevId, false, true); - if (capabilitiesOfResourceOnly.isRight()) { - log.error("failed to get capabilities of resource. resourceId {} status is {}", prevId, capabilitiesOfResourceOnly.right().value()); - return Either.right(capabilitiesOfResourceOnly.right().value()); - } - Map> capabilityMap = getCapabilityOperation().convertCapabilityMap(capabilitiesOfResourceOnly.left().value(), null, null); - return Either.left(capabilityMap); - } - - @Override - protected StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type) { - StorageOperationStatus status = StorageOperationStatus.OK; - List newCategoryList = component.getCategories(); - CategoryDefinition newCategory = newCategoryList.get(0); - CategoryDefinition currentCategory = currentComponent.getCategories().get(0); - boolean categoryWasChanged = false; - - if (newCategory.getName() != null && false == newCategory.getName().equals(currentCategory.getName())) { - // the category was changed - categoryWasChanged = true; - } else { - // the sub-category was changed - SubCategoryDefinition currSubcategory = currentCategory.getSubcategories().get(0); - SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0); - if (newSubcategory.getName() != null && false == newSubcategory.getName().equals(currSubcategory.getName())) { - log.debug("Going to update the category of the resource from {} to {}", currentCategory, newCategory); - categoryWasChanged = true; - } - } - if (categoryWasChanged) { - status = moveCategoryEdge((Resource) component, (ResourceMetadataData) componentData, newCategory); - log.debug("Going to update the category of the resource from {} to {}. status is {}", currentCategory, newCategory, status); - } - return status; - } - - @Override - public Resource getDefaultComponent() { - return new Resource(); - } - - @Override - public Either getMetadataComponent(String id, boolean inTransaction) { - return getMetadataComponent(id, NodeTypeEnum.Resource, inTransaction); - } - - @Override - Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData) { - return convertResourceDataToResource((ResourceMetadataData) componentMetadataData); - } - - @Override - public Either validateComponentNameExists(String componentName) { - return validateComponentNameUniqueness(componentName, titanGenericDao, NodeTypeEnum.Resource); - } - - @Override - public Either markComponentToDelete(Component componentToDelete, boolean inTransaction) { - return internalMarkComponentToDelete(componentToDelete, inTransaction); - } - - @Override - public Either isComponentInUse(String componentId) { - return isResourceInUse(componentId); - } - - @Override - public Either, StorageOperationStatus> getAllComponentsMarkedForDeletion() { - return getAllResourcesMarkedForDeletion(); - } - - @Override - public Either, StorageOperationStatus> getAllResourcesMarkedForDeletion() { - return getAllComponentsMarkedForDeletion(NodeTypeEnum.Resource); - } - - @Override - public Either isResourceInUse(String resourceToDelete) { - return isComponentInUse(resourceToDelete, NodeTypeEnum.Resource); - } - - public Either, StorageOperationStatus> cloneGroups(Resource resource, Resource newResource, ImmutablePair, Map> cloneInstances, boolean inTransaction) { - - Either, StorageOperationStatus> result = null; - - if (resource.getGroups() == null) { - return Either.right(StorageOperationStatus.OK); - } - - Either, StorageOperationStatus> prepareGroupsForCloning = groupOperation.prepareGroupsForCloning(resource, cloneInstances); - if (prepareGroupsForCloning.isRight()) { - StorageOperationStatus status = prepareGroupsForCloning.right().value(); - if (status != StorageOperationStatus.OK) { - BeEcompErrorManager.getInstance().logInternalFlowError("CloneResource", "Failed to prepare groups for cloning", ErrorSeverity.ERROR); - } - result = Either.right(status); - return result; - } else { - List groupsToCreate = prepareGroupsForCloning.left().value(); - if (groupsToCreate != null && false == groupsToCreate.isEmpty()) { - Either, StorageOperationStatus> addGroups = groupOperation.addGroups(NodeTypeEnum.Resource, newResource.getUniqueId(), groupsToCreate, inTransaction); - if (addGroups.isRight()) { - BeEcompErrorManager.getInstance().logInternalFlowError("CloneResource", "Failed to clone groups", ErrorSeverity.ERROR); - result = Either.right(addGroups.right().value()); - return result; - } - - return Either.left(addGroups.left().value()); - } else { - return Either.right(StorageOperationStatus.OK); - } - } - } - - public Either getLatestResourceByCsarOrName(String csarUUID, String systemName) { - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.CSAR_UUID.getProperty(), csarUUID); - props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - ResourceMetadataData resourceMetadataData = null; - List resourceMetadataDataList = null; - Either, TitanOperationStatus> byCsar = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); - if (byCsar.isRight()) { - if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) { - //Fix Defect DE256036 - if( StringUtils.isEmpty(systemName)){ - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND)); - } - - props.clear(); - props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - props.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), systemName); - Either, TitanOperationStatus> bySystemname = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); - if (bySystemname.isRight()) { - log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value())); - } - if (bySystemname.left().value().size() > 2) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - resourceMetadataDataList = bySystemname.left().value(); - if (resourceMetadataDataList.size() == 1) { - resourceMetadataData = resourceMetadataDataList.get(0); - } else { - for (ResourceMetadataData curResource : resourceMetadataDataList) { - if (!curResource.getMetadataDataDefinition().getState().equals("CERTIFIED")) { - resourceMetadataData = curResource; - break; - } - } - } - if (resourceMetadataData == null) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions"); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - if (resourceMetadataData.getMetadataDataDefinition().getCsarUUID() != null && !resourceMetadataData.getMetadataDataDefinition().getCsarUUID().equals(csarUUID)) { - log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getMetadataDataDefinition().getCsarUUID(), csarUUID); - // correct error will be returned from create flow. with all - // correct audit records!!!!! - return Either.right(StorageOperationStatus.NOT_FOUND); - } - Either resource = getResource((String) resourceMetadataData.getUniqueId()); - return resource; - } - } else { - resourceMetadataDataList = byCsar.left().value(); - if (resourceMetadataDataList.size() > 2) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - if (resourceMetadataDataList.size() == 1) { - resourceMetadataData = resourceMetadataDataList.get(0); - } else { - for (ResourceMetadataData curResource : resourceMetadataDataList) { - if (!curResource.getMetadataDataDefinition().getState().equals("CERTIFIED")) { - resourceMetadataData = curResource; - break; - } - } - } - if (resourceMetadataData == null) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions"); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - Either resource = getResource((String) resourceMetadataData.getMetadataDataDefinition().getUniqueId()); - return resource; - } - return null; - } - - public Either, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) { - - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.CSAR_UUID.getProperty(), csarUUID); - - Either, TitanOperationStatus> byCsar = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); - if (byCsar.isRight()) { - if (TitanOperationStatus.NOT_FOUND.equals(byCsar.right().value())) { - return Either.left(null); - } else { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCsar.right().value())); - } - } - return Either.left(byCsar.left().value()); - } - - public Either getResource(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction) { - - Resource resource = null; - try { - - NodeTypeEnum resourceNodeType = NodeTypeEnum.Resource; - NodeTypeEnum compInstNodeType = NodeTypeEnum.Resource; - - Either componentByLabelAndId = getComponentByLabelAndId(uniqueId, resourceNodeType, ResourceMetadataData.class); - if (componentByLabelAndId.isRight()) { - return Either.right(componentByLabelAndId.right().value()); - } - ResourceMetadataData resourceData = componentByLabelAndId.left().value(); - - // Try to fetch resource from the cache. The resource will be - // fetched only if the time on the cache equals to - // the time on the graph. - Either componentFromCacheIfUpToDate = this.getComponentFromCacheIfUpToDate(uniqueId, resourceData, componentParametersView, Resource.class, ComponentTypeEnum.RESOURCE); - if (componentFromCacheIfUpToDate.isLeft()) { - Resource cachedResource = componentFromCacheIfUpToDate.left().value(); - log.debug("Resource {} with uid {} was fetched from cache.", cachedResource.getName(), cachedResource.getUniqueId()); - return Either.left(cachedResource); - } - - resource = convertResourceDataToResource(resourceData); - - TitanOperationStatus status = null; - if (false == componentParametersView.isIgnoreUsers()) { - status = setResourceCreatorFromGraph(resource, uniqueId); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - status = setResourceLastModifierFromGraph(resource, uniqueId); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (false == componentParametersView.isIgnoreProperties()) { - status = setResourcePropertiesFromGraph(uniqueId, resource); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (false == componentParametersView.isIgnoreAttributesFrom()) { - status = setResourceAttributesFromGraph(uniqueId, resource); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (false == componentParametersView.isIgnoreDerivedFrom()) { - status = setResourceDerivedFromGraph(uniqueId, resource); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (false == componentParametersView.isIgnoreCategories()) { - status = setComponentCategoriesFromGraph(resource); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - // Since capabilities and requirements and instances properties are - // based on component instances, then we must fetch the instances. - if (false == componentParametersView.isIgnoreComponentInstances() || false == componentParametersView.isIgnoreComponentInstancesProperties() || false == componentParametersView.isIgnoreComponentInstancesInputs() - || false == componentParametersView.isIgnoreCapabilities() || false == componentParametersView.isIgnoreRequirements()) { - - status = setComponentInstancesFromGraph(uniqueId, resource, resourceNodeType, compInstNodeType); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - } - - if (false == componentParametersView.isIgnoreRequirements()) { - StorageOperationStatus setRequirementsStatus = setResourceRequirementsFromGraph(uniqueId, resource, true); - if (setRequirementsStatus != StorageOperationStatus.OK) { - log.error("Failed to set requirement of resource {}. status is {}", uniqueId, setRequirementsStatus); - return Either.right(setRequirementsStatus); - } - } - - if (false == componentParametersView.isIgnoreInputs()) { - status = setComponentInputsFromGraph(uniqueId, resource, true); - if (status != TitanOperationStatus.OK) { - log.error("Failed to set inputs of resource {}. status is {}", uniqueId, status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - } - - StorageOperationStatus storageStatus = null; - if (false == componentParametersView.isIgnoreCapabilities()) { - storageStatus = setResourceCapabilitiesFromGraph(uniqueId, resource); - if (storageStatus != StorageOperationStatus.OK) { - return Either.right(storageStatus); - } - } - - if (false == componentParametersView.isIgnoreArtifacts()) { - storageStatus = setArtifactFromGraph(uniqueId, resource); - if (storageStatus != StorageOperationStatus.OK) { - return Either.right(storageStatus); - } - } - if (false == componentParametersView.isIgnoreComponentInstancesAttributesFrom()) { - status = setComponentInstancesAttributesFromGraph(uniqueId, resource); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - } - - if (false == componentParametersView.isIgnoreComponentInstancesProperties()) { - status = setComponentInstancesPropertiesFromGraph(resource); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - } - - if (false == componentParametersView.isIgnoreComponentInstancesInputs()) { - status = setComponentInstancesInputsFromGraph(uniqueId, resource); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - } - - if (false == componentParametersView.isIgnoreInterfaces()) { - storageStatus = setResourceInterfacesFromGraph(uniqueId, resource); - if (storageStatus != StorageOperationStatus.OK) { - return Either.right(storageStatus); - } - } - - if (false == componentParametersView.isIgnoreAdditionalInformation()) { - storageStatus = setResourceAdditionalInformationFromGraph(uniqueId, resource); - if (storageStatus != StorageOperationStatus.OK) { - return Either.right(storageStatus); - } - } - - if (false == componentParametersView.isIgnoreAllVersions()) { - status = setAllVersions(resource); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (false == componentParametersView.isIgnoreGroups()) { - status = setGroupsFromGraph(uniqueId, resource, NodeTypeEnum.Resource); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (true == componentParametersView.isIgnoreComponentInstances()) { - resource.setComponentInstances(null); - resource.setComponentInstancesRelations(null); - } - - } finally { - if (false == inTransaction) { - titanGenericDao.commit(); - } - } - - return Either.left(resource); - - } - - @SuppressWarnings("unchecked") - @Override - public Either getComponent(String id, ComponentParametersView componentParametersView, boolean inTrasnaction) { - - Either component = getResource(id, componentParametersView, inTrasnaction); - if (component.isRight()) { - return Either.right(component.right().value()); - } - return (Either) component; - } - - // @Override - public Either updateResource(Resource resource, boolean inTransaction, ComponentParametersView filterResultView) { - return (Either) updateComponentFilterResult(resource, inTransaction, titanGenericDao, resource.getClass(), NodeTypeEnum.Resource, filterResultView); - } - - @Override - protected Either updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterResultView) { - return (Either) updateResource((Resource) component, inTransaction, filterResultView); - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java deleted file mode 100644 index e503c787b5..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java +++ /dev/null @@ -1,1289 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; -import fj.data.Either; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; -import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint; -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.datatypes.components.ServiceMetadataDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.operations.api.IArtifactOperation; -import org.openecomp.sdc.be.model.operations.api.IElementOperation; -import org.openecomp.sdc.be.model.operations.api.IServiceOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.resources.data.ComponentMetadataData; -import org.openecomp.sdc.be.resources.data.PropertyData; -import org.openecomp.sdc.be.resources.data.ServiceMetadataData; -import org.openecomp.sdc.be.resources.data.UserData; -import org.openecomp.sdc.be.resources.data.category.CategoryData; -import org.openecomp.sdc.common.util.ValidationUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -@org.springframework.stereotype.Component("service-operation") -@Deprecated -public class ServiceOperation extends ComponentOperation implements IServiceOperation { - - private static Logger log = LoggerFactory.getLogger(ServiceOperation.class.getName()); - - @Resource - private IArtifactOperation artifactOperation; - - @Resource - private IElementOperation elementOperation; - - public ServiceOperation() { - log.debug("ServiceOperation created"); - } - - @Override - public Either createService(Service service) { - return createService(service, false); - } - - @Override - public Either createService(Service service, boolean inTransaction) { - Either result = null; - - try { - - ServiceMetadataData serviceData = getServiceMetaDataFromService(service); - addComponentInternalFields(serviceData); - String uniqueId = (String) serviceData.getUniqueId(); - generateUUID(service); - - String userId = service.getCreatorUserId(); - - Either findUser = findUser(userId); - - if (findUser.isRight()) { - TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user {} in the graph. status is {}",userId,status); - return sendError(status, StorageOperationStatus.USER_NOT_FOUND); - } - - UserData creatorUserData = findUser.left().value(); - UserData updaterUserData = creatorUserData; - String updaterUserId = service.getLastUpdaterUserId(); - if (updaterUserId != null && !updaterUserId.equals(userId)) { - findUser = findUser(updaterUserId); - if (findUser.isRight()) { - TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user {} in the graph. status is {}",userId, status); - return sendError(status, StorageOperationStatus.USER_NOT_FOUND); - } else { - updaterUserData = findUser.left().value(); - } - } - - // get category - List categories = service.getCategories(); - CategoryData categoryData = null; - - String categoryName = categories.get(0).getName(); - if (categoryName != null) { - Either categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ServiceNewCategory, CategoryData.class); - if (categoryResult.isRight()) { - StorageOperationStatus status = categoryResult.right().value(); - /* - * TitanOperationStatus titanStatus = null; if(ActionStatus.CATEGORY_NOT_FOUND.equals(status)){ titanStatus = TitanOperationStatus.NOT_FOUND; }else{ titanStatus = TitanOperationStatus.GENERAL_ERROR; } - */ - log.error("Cannot find category {} in the graph. status is {}",categoryName,status); - return Either.right(status); - } - - categoryData = categoryResult.left().value(); - } - - StorageOperationStatus storageOperationStatus = createTagsForComponent(service); - if (storageOperationStatus != StorageOperationStatus.OK) { - return Either.right(storageOperationStatus); - } - - log.debug("try to create service node on graph for id {}",serviceData.getUniqueId()); - Either createNode = titanGenericDao.createNode(serviceData, ServiceMetadataData.class); - if (createNode.isRight()) { - TitanOperationStatus status = createNode.right().value(); - log.error("Error returned after creating service data node {}. status returned is {}",serviceData,status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - log.debug("create service node created on graph for id {}",serviceData.getUniqueId()); - - TitanOperationStatus associateMetadata = associateMetadataToComponent(serviceData, creatorUserData, updaterUserData, null, null); - if (associateMetadata != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateMetadata)); - return result; - } - TitanOperationStatus associateCategory = associateMetadataCategoryToComponent(serviceData, categoryData); - if (associateCategory != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateCategory)); - return result; - } - - Map allArtifacts = new HashMap(); - if (service.getArtifacts() != null) { - allArtifacts.putAll(service.getArtifacts()); - } - if (service.getDeploymentArtifacts() != null) { - allArtifacts.putAll(service.getDeploymentArtifacts()); - } - if (service.getServiceApiArtifacts() != null) { - allArtifacts.putAll(service.getServiceApiArtifacts()); - } - if (service.getToscaArtifacts() != null) { - allArtifacts.putAll(service.getToscaArtifacts()); - } - - StorageOperationStatus associateArtifacts = associateArtifactsToComponent(NodeTypeEnum.Service, serviceData, allArtifacts); - if (associateArtifacts != StorageOperationStatus.OK) { - result = Either.right(associateArtifacts); - return result; - } - - TitanOperationStatus associateInputs = associateInputsToComponent(NodeTypeEnum.Service, serviceData, service.getInputs()); - if (associateInputs != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateInputs)); - return result; - } - - List additionalInformation = service.getAdditionalInformation(); - StorageOperationStatus addAdditionalInformation = addAdditionalInformationToService(uniqueId, additionalInformation); - if (addAdditionalInformation != StorageOperationStatus.OK) { - result = Either.right(addAdditionalInformation); - return result; - } - - result = this.getService(uniqueId, true); - if (result.isRight()) { - log.error("Cannot get full service from the graph. status is {}", result.right().value()); - return Either.right(result.right().value()); - } - - if (log.isDebugEnabled()) { - String json = prettyJson.toJson(result.left().value()); - log.debug("Service retrieved is {}",json); - } - - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - } - - private TitanOperationStatus associateMetadataCategoryToComponent(ServiceMetadataData serviceData, CategoryData categoryData) { - Either result; - if (categoryData != null) { - result = titanGenericDao.createRelation(serviceData, categoryData, GraphEdgeLabels.CATEGORY, null); - log.debug("After associating component {} to category {}. Edge type is {}",serviceData.getUniqueId(),categoryData,GraphEdgeLabels.CATEGORY); - if (result.isRight()) { - log.error("Faield to associate component {} to category {}. Edge type is {}",serviceData.getUniqueId(),categoryData,GraphEdgeLabels.CATEGORY); - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private StorageOperationStatus addAdditionalInformationToService(String resourceUniqueId, List additionalInformation) { - - StorageOperationStatus result = null; - - if (additionalInformation == null || true == additionalInformation.isEmpty()) { - result = super.addAdditionalInformation(NodeTypeEnum.Service, resourceUniqueId, null); - } else { - if (additionalInformation.size() == 1) { - result = super.addAdditionalInformation(NodeTypeEnum.Service, resourceUniqueId, additionalInformation.get(0)); - } else { - result = StorageOperationStatus.BAD_REQUEST; - log.info("Cannot create resource with more than one additional information object. The number of received object is {}", additionalInformation.size()); - } - } - return result; - } - - public Either cloneService(Service other, String version, boolean inTransaction) { - return cloneService(other, version, null, inTransaction); - } - - public Either cloneService(Service other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) { - Either result = null; - - try { - String origServiceId = other.getUniqueId(); - other.setVersion(version); - other.setUniqueId(null); - - Either counterStatus = getComponentInstanceCoutner(origServiceId, NodeTypeEnum.Service); - if (counterStatus.isRight()) { - StorageOperationStatus status = counterStatus.right().value(); - log.error("failed to get resource instance counter on service {}. status={}", origServiceId, counterStatus); - result = Either.right(status); - return result; - } - Map> inputsValuesMap = new HashMap>(); - List inputs = other.getInputs(); - if (inputs != null) { - for (InputDefinition input : inputs) { - - Either, TitanOperationStatus> inputStatus = inputOperation - .getComponentInstanceInputsByInputId(input.getUniqueId()); - - if (inputStatus.isLeft() && inputStatus.left().value() != null) { - inputsValuesMap.put(input.getName(), inputStatus.left().value()); - } - } - } - - Either createServiceMD = createService(other, true); - - if (createServiceMD.isRight()) { - StorageOperationStatus status = createServiceMD.right().value(); - log.error("failed to clone service. status= {}", status); - result = Either.right(status); - return result; - } - - Service service = createServiceMD.left().value(); - - Either, Map>, StorageOperationStatus> cloneInstances = componentInstanceOperation.cloneAllComponentInstancesFromContainerComponent(origServiceId, service, - NodeTypeEnum.Service, NodeTypeEnum.Resource, targetLifecycle, inputsValuesMap); - if (cloneInstances.isRight()) { - result = Either.right(cloneInstances.right().value()); - return result; - } - - Either setResourceInstanceCounter = setComponentInstanceCounter(service.getUniqueId(), NodeTypeEnum.Service, counterStatus.left().value(), true); - if (setResourceInstanceCounter.isRight()) { - StorageOperationStatus status = setResourceInstanceCounter.right().value(); - log.error("failed to set resource instance counter on service {}. status={}", service.getUniqueId(), setResourceInstanceCounter); - result = Either.right(status); - return result; - } - - result = this.getService(service.getUniqueId(), true); - if (result.isRight()) { - log.error("Cannot get full service from the graph. status is {}", result.right().value()); - return Either.right(result.right().value()); - } - - if (log.isTraceEnabled()) { - String json = prettyJson.toJson(result.left().value()); - log.trace("Resource retrieved is {}", json); - } - - return result; - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - } - - private ServiceMetadataData getServiceMetaDataFromService(Service service) { - ServiceMetadataData serviceData = new ServiceMetadataData((ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition()); - if (service.getNormalizedName() == null || service.getNormalizedName().isEmpty()) { - serviceData.getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(service.getName())); - } - if (service.getSystemName() == null || service.getSystemName().isEmpty()) { - serviceData.getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(service.getName())); - } - - return serviceData; - } - - private Either sendError(TitanOperationStatus status, StorageOperationStatus statusIfNotFound) { - Either result; - if (status == TitanOperationStatus.NOT_FOUND) { - result = Either.right(statusIfNotFound); - return result; - } else { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - } - - /** - * - */ - public Either getService(String uniqueId) { - return getService(uniqueId, false); - } - - public Either getService(String uniqueId, boolean inTransaction) { - ComponentParametersView componentParametersView = new ComponentParametersView(); - return getService(uniqueId, componentParametersView, inTransaction); - } - - public Either getService(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction) { - - Service service = null; - Either result = null; - try { - - NodeTypeEnum serviceNodeType = NodeTypeEnum.Service; - NodeTypeEnum compInstNodeType = NodeTypeEnum.Resource; - - Either getComponentByLabel = getComponentByLabelAndId(uniqueId, serviceNodeType, ServiceMetadataData.class); - if (getComponentByLabel.isRight()) { - result = Either.right(getComponentByLabel.right().value()); - return result; - } - ServiceMetadataData serviceData = getComponentByLabel.left().value(); - // Try to fetch resource from the cache. The resource will be - // fetched only if the time on the cache equals to - // the time on the graph. - Either componentFromCacheIfUpToDate = this.getComponentFromCacheIfUpToDate(uniqueId, serviceData, componentParametersView, Service.class, ComponentTypeEnum.SERVICE); - if (componentFromCacheIfUpToDate.isLeft()) { - Service cachedService = componentFromCacheIfUpToDate.left().value(); - log.debug("Service {} with uid {} was fetched from cache.", cachedService.getName(), cachedService.getUniqueId()); - return Either.left(cachedService); - } - - service = convertServiceDataToService(serviceData); - TitanOperationStatus status = null; - if (false == componentParametersView.isIgnoreUsers()) { - status = setComponentCreatorFromGraph(service, uniqueId, serviceNodeType); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - status = setComponentLastModifierFromGraph(service, uniqueId, serviceNodeType); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - - } - } - if (false == componentParametersView.isIgnoreCategories()) { - status = setComponentCategoriesFromGraph(service); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - - } - } - - if (false == componentParametersView.isIgnoreArtifacts()) { - StorageOperationStatus storageStatus = setArtifactFromGraph(uniqueId, service, serviceNodeType, artifactOperation); - if (storageStatus != StorageOperationStatus.OK) { - result = Either.right(storageStatus); - return result; - } - } - - if (false == componentParametersView.isIgnoreComponentInstances() || false == componentParametersView.isIgnoreComponentInstancesProperties() || false == componentParametersView.isIgnoreCapabilities() - || false == componentParametersView.isIgnoreRequirements()) { - status = setComponentInstancesFromGraph(uniqueId, service, serviceNodeType, compInstNodeType); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - - } - } - if (false == componentParametersView.isIgnoreComponentInstancesProperties()) { - status = setComponentInstancesPropertiesFromGraph(service); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - } - if (false == componentParametersView.isIgnoreCapabilities()) { - status = setCapabilitiesFromGraph(uniqueId, service, NodeTypeEnum.Service); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - } - if (false == componentParametersView.isIgnoreRequirements()) { - status = setRequirementsFromGraph(uniqueId, service, NodeTypeEnum.Service); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - } - if (false == componentParametersView.isIgnoreAllVersions()) { - status = setAllVersions(service); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (false == componentParametersView.isIgnoreAdditionalInformation()) { - status = setServiceAdditionalInformationFromGraph(uniqueId, service); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (false == componentParametersView.isIgnoreGroups()) { - status = setGroupsFromGraph(uniqueId, service, NodeTypeEnum.Resource); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (false == componentParametersView.isIgnoreInputs()) { - status = setComponentInputsFromGraph(uniqueId, service, true); - if (status != TitanOperationStatus.OK) { - log.error("Failed to set inputs of resource {}. status is {}",uniqueId,status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - } - - if (false == componentParametersView.isIgnoreComponentInstancesInputs()) { - status = setComponentInstancesInputsFromGraph(uniqueId, service); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - } - - result = Either.left(service); - return result; - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - titanGenericDao.rollback(); - } else { - titanGenericDao.commit(); - } - } - } - } - - // public Either getService_tx(String - // uniqueId, boolean inTransaction) { - // - // Service service = null; - // Either result = null; - // try { - // - // NodeTypeEnum serviceNodeType = NodeTypeEnum.Service; - // NodeTypeEnum compInstNodeType = NodeTypeEnum.Resource; - // - // Either getComponentByLabel = - // getComponentByLabelAndId_tx(uniqueId, serviceNodeType, - // ServiceMetadataData.class); - // if (getComponentByLabel.isRight()) { - // result = Either.right(getComponentByLabel.right().value()); - // return result; - // } - // ServiceMetadataData serviceData = getComponentByLabel.left().value(); - // service = convertServiceDataToService(serviceData); - // - // TitanOperationStatus status = setComponentCreatorFromGraph(service, - // uniqueId, serviceNodeType); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // } - // - // status = setComponentLastModifierFromGraph(service, uniqueId, - // serviceNodeType); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // - // } - // status = setComponentCategoriesFromGraph(service); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // - // } - // - // // status = setServicePropertiesFromGraph(uniqueId, resource, vertex); - // // if (status != TitanOperationStatus.OK) { - // // return - // Either.right(TitanStatusConverter.convertTitanStatusToStorageStatus(status)); - // // } - // - // StorageOperationStatus storageStatus = setArtifactFromGraph(uniqueId, - // service, serviceNodeType, artifactOperation); - // if (storageStatus != StorageOperationStatus.OK) { - // result = Either.right(storageStatus); - // return result; - // } - // - // status = setComponentInstancesFromGraph(uniqueId, service, - // serviceNodeType, compInstNodeType); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // - // } - // - // status = setComponentInstancesPropertiesFromGraph(uniqueId, service); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // } - // - // status = setCapabilitiesFromGraph(uniqueId, service, - // NodeTypeEnum.Service); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // } - // - // status = setRequirementsFromGraph( uniqueId, service, - // NodeTypeEnum.Service); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // } - // - // status = setAllVersions(service); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // status = setServiceAdditionalInformationFromGraph(uniqueId, service); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // result = Either.left(service); - // return result; - // } finally { - // if (false == inTransaction) { - // if (result == null || result.isRight()) { - // titanGenericDao.rollback(); - // } else { - // titanGenericDao.commit(); - // } - // } - // } - // } - - @Override - TitanOperationStatus setComponentCategoriesFromGraph(Component service) { - - String uniqueId = service.getUniqueId(); - Either>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), uniqueId, GraphEdgeLabels.CATEGORY, - NodeTypeEnum.ServiceNewCategory, CategoryData.class); - if (parentNode.isRight()) { - return parentNode.right().value(); - } - - List> listValue = parentNode.left().value(); - if (log.isDebugEnabled()) - log.debug("Result after looking for category nodes pointed by service {}. status is {}", uniqueId, listValue); - if (listValue.size() > 1) { - log.error("Multiple edges foud between resource {} to category nodes.",uniqueId); - } - ImmutablePair value = listValue.get(0); - if (log.isDebugEnabled()) - log.debug("Found parent node {}", value); - - CategoryData categoryData = value.getKey(); - CategoryDefinition categoryDefinition = new CategoryDefinition(categoryData.getCategoryDataDefinition()); - - List categories = new ArrayList<>(); - categories.add(categoryDefinition); - service.setCategories(categories); - return TitanOperationStatus.OK; - - } - - @Override - public Either deleteService(String serviceId) { - return deleteService(serviceId, false); - } - - @Override - public Either deleteService(String serviceId, boolean inTransaction) { - - Either result = Either.right(StorageOperationStatus.GENERAL_ERROR); - try { - - Either graphResult = titanGenericDao.getGraph(); - if (graphResult.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); - return result; - } - - Either serviceNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), serviceId, ServiceMetadataData.class); - if (serviceNode.isRight()) { - TitanOperationStatus status = serviceNode.right().value(); - log.error("Failed to find service {}. status is {}",serviceId,status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - Either serviceRes = getService(serviceId, true); - if (serviceRes.isRight()) { - StorageOperationStatus status = serviceRes.right().value(); - log.error("Failed to find sevice {}.status is {}",serviceId,status); - result = Either.right(status); - return result; - } - Service service = serviceRes.left().value(); - - Either, StorageOperationStatus> deleteAllResourceInstancesRes = componentInstanceOperation.deleteAllComponentInstances(serviceId, NodeTypeEnum.Service, true); - log.debug("After deleting resource instances under service {}.Result is {}",serviceId,deleteAllResourceInstancesRes); - if (deleteAllResourceInstancesRes.isRight()) { - StorageOperationStatus status = deleteAllResourceInstancesRes.right().value(); - if (status != StorageOperationStatus.NOT_FOUND) { - log.error("Failed to delete resource instances under service {} .status is ",serviceId,status); - result = Either.right(status); - return result; - } - } - StorageOperationStatus removeArtifactsFromResource = removeArtifactsFromComponent(service, NodeTypeEnum.Service); - log.debug("After deleting artifacts nodes in the graph. status is {}",removeArtifactsFromResource); - if (!removeArtifactsFromResource.equals(StorageOperationStatus.OK)) { - result = Either.right(removeArtifactsFromResource); - return result; - } - - StorageOperationStatus removeInputsFromResource = removeInputsFromComponent(NodeTypeEnum.Service, service); - log.debug("After deleting requirements nodes in the graph. status is {}",removeInputsFromResource); - if (removeInputsFromResource != StorageOperationStatus.OK) { - result = Either.right(removeInputsFromResource); - return result; - } - - Either>, TitanOperationStatus> deleteChildrenNodesRes = titanGenericDao.deleteChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), serviceId, GraphEdgeLabels.PROPERTY, - NodeTypeEnum.Property, PropertyData.class); - - if (deleteChildrenNodesRes.isRight()) { - TitanOperationStatus status = deleteChildrenNodesRes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - } - - StorageOperationStatus removeAdditionalInformationFromService = super.deleteAdditionalInformation(NodeTypeEnum.Service, serviceId); - log.debug("After deleting additional information node in the graph. status is {}",removeAdditionalInformationFromService); - if (!removeAdditionalInformationFromService.equals(StorageOperationStatus.OK)) { - result = Either.right(removeAdditionalInformationFromService); - return result; - } - - StorageOperationStatus removeGroupsFromService = super.deleteGroups(NodeTypeEnum.Service, serviceId); - log.debug("After deleting group nodes in the graph. status is {}",removeGroupsFromService); - if (!removeGroupsFromService.equals(StorageOperationStatus.OK)) { - result = Either.right(removeGroupsFromService); - return result; - } - - Either deleteServiceNodeRes = titanGenericDao.deleteNode(serviceNode.left().value(), ServiceMetadataData.class); - if (deleteServiceNodeRes.isRight()) { - TitanOperationStatus status = deleteServiceNodeRes.right().value(); - log.error("Failed to delete service node {}. status is {}",serviceId, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - result = Either.left(service); - - return result; - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("deleteService operation : Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("deleteService operation : Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - @Override - public Either validateServiceNameExists(String serviceName) { - return validateServiceNameUniqueness(serviceName, titanGenericDao); - } - - private Service convertServiceDataToService(ServiceMetadataData serviceData) { - ServiceMetadataDefinition serviceMetadataDefinition = new ServiceMetadataDefinition((ServiceMetadataDataDefinition) serviceData.getMetadataDataDefinition()); - - Service service = new Service(serviceMetadataDefinition); - - return service; - } - - @Override - public Either getComponent(String id, Class clazz) { - - Either component = getService(id); - if (component.isRight()) { - return Either.right(component.right().value()); - } - return Either.left(clazz.cast(component.left().value())); - } - - @Override - @SuppressWarnings("unchecked") - public Either, StorageOperationStatus> getFollowed(String userId, Set lifecycleStates, Set lastStateStates, boolean inTransaction) { - - return (Either, StorageOperationStatus>) (Either) getFollowedComponent(userId, lifecycleStates, lastStateStates, inTransaction, titanGenericDao, NodeTypeEnum.Service); - } - - @SuppressWarnings("unchecked") - @Override - public Either getComponent(String id, boolean inTransaction) { - return (Either) getService(id, inTransaction); - } - - @Override - public Either, StorageOperationStatus> getCatalogData(Map propertiesToMatch, boolean inTransaction) { - return getComponentCatalogData(NodeTypeEnum.Service, propertiesToMatch, Service.class, ServiceMetadataData.class, inTransaction); - } - - @Override - public Either updateService(Service service, boolean inTransaction) { - Either result = updateComponent(service, inTransaction, titanGenericDao, Service.class, NodeTypeEnum.Service); - return result; - } - - @SuppressWarnings("unchecked") - @Override - public Either updateComponent(T component, boolean inTransaction) { - return (Either) updateService((Service) component, inTransaction); - } - - @SuppressWarnings("unchecked") - @Override - public Either deleteComponent(String id, boolean inTransaction) { - return (Either) (Either) deleteService(id, inTransaction); - } - - @Override - protected ComponentMetadataData getMetaDataFromComponent(Component component) { - return getServiceMetaDataFromService((Service) component); - } - - @Override - public Either getLightComponent(String id, boolean inTransaction) { - return getLightComponent(id, NodeTypeEnum.Service, inTransaction); - } - - @Override - public Either, StorageOperationStatus> getFilteredComponents(Map filters, boolean inTransaction) { - Either, StorageOperationStatus> components = null; - - String categoryName = filters.get(FilterKeyEnum.CATEGORY); - String distributionStatus = filters.get(FilterKeyEnum.DISTRIBUTION_STATUS); - DistributionStatusEnum distEnum = DistributionStatusEnum.findState(distributionStatus); - if (distributionStatus != null && distEnum == null) { - filters.remove(FilterKeyEnum.CATEGORY); - return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); - } - - if (categoryName != null) { // primary filter - components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), NodeTypeEnum.Service, inTransaction, ServiceMetadataData.class, null); - if (components.isLeft() && distEnum != null) {// secondary filter - Predicate statusFilter = p -> ((Service) p).getDistributionStatus().equals(distEnum); - return Either.left(components.left().value().stream().filter(statusFilter).collect(Collectors.toList())); - } - filters.remove(FilterKeyEnum.DISTRIBUTION_STATUS); - return components; - } - components = fetchByDistributionStatus(distEnum.name(), inTransaction); - if (components.isRight()) { // not found == empty list - return Either.left(new ArrayList<>()); - } - return components; - } - - private Either, StorageOperationStatus> fetchByDistributionStatus(String status, boolean inTransaction) { - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.DISTRIBUTION_STATUS.getProperty(), status); - props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - return (Either, StorageOperationStatus>) (Either) getServiceListByCriteria(props, inTransaction); - } - - @SuppressWarnings("unchecked") - @Override - public Either, StorageOperationStatus> getTesterFollowed(String userId, Set lifecycleStates, boolean inTransaction) { - return (Either, StorageOperationStatus>) (Either) getTesterFollowedComponent(userId, lifecycleStates, inTransaction, NodeTypeEnum.Service); - } - - @Override - public Either updateDestributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) { - String userId = user.getUserId(); - Either findUser = findUser(userId); - if (findUser.isRight()) { - TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user {} in the graph. status is {}", userId, status); - return sendError(status, StorageOperationStatus.USER_NOT_FOUND); - } - UserData userData = findUser.left().value(); - - Either serviceMetadataDataRequeset = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), service.getUniqueId(), ServiceMetadataData.class); - if (serviceMetadataDataRequeset.isRight()) { - TitanOperationStatus status = serviceMetadataDataRequeset.right().value(); - log.error("Cannot find service {} in the graph. status is {}",service.getUniqueId(),status); - return sendError(status, StorageOperationStatus.NOT_FOUND); - } - ServiceMetadataData serviceMetadataData = serviceMetadataDataRequeset.left().value(); - - StorageOperationStatus result = StorageOperationStatus.OK; - - Either deleteIncomingRelation = deleteLastDistributionModifierRelation(service); - if (deleteIncomingRelation.isRight() && deleteIncomingRelation.right().value() != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to delete user from component {}. Edge type is {}",service.getUniqueId(),GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteIncomingRelation.right().value()); - return Either.right(result); - } - - Either createRelation = titanGenericDao.createRelation(userData, serviceMetadataData, GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER, null); - log.debug("After associating user {} to component {}. Edge type is {}",userData,serviceMetadataData.getUniqueId(),GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER); - if (createRelation.isRight()) { - log.error("Failed to associate user {} to component {}. Edge type is {}",userData,serviceMetadataData.getUniqueId(),GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value()); - return Either.right(result); - } - service.setDistributionStatus(distributionStatus); - Either updateResponse = updateComponent(service, true, titanGenericDao, Service.class, NodeTypeEnum.Service); - - return updateResponse; - - } - - private Either deleteLastDistributionModifierRelation(Service service) { - GraphRelation lastDistributionStateModifaierRelation = new GraphRelation(); - lastDistributionStateModifaierRelation.setType(GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER.getProperty()); - RelationEndPoint relationEndPoint = new RelationEndPoint(NodeTypeEnum.Service, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), service.getUniqueId()); - lastDistributionStateModifaierRelation.setTo(relationEndPoint); - Either deleteIncomingRelation = titanGenericDao.deleteIncomingRelation(lastDistributionStateModifaierRelation); - return deleteIncomingRelation; - } - - @Override - public Either, StorageOperationStatus> getCertifiedServicesWithDistStatus(Map propertiesToMatch, Set distStatus, boolean inTransaction) { - log.debug("Start getCertifiedServicesWithDistStatus."); - Set servicesSet = new HashSet(); - if (distStatus != null && !distStatus.isEmpty()) { - for (DistributionStatusEnum status : distStatus) { - Map props = new HashMap<>(); - props.putAll(propertiesToMatch); - props.put(GraphPropertiesDictionary.DISTRIBUTION_STATUS.getProperty(), status.name()); - Either, StorageOperationStatus> services = retrieveCertifiedServicesWithStatus(inTransaction, props); - if (services.isRight()) { - return services; - } else { - servicesSet.addAll(services.left().value()); - } - } - return Either.left(servicesSet); - } else { - return retrieveCertifiedServicesWithStatus(inTransaction, propertiesToMatch); - } - } - - private Either, StorageOperationStatus> retrieveCertifiedServicesWithStatus(boolean inTransaction, Map props) { - Either, TitanOperationStatus> criteriaRes = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class); - return retrieveComponentsFromNodes(criteriaRes, inTransaction); - } - - public Either, StorageOperationStatus> getServiceCatalogData(boolean inTransaction) { - - long start = System.currentTimeMillis(); - - try { - /* - * Map propertiesToMatch = new HashMap<>(); propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty (), LifecycleStateEnum.CERTIFIED.name()); Either, TitanOperationStatus> - * lastVersionNodes = getLastVersion(NodeTypeEnum.Service, propertiesToMatch, ServiceMetadataData.class); if (lastVersionNodes.isRight() && lastVersionNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return - * Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus (lastVersionNodes.right().value())); } List notCertifiedHighest = (lastVersionNodes.isLeft() ? lastVersionNodes.left().value() : new - * ArrayList()); - * - * propertiesToMatch.put(GraphPropertiesDictionary. IS_HIGHEST_VERSION.getProperty(), true); Either, TitanOperationStatus> componentsNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Service, propertiesToMatch, - * ServiceMetadataData.class); if (componentsNodes.isRight() && componentsNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus - * (componentsNodes.right().value())); } List certifiedHighest = (componentsNodes.isLeft() ? componentsNodes.left().value() : new ArrayList()); - */ - - Either, TitanOperationStatus> listOfHighestComponents = this.getListOfHighestComponents(NodeTypeEnum.Service, ServiceMetadataData.class); - if (listOfHighestComponents.isRight() && listOfHighestComponents.right().value() != TitanOperationStatus.NOT_FOUND) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfHighestComponents.right().value())); - } - - List notCertifiedHighest = listOfHighestComponents.left().value(); - - List result = new ArrayList<>(); - - if (notCertifiedHighest != null && false == notCertifiedHighest.isEmpty()) { - - // fetch from cache - long startFetchAllFromCache = System.currentTimeMillis(); - - Map components = notCertifiedHighest.stream().collect(Collectors.toMap(p -> p.getMetadataDataDefinition().getUniqueId(), p -> p.getMetadataDataDefinition().getLastUpdateDate())); - - Either, Set>, ActionStatus> componentsFromCacheForCatalog = this.getComponentsFromCacheForCatalog(components, ComponentTypeEnum.SERVICE); - if (componentsFromCacheForCatalog.isLeft()) { - ImmutablePair, Set> immutablePair = componentsFromCacheForCatalog.left().value(); - List list = immutablePair.getLeft(); - if (list != null) { - for (Component component : list) { - result.add((Service) component); - } - List addedUids = list.stream().map(p -> p.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId()).collect(Collectors.toList()); - notCertifiedHighest = notCertifiedHighest.stream().filter(p -> false == addedUids.contains(p.getMetadataDataDefinition().getUniqueId())).collect(Collectors.toList()); - } - } - long endFetchAllFromCache = System.currentTimeMillis(); - log.debug("Fetch all catalog services metadata from cache took {} ms", (endFetchAllFromCache - startFetchAllFromCache)); - log.debug("The number of services added to catalog from cache is {}", result.size()); - - log.debug("The number of services needed to be fetch as light component is {}", notCertifiedHighest.size()); - for (ServiceMetadataData data : notCertifiedHighest) { - Either component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction); - if (component.isRight()) { - log.debug("Failed to get Service for id = {}, error : {}. Skip service", data.getUniqueId(), component.right().value()); - } else { - result.add(component.left().value()); - } - } - } - return Either.left(result); - } finally { - if (false == inTransaction) { - titanGenericDao.commit(); - } - log.debug("Fetch all catalog services took {} ms",(System.currentTimeMillis() - start)); - } - - } - - public Either, StorageOperationStatus> getServiceCatalogDataLatestCertifiedAndNotCertified(boolean inTransaction) { - Map properties = new HashMap<>(); - - properties.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - List result = new ArrayList<>(); - Either, TitanOperationStatus> lastVersionNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Service, properties, ServiceMetadataData.class); - - if (lastVersionNodes.isRight() && lastVersionNodes.right().value() != TitanOperationStatus.NOT_FOUND) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(lastVersionNodes.right().value())); - } - - List latestServices; - - if (lastVersionNodes.isLeft()) { - latestServices = lastVersionNodes.left().value(); - } else { - return Either.left(result); - } - - for (ServiceMetadataData data : latestServices) { - Either component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction); - if (component.isRight()) { - log.debug("Failed to get Service for id = {} error : {} skip resource",data.getUniqueId(),component.right().value()); - } else { - result.add(component.left().value()); - } - } - - return Either.left(result); - - } - - private Either, StorageOperationStatus> getServiceListByCriteria(Map props, boolean inTransaction) { - props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName()); - Either, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class); - - if (byCriteria.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value())); - } - List services = new ArrayList<>(); - List servicesDataList = byCriteria.left().value(); - for (ServiceMetadataData data : servicesDataList) { - Either service = getService(data.getMetadataDataDefinition().getUniqueId(), inTransaction); - if (service.isLeft()) { - services.add(service.left().value()); - } else { - log.debug("Failed to fetch resource for name = {} and id = {}",data.getMetadataDataDefinition().getName(),data.getUniqueId()); - } - } - return Either.left(services); - } - - public Either, StorageOperationStatus> getServiceListByUuid(String uuid, boolean inTransaction) { - return getLatestServiceByUuid(uuid, false, inTransaction); - } - - public Either, StorageOperationStatus> getLatestServiceByUuid(String uuid, boolean inTransaction) { - return getLatestServiceByUuid(uuid, true, inTransaction); - } - - private Either, StorageOperationStatus> getLatestServiceByUuid(String uuid, boolean isLatest, boolean inTransaction) { - Map props = new HashMap(); - - if (isLatest) { - props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), isLatest); - } - - props.put(GraphPropertiesDictionary.UUID.getProperty(), uuid); - return getServiceListByCriteria(props, inTransaction); - } - - @Override - public Either, StorageOperationStatus> getAll() { - Either, StorageOperationStatus> serviceListByCriteria = getServiceListByCriteria(new HashMap<>(), false); - if (serviceListByCriteria.isRight() && serviceListByCriteria.right().value() == StorageOperationStatus.NOT_FOUND) { - return Either.left(Collections.emptyList()); - } - return serviceListByCriteria; - } - - public Either, StorageOperationStatus> getServiceListBySystemName(String systemName, boolean inTransaction) { - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), systemName); - return getServiceListByCriteria(props, inTransaction); - } - - public Either getServiceByNameAndVersion(String name, String version, Map additionalParams, boolean inTransaction) { - return getByNamesAndVersion(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normaliseComponentName(name), version, additionalParams, inTransaction); - } - - @Override - public Either getServiceByNameAndVersion(String name, String version) { - return getServiceByNameAndVersion(name, version, null, false); - } - - protected Either getByNamesAndVersion(String nameKey, String nameValue, String version, Map additionalParams, boolean inTransaction) { - Map props = new HashMap(); - props.put(nameKey, nameValue); - props.put(GraphPropertiesDictionary.VERSION.getProperty(), version); - props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName()); - if (additionalParams != null && !additionalParams.isEmpty()) { - props.putAll(additionalParams); - } - - Either, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class); - - if (byCriteria.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value())); - } - List dataList = byCriteria.left().value(); - if (dataList != null && !dataList.isEmpty()) { - if (dataList.size() > 1) { - log.debug("More that one instance of resource for name ={} and version = {}",nameValue,version); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - ServiceMetadataData serviceData = dataList.get(0); - Either service = getService(serviceData.getMetadataDataDefinition().getUniqueId(), inTransaction); - if (service.isRight()) { - log.debug("Failed to fetch resource for name = {} and id = {}",serviceData.getMetadataDataDefinition().getName(),serviceData.getMetadataDataDefinition().getUniqueId()); - } - return service; - } - return Either.right(StorageOperationStatus.NOT_FOUND); - } - - protected Either getComponentByNameAndVersion(String name, String version, Map additionalParams, boolean inTransaction) { - return (Either) getServiceByNameAndVersion(name, version, additionalParams, inTransaction); - } - - @Override - public Either getServiceBySystemNameAndVersion(String name, String version, boolean inTransaction) { - return getByNamesAndVersion(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), name, version, null, inTransaction); - } - - private TitanOperationStatus setServiceAdditionalInformationFromGraph(String uniqueId, Service service) { - - List additionalInformation = new ArrayList<>(); - - Either either = additionalInformationOperation.getAllAdditionalInformationParameters(NodeTypeEnum.Service, uniqueId, true); - - if (either.isRight()) { - TitanOperationStatus status = either.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - return TitanOperationStatus.OK; - } - return status; - } - - AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); - additionalInformation.add(additionalInformationDefinition); - - service.setAdditionalInformation(additionalInformation); - - return TitanOperationStatus.OK; - - } - - private TitanOperationStatus setAllVersions(Service service) { - Either, TitanOperationStatus> res = getVersionList(NodeTypeEnum.Service, service.getVersion(), service, ServiceMetadataData.class); - if (res.isRight()) { - return res.right().value(); - } - service.setAllVersions(res.left().value()); - return TitanOperationStatus.OK; - } - - public Either, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction) { - List artifacts = new ArrayList<>(); - return Either.left(artifacts); - } - - @Override - public boolean isComponentExist(String serviceId) { - return isComponentExist(serviceId, NodeTypeEnum.Service); - } - - // @SuppressWarnings("unchecked") - // @Override - // public Either cloneComponent(T other, - // String version, boolean inTransaction) { - // return (Either) cloneService((Service)other, - // version, inTransaction); - // } - - @SuppressWarnings("unchecked") - @Override - public Either cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) { - return (Either) cloneService((Service) other, version, targetLifecycle, inTransaction); - } - - @Override - public Either increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction) { - return increaseAndGetComponentInstanceCounter(componentId, NodeTypeEnum.Service, inTransaction); - } - - @Override - protected StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type) { - List newcategories = component.getCategories(); - CategoryDefinition newCat = newcategories.get(0); - CategoryDefinition currentCategory = currentComponent.getCategories().get(0); - - StorageOperationStatus status = StorageOperationStatus.OK; - if (newCat != null && newCat.getName() != null && false == newCat.getName().equals(currentCategory.getName())) { - log.debug("Going to update the category of the resource from {} to {}",currentCategory,newCat.getName()); - - status = moveCategoryEdge(component, componentData, newCat, type); - log.debug("Going to update the category of the resource from {} to {}. status is {}",currentCategory,newCat.getName(),status); - } - return status; - } - - @Override - protected StorageOperationStatus updateDerived(Component component, Component currentComponent, ComponentMetadataData componentData, Class clazz) { - log.debug("Derived class isn't supported for resource"); - return null; - } - - @Override - public Service getDefaultComponent() { - return new Service(); - } - - @Override - public Either getMetadataComponent(String id, boolean inTransaction) { - return getMetadataComponent(id, NodeTypeEnum.Service, inTransaction); - } - - @Override - Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData) { - return convertServiceDataToService((ServiceMetadataData) componentMetadataData); - } - - @Override - public Either validateComponentNameExists(String componentName) { - return validateComponentNameUniqueness(componentName, titanGenericDao, NodeTypeEnum.Service); - } - - @Override - public Either markComponentToDelete(Component componentToDelete, boolean inTransaction) { - return internalMarkComponentToDelete(componentToDelete, inTransaction); - } - - @Override - public Either isComponentInUse(String componentId) { - return isComponentInUse(componentId, NodeTypeEnum.Service); - } - - @Override - public Either, StorageOperationStatus> getAllComponentsMarkedForDeletion() { - return getAllComponentsMarkedForDeletion(NodeTypeEnum.Service); - } - - @SuppressWarnings("unchecked") - @Override - public Either getComponent(String id, ComponentParametersView componentParametersView, boolean inTransaction) { - - Either component = getService(id, componentParametersView, inTransaction); - if (component.isRight()) { - return Either.right(component.right().value()); - } - return (Either) component; - } - - public Either updateService(Service service, boolean inTransaction, ComponentParametersView filterResultView) { - return (Either) updateComponentFilterResult(service, inTransaction, titanGenericDao, service.getClass(), NodeTypeEnum.Service, filterResultView); - } - - @Override - protected Either updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterResultView) { - return (Either) updateService((Service) component, inTransaction, filterResultView); - } - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorImpl.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorImpl.java deleted file mode 100644 index 5674a6ef0c..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorImpl.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator; -import org.springframework.stereotype.Component; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -@Component("tosca-path-calculator") -public class ToscaDefinitionPathCalculatorImpl implements ToscaDefinitionPathCalculator { - - @Override - public List calculateToscaDefinitionPath(ComponentInstance componentInstance, GraphEdge edge) { - String ownerId = getCapReqOwner(edge); - String instanceId = componentInstance.getUniqueId(); - return ownerId.equals(instanceId) ? Collections.singletonList(instanceId) : Arrays.asList(instanceId, ownerId); - } - - private String getCapReqOwner(GraphEdge edge) { - String ownerIdKey = GraphEdgePropertiesDictionary.OWNER_ID.getProperty(); - return (String)edge.getProperties().get(ownerIdKey); - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java index 81ca98444c..62ab886472 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 @@ -67,11 +67,6 @@ public class UserAdminOperation implements IUserAdminOperation { private static Logger log = LoggerFactory.getLogger(UserAdminOperation.class.getName()); - @Override - public Either getInactiveUserData(String id) { - return getUserData(id, false, false); - } - @Override public Either getUserData(String id, boolean inTransaction) { return getUserData(id, true, inTransaction); @@ -380,16 +375,6 @@ public class UserAdminOperation implements IUserAdminOperation { return result; } - @Override - public Either, ActionStatus> getAllUsers() { - try { - Either, TitanOperationStatus> userNodes = titanGenericDao.getAll(NodeTypeEnum.User, UserData.class); - return convertToUsers("", userNodes); - } finally { - titanGenericDao.commit(); - } - } - private Either getUserNotFoundError(String uid, TitanOperationStatus status) { if (status == TitanOperationStatus.NOT_FOUND) { log.debug("User with userId {} not found", uid); @@ -427,96 +412,4 @@ public class UserAdminOperation implements IUserAdminOperation { return userData; } - @Override - public Either, ActionStatus> getUserDataWithFunctionalMenu(String userId) { - - Either userData = getUserData(userId, true, true); - - if (userData.isRight()) { - return Either.right(userData.right().value()); - } - User user = userData.left().value(); - Either functionalMenu = getFunctionalMenu(userId); - - FunctionalMenuInfo functionalMenuInfo = new FunctionalMenuInfo(); - if (functionalMenu.isRight()) { - TitanOperationStatus status = functionalMenu.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - return Either.right(ActionStatus.GENERAL_ERROR); - } - } else { - UserFunctionalMenuData userFunctionalMenuData = functionalMenu.left().value(); - functionalMenuInfo.setFunctionalMenu(userFunctionalMenuData.getFunctionalMenu()); - } - - ImmutablePair result = new ImmutablePair(user, functionalMenuInfo); - - return Either.left(result); - } - - public Either getFunctionalMenu(String userId) { - - Either result; - if (userId == null) { - log.info("User userId is empty"); - result = Either.right(TitanOperationStatus.NOT_FOUND); - return result; - } - userId = userId.toLowerCase(); - String uid = UniqueIdBuilder.buildUserFunctionalMenuUid(userId); - - Either either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.UserFunctionalMenu), uid, UserFunctionalMenuData.class); - - return either; - } - - public Either createOrUpdateFunctionalMenu(String userId, String newFunctionalMenu) { - - Either functionalMenu = getFunctionalMenu(userId); - - if (functionalMenu.isRight()) { - TitanOperationStatus status = functionalMenu.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - String uid = UniqueIdBuilder.buildUserFunctionalMenuUid(userId); - UserFunctionalMenuData functionalMenuData = new UserFunctionalMenuData(newFunctionalMenu, uid); - - Either createNode = titanGenericDao.createNode(functionalMenuData, UserFunctionalMenuData.class); - - if (createNode.isRight()) { - return Either.right(createNode.right().value()); - } else { - return Either.left(convert(createNode.left().value())); - } - - } else { - return Either.right(status); - } - - } else { - UserFunctionalMenuData userFunctionalMenuData = functionalMenu.left().value(); - userFunctionalMenuData.setFunctionalMenu(newFunctionalMenu); - Either updateNode = titanGenericDao.updateNode(userFunctionalMenuData, UserFunctionalMenuData.class); - - if (updateNode.isRight()) { - return Either.right(updateNode.right().value()); - } else { - return Either.left(convert(updateNode.left().value())); - } - } - - } - - private FunctionalMenuInfo convert(UserFunctionalMenuData functionalMenuData) { - - if (functionalMenuData == null) { - return null; - } - - FunctionalMenuInfo functionalMenuInfo = new FunctionalMenuInfo(); - functionalMenuInfo.setFunctionalMenu(functionalMenuData.getFunctionalMenu()); - - return functionalMenuInfo; - - } - } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationMalformedDataLogger.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationMalformedDataLogger.java deleted file mode 100644 index 3cbdfc798c..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationMalformedDataLogger.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.migration; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * to be moved with all operations to the migration project - */ - -public class MigrationMalformedDataLogger { - - private static Logger log = LoggerFactory.getLogger(MigrationMalformedDataLogger.class); - private static Set malformedVFs = new HashSet<>(); - - public static void reportMalformedVF(String vfId, String errorMsg) { - log.error(errorMsg); - malformedVFs.add(vfId); - } - - public static void logMalformedDataMsg(String errorMsg) { - log.error(errorMsg); - } - - public static void logIfServiceUsingMalformedVfs(Component service) { - List componentInstances = service.getComponentInstances(); - if (componentInstances != null && !componentInstances.isEmpty() && !malformedVFs.isEmpty()) { - Set serviceInstances = componentInstances.stream().map(ComponentInstance::getComponentUid).collect(Collectors.toSet()); - serviceInstances.retainAll(malformedVFs); - if (!serviceInstances.isEmpty()) { - log.error(String.format("Service %s with id %s and version %s is using malformed VFs: %s", service.getName(), - service.getVersion(), - service.getUniqueId(), - StringUtils.join(serviceInstances, ','))); - } - } - } - - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java index fe5d79a266..01c9eefb20 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java @@ -20,20 +20,16 @@ package org.openecomp.sdc.be.model.operations.utils; +import fj.data.Either; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.operations.api.IResourceOperation; -import org.openecomp.sdc.be.model.operations.api.IServiceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; - public class ComponentValidationUtils { private static Logger log = LoggerFactory.getLogger(ComponentValidationUtils.class.getName()); diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java index eea11b6625..b24d6d8285 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java @@ -20,37 +20,20 @@ package org.openecomp.sdc.be.model.operations.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; 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.LifecycleStateEnum; import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; import org.openecomp.sdc.be.resources.data.UserData; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.thinkaurelius.titan.core.TitanGraph; -//import com.tinkerpop.blueprints.Vertex; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; +import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context-test.xml") @@ -62,9 +45,6 @@ public class AdditionalInformationOperationTest extends ModelTestBase { @javax.annotation.Resource(name = "titan-generic-dao") private TitanGenericDao titanDao; - @javax.annotation.Resource(name = "resource-operation") - private ResourceOperation resourceOperation; - @javax.annotation.Resource(name = "additional-information-operation") private IAdditionalInformationOperation additionalInformationOperation; @@ -89,64 +69,6 @@ public class AdditionalInformationOperationTest extends ModelTestBase { } - private int getNumberOfVerticesOnGraph() { - Either graphResult = titanDao.getGraph(); - TitanGraph graph = graphResult.left().value(); - - int i = 0; - Iterable vertices = graph.query().vertices(); - if (vertices != null) { - Iterator iterator = vertices.iterator(); - while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - i++; - } - - } - - titanDao.commit(); - - return i; - } - - @Test - public void testCreateAndDeleteResource() { - - int before = getNumberOfVerticesOnGraph(); - - Resource newResource = createResource(USER_ID, CATEGORY_NAME, "testCreateAndDeleteResource", "0.1", null, false, true); - String resourceId = newResource.getUniqueId(); - - Either deleteResource = resourceOperation.deleteResource(resourceId); - assertTrue(deleteResource.isLeft()); - - int after = getNumberOfVerticesOnGraph(); - - assertEquals("check number of vertices not changed", before, after); - } - - private Resource buildResourceMetadata(String userId, String category, String resourceName, String resourceVersion) { - - Resource resource = new Resource(); - resource.setName(resourceName); - resource.setVersion(resourceVersion); - ; - resource.setDescription("description 1"); - resource.setAbstract(false); - resource.setCreatorUserId(userId); - resource.setContactId("contactId@sdc.com"); - resource.setVendorName("vendor 1"); - resource.setVendorRelease("1.0.0"); - String[] categoryArr = category.split("/"); - resource.addCategory(categoryArr[0], categoryArr[1]); - resource.setIcon("images/my.png"); - // List tags = new ArrayList(); - // tags.add("TAG1"); - // tags.add("TAG2"); - // resource.setTags(tags); - return resource; - } - private UserData deleteAndCreateUser(String userId, String firstName, String lastName) { UserData userData = new UserData(); userData.setUserId(userId); @@ -165,26 +87,4 @@ public class AdditionalInformationOperationTest extends ModelTestBase { OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); } - public Resource createResource(String userId, String category, String resourceName, String resourceVersion, String parentResourceName, boolean isAbstract, boolean isHighestVersion) { - - List derivedFrom = new ArrayList(); - if (parentResourceName != null) { - derivedFrom.add(parentResourceName); - } - Resource resource = buildResourceMetadata(userId, category, resourceName, resourceVersion); - - resource.setAbstract(isAbstract); - resource.setHighestVersion(isHighestVersion); - - Either result = resourceOperation.createResource(resource, true); - - assertTrue(result.isLeft()); - Resource resultResource = result.left().value(); - - assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultResource.getLifecycleState()); - - return resultResource; - - } - } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java index 875c34b780..1082b44e5b 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java @@ -20,18 +20,10 @@ package org.openecomp.sdc.be.model.operations.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; @@ -46,18 +38,8 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.ModelTestBase; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation; -import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; -import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; -import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation; -import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation; -import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; -import org.openecomp.sdc.be.model.operations.impl.RequirementOperation; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; -import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; import org.openecomp.sdc.be.resources.data.ArtifactData; import org.openecomp.sdc.be.resources.data.HeatParameterData; @@ -70,7 +52,12 @@ import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context-test.xml") @@ -81,37 +68,13 @@ public class ArtifactOperationTest extends ModelTestBase { @javax.annotation.Resource(name = "titan-generic-dao") private TitanGenericDao titanDao; - @javax.annotation.Resource(name = "service-operation") - private ServiceOperation serviceOperation; - - @javax.annotation.Resource - private IGraphLockOperation graphLockOperation; + @javax.annotation.Resource(name = "tosca-operation-facade") + private ToscaOperationFacade toscaOperationFacade; @javax.annotation.Resource private ArtifactOperation artifactOperation; - @javax.annotation.Resource(name = "requirement-operation") - private RequirementOperation requirementOperation; - - @javax.annotation.Resource(name = "resource-operation") - private ResourceOperation resourceOperation; - - @javax.annotation.Resource(name = "property-operation") - private PropertyOperation propertyOperation; - - @javax.annotation.Resource(name = "capability-operation") - private CapabilityOperation capabilityOperation; - - @javax.annotation.Resource(name = "capability-type-operation") - private CapabilityTypeOperation capabilityTypeOperation; - - @javax.annotation.Resource(name = "component-instance-operation") - private ComponentInstanceOperation resourceInstanceOperation; - - @javax.annotation.Resource(name = "lifecycle-operation") - private LifecycleOperation lifecycleOperation; - - private static Logger log = LoggerFactory.getLogger(ServiceOperation.class.getName()); + private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName()); private static String RESOURCE_ID = "resourceId"; private static String RESOURCE_ID_2 = "resourceId2"; @@ -132,6 +95,7 @@ public class ArtifactOperationTest extends ModelTestBase { } @Test + @Ignore public void testAddArtifactToServiceVersionAndUUIDNotNull() { CategoryDefinition category = new CategoryDefinition(); category.setName(CATEGORY_NAME); @@ -149,7 +113,7 @@ public class ArtifactOperationTest extends ModelTestBase { assertNotNull("add informational artifact version : " + artifactInfo.getArtifactUUID(), artifactInfo.getArtifactUUID()); - Either service = serviceOperation.getService(serviceId); + Either service = toscaOperationFacade.getToscaFullElement(serviceId); assertTrue(service.isLeft()); Map artifacts = service.left().value().getArtifacts(); @@ -159,23 +123,24 @@ public class ArtifactOperationTest extends ModelTestBase { artifactOperation.removeArifactFromResource(serviceId, artifactId, NodeTypeEnum.Service, true, false); } - service = serviceOperation.getService(serviceId); + service = toscaOperationFacade.getToscaFullElement(serviceId); assertTrue(service.isLeft()); artifacts = service.left().value().getArtifacts(); assertEquals(0, artifacts.size()); - Either serviceDelete = serviceOperation.deleteService(serviceId); + Either serviceDelete = toscaOperationFacade.deleteToscaComponent(serviceId); Either, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, null, ArtifactData.class); assertTrue(byCriteria.isRight()); assertEquals(TitanOperationStatus.NOT_FOUND, byCriteria.right().value()); - serviceOperation.deleteService(serviceAfterSave.getUniqueId()); + toscaOperationFacade.deleteToscaComponent(serviceId); } @Test + @Ignore public void testUpdateArtifactToServiceVersionNotChanged() { CategoryDefinition category = new CategoryDefinition(); category.setName(CATEGORY_NAME); @@ -200,7 +165,7 @@ public class ArtifactOperationTest extends ModelTestBase { assertEquals("add informational artifact version : " + newVersion, newVersion, version); assertEquals("add informational artifact uuid : " + newArtUuid, newArtUuid, artUuid); - Either service = serviceOperation.getService(serviceId); + Either service = toscaOperationFacade.getToscaFullElement(serviceId); assertTrue(service.isLeft()); Map artifacts = service.left().value().getArtifacts(); @@ -210,19 +175,19 @@ public class ArtifactOperationTest extends ModelTestBase { artifactOperation.removeArifactFromResource(serviceId, artifactId, NodeTypeEnum.Service, true, false); } - service = serviceOperation.getService(serviceId); + service = toscaOperationFacade.getToscaFullElement(serviceId); assertTrue(service.isLeft()); artifacts = service.left().value().getArtifacts(); assertEquals(0, artifacts.size()); - Either serviceDelete = serviceOperation.deleteService(serviceId); + Either serviceDelete = toscaOperationFacade.deleteToscaComponent(serviceId); Either, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, null, ArtifactData.class); assertTrue(byCriteria.isRight()); assertEquals(TitanOperationStatus.NOT_FOUND, byCriteria.right().value()); - serviceOperation.deleteService(serviceAfterSave.getUniqueId()); + toscaOperationFacade.deleteToscaComponent(serviceAfterSave.getUniqueId()); } @@ -469,7 +434,7 @@ public class ArtifactOperationTest extends ModelTestBase { service.setHighestVersion(isHighestVersion); - Either result = serviceOperation.createService(service, true); + Either result = toscaOperationFacade.createToscaComponent(service); log.info(result.toString()); assertTrue(result.isLeft()); diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java deleted file mode 100644 index f07115af5b..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java +++ /dev/null @@ -1,513 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.UUID; -import java.util.function.Function; -import java.util.stream.Collectors; - -import javax.annotation.Resource; - -import org.apache.tinkerpop.gremlin.structure.io.IoCore; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -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.CapabilityDefinition; -import org.openecomp.sdc.be.model.CapabilityTypeDefinition; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.PropertyConstraint; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; -import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; -import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation; -import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation; -import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; -import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; -import org.openecomp.sdc.be.model.operations.impl.util.ResourceCreationUtils; -import org.openecomp.sdc.be.model.tosca.ToscaType; -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.resources.data.CapabilityData; -import org.openecomp.sdc.be.resources.data.CapabilityInstData; -import org.openecomp.sdc.be.resources.data.PropertyValueData; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import org.openecomp.sdc.be.resources.data.ServiceMetadataData; -import org.openecomp.sdc.be.resources.data.UserData; -import org.openecomp.sdc.be.unittests.utils.FactoryUtils; -import org.openecomp.sdc.be.unittests.utils.FactoryUtils.Constants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:application-context-test.xml") -public class ComponentInstanceOperationSpringTest extends ModelTestBase { - private static Logger log = LoggerFactory.getLogger(ComponentInstanceOperationSpringTest.class.getName()); - @Resource(name = "component-instance-operation") - private ComponentInstanceOperation componentInstanceOperation; - - @Resource(name = "component-instance-operation") - private ComponentInstanceOperation resourceInstanceOperation; - - @Resource(name = "capability-type-operation") - private CapabilityTypeOperation capabilityTypeOperation; - - @Resource(name = "capability-operation") - public CapabilityOperation capabilityOperation; - - @Resource(name = "service-operation") - private ServiceOperation serviceOperation; - - @Resource(name = "resource-operation") - private ResourceOperation resourceOperation; - - @Resource(name = "property-operation") - private PropertyOperation propertyOperation; - - @Resource(name = "lifecycle-operation") - private LifecycleOperation lifecycleOperation; - - TitanGenericDao titanGenericDao; - - private static String CATEGORY_NAME = "category/mycategory"; - - User rfcUser; - - @BeforeClass - public static void setupBeforeClass() { - ModelTestBase.init(); - - } - - @Before - public void cleanUp() { - titanGenericDao = componentInstanceOperation.titanGenericDao; - Either graphResult = titanGenericDao.getGraph(); - TitanGraph graph = graphResult.left().value(); - - Iterable vertices = graph.query().vertices(); - if (vertices != null) { - Iterator iterator = vertices.iterator(); - while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - vertex.remove(); - } - - } - titanGenericDao.commit(); - deleteAndCreateCategory(CATEGORY_NAME); - UserData modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "rfc", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN"); - rfcUser = convertUserDataToUser(modifierData); - } - - @Test - @Ignore - public void testAddCapabilityPropertyValuesToResourceInstance() { - String rootName = "Root123"; - org.openecomp.sdc.be.model.Resource rootResource = createResource(rfcUser.getUserId(), CATEGORY_NAME, rootName, "1.0", null, false, true); - - // certification request - Either requestCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, rootResource, rfcUser, rfcUser, false); - assertTrue(requestCertificationResult.isLeft()); - - org.openecomp.sdc.be.model.Resource resultResource = (org.openecomp.sdc.be.model.Resource) requestCertificationResult.left().value(); - - // start certification - Either startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Resource, resultResource, rfcUser, rfcUser, false); - assertEquals(true, startCertificationResult.isLeft()); - - Either certifiedResourceRes = lifecycleOperation.certifyComponent(NodeTypeEnum.Resource, rootResource, rfcUser, rfcUser, false); - assertTrue(certifiedResourceRes.isLeft()); - - CapabilityTypeDefinition capabilityType = buildCapabilityType(); - Either capabilityTypeRes = capabilityTypeOperation.addCapabilityType(capabilityType); - assertTrue(capabilityTypeRes.isLeft()); - - CapabilityData capData = FactoryUtils.createCapabilityData(); - CapabilityDefinition capabilityDefinitionRoot = FactoryUtils.convertCapabilityDataToCapabilityDefinitionRoot(capData); - - Either addCapabilityRootRes = capabilityOperation.addCapability((String) certifiedResourceRes.left().value().getUniqueId(), capabilityDefinitionRoot.getName(), capabilityDefinitionRoot); - assertTrue(addCapabilityRootRes.isLeft()); - - String resourceName = "tosca.nodes.Apache.2.0"; - - CapabilityDefinition capabilityDefinition = FactoryUtils.convertCapabilityDataToCapabilityDefinitionAddProperties(capData); - org.openecomp.sdc.be.model.Resource resource = createResource(rfcUser.getUserId(), CATEGORY_NAME, resourceName, "0.1", rootName, false, true); - - Either addCapabilityRes = capabilityOperation.addCapability((String) resource.getUniqueId(), capabilityDefinition.getName(), capabilityDefinition); - assertTrue(addCapabilityRes.isLeft()); - List properties = addCapabilityRes.left().value().getProperties(); - assertTrue(properties.size() == 2); - - Either clonedResourceRes = resourceOperation.cloneComponent(resource, "0.2", false); - assertTrue(clonedResourceRes.isLeft()); - org.openecomp.sdc.be.model.Resource clonedResource = clonedResourceRes.left().value(); - - ComponentInstance instance = buildResourceInstance(clonedResource.getUniqueId(), "1", "tosca.nodes.Apache"); - - Service origService = createService(rfcUser.getUserId(), CATEGORY_NAME, "my-service", "1.0", true); - Either service2 = serviceOperation.getService(origService.getUniqueId(), false); - assertTrue(service2.isLeft()); - origService = service2.left().value(); - - Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); - String json = prettyGson.toJson(origService); - log.debug(json); - - Service fullService = origService; - - Either status = resourceInstanceOperation.addComponentInstanceToContainerComponent((String) origService.getUniqueId(), NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false); - assertTrue(status.isLeft()); - - ComponentInstance resourceInstance = status.left().value(); - CapabilityDefinition capability = addCapabilityRes.left().value(); - capability.setName(capabilityDefinition.getName()); - List propertyValues = FactoryUtils.createComponentInstancePropertyList(); - capability.setProperties(propertyValues); - - Either>, TitanOperationStatus> addCPVsToRiRes = componentInstanceOperation.addCapabilityPropertyValuesToResourceInstance(resourceInstance.getUniqueId(), capability, true); - assertTrue(addCPVsToRiRes.isLeft()); - - Either createService = serviceOperation.cloneService(fullService, "2.0", false); - assertTrue(createService.isLeft()); - Map> capabilitiesMap = createService.left().value().getCapabilities(); - assertTrue(capabilitiesMap != null && capabilitiesMap.size() == 1); - Map capabilities = capabilitiesMap.values().iterator().next().stream().collect(Collectors.toMap(CapabilityDefinition::getName, Function.identity())); - assertTrue(capabilities.containsKey("Cap1") && capabilities.containsKey("Cap2")); - - // String outputFile = exportGraphMl(); - - } - - public String exportGraphMl() { - String result = null; - String outputFile = "C:\\Output" + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml"; - TitanGraph graph = titanGenericDao.getGraph().left().value(); - try { - try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) { - graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph); - } - result = outputFile; - graph.tx().commit(); - } catch (Exception e) { - graph.tx().rollback(); - e.printStackTrace(); - } - return result; - - } - - private CapabilityTypeDefinition buildCapabilityType() { - CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition(); - Map properties = new HashMap(); - - capabilityType.setType(Constants.DEFAULT_CAPABILITY_TYPE); - capabilityType.setProperties(properties); - - PropertyDefinition host = new PropertyDefinition(); - host.setUniqueId(UUID.randomUUID().toString()); - host.setName("host"); - host.setDefaultValue("captypehost"); - host.setType("string"); - - host.setSchema(new SchemaDefinition()); - host.getSchema().setProperty(new PropertyDataDefinition()); - host.getSchema().getProperty().setType("string"); - - PropertyDefinition port = new PropertyDefinition(); - port.setName("port"); - port.setDefaultValue("captypeport"); - port.setUniqueId(UUID.randomUUID().toString()); - port.setType("string"); - - port.setSchema(new SchemaDefinition()); - port.getSchema().setProperty(new PropertyDataDefinition()); - port.getSchema().getProperty().setType("string"); - - PropertyDefinition rootproperty = new PropertyDefinition(); - rootproperty.setName("captypeproperty"); - rootproperty.setDefaultValue("captypevalue"); - rootproperty.setUniqueId(UUID.randomUUID().toString()); - rootproperty.setType("string"); - - rootproperty.setSchema(new SchemaDefinition()); - rootproperty.getSchema().setProperty(new PropertyDataDefinition()); - rootproperty.getSchema().getProperty().setType("string"); - - properties.put("host", host); - properties.put("port", port); - properties.put("captypeproperty", rootproperty); - return capabilityType; - } - - private CapabilityInstData buildCapabilityInstanceData(String resourceInstanceId, CapabilityDefinition capability) { - CapabilityInstData capabilityInstance = new CapabilityInstData(); - Long creationTime = System.currentTimeMillis(); - String uniqueId = UniqueIdBuilder.buildCapabilityInstanceUid(resourceInstanceId, capability.getName()); - capabilityInstance.setCreationTime(creationTime); - capabilityInstance.setModificationTime(creationTime); - capabilityInstance.setUniqueId(uniqueId); - return capabilityInstance; - } - - private ComponentInstance buildResourceInstance(String respurceUid, String instanceNumber, String name) { - ComponentInstance resourceInstance = new ComponentInstance(); - resourceInstance.setName(name); - resourceInstance.setDescription("desc1"); - resourceInstance.setPosX("20"); - resourceInstance.setPosY("40"); - resourceInstance.setComponentUid(respurceUid); - resourceInstance.setCreationTime(System.currentTimeMillis()); - resourceInstance.setModificationTime(System.currentTimeMillis()); - resourceInstance.setNormalizedName(ResourceInstanceOperationTest.normaliseComponentInstanceName(name)); - return resourceInstance; - } - - public ResourceMetadataData createResource(String resourceName, TitanGenericDao titanGenericDao) { - ResourceMetadataData serviceData1 = new ResourceMetadataData(); - serviceData1.getMetadataDataDefinition().setUniqueId(resourceName); - Either createNode = titanGenericDao.createNode(serviceData1, ResourceMetadataData.class); - assertTrue("check service created", createNode.isLeft()); - return createNode.left().value(); - } - - public ServiceMetadataData createServiceMetadataData(String serviceName, TitanGenericDao titanGenericDao) { - ServiceMetadataData serviceData1 = new ServiceMetadataData(); - serviceData1.getMetadataDataDefinition().setUniqueId(serviceName); - Either createNode = titanGenericDao.createNode(serviceData1, ServiceMetadataData.class); - assertTrue("check service created", createNode.isLeft()); - return createNode.left().value(); - } - - public Service createService(String userId, String category, String serviceName, String serviceVersion, boolean isHighestVersion) { - Service service = buildServiceMetadata(userId, category, serviceName, serviceVersion); - service.setHighestVersion(isHighestVersion); - Either result = serviceOperation.createService(service, true); - assertTrue(result.isLeft()); - Service resultService = result.left().value(); - assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultService.getLifecycleState()); - return resultService; - } - - private Service buildServiceMetadata(String userId, String category, String serviceName, String serviceVersion) { - Service service = new Service(); - service.setName(serviceName); - service.setVersion(serviceVersion); - service.setDescription("description 1"); - service.setCreatorUserId(userId); - service.setContactId("contactId@sdc.com"); - CategoryDefinition categoryDef = new CategoryDefinition(); - categoryDef.setName(category); - List categories = new ArrayList<>(); - categories.add(categoryDef); - service.setCategories(categories); - service.setIcon("images/my.png"); - List tags = new ArrayList(); - tags.add("TAG1"); - tags.add("TAG2"); - service.setTags(tags); - return service; - } - - private void deleteAndCreateCategory(String category) { - String[] names = category.split("/"); - OperationTestsUtil.deleteAndCreateServiceCategory(category, titanGenericDao); - OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanGenericDao); - } - - private UserData deleteAndCreateUser(String userId, String firstName, String lastName, String role) { - UserData userData = new UserData(); - userData.setUserId(userId); - userData.setFirstName(firstName); - userData.setLastName(lastName); - if (role != null && !role.isEmpty()) { - userData.setRole(role); - } else { - userData.setRole("ADMIN"); - } - titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); - titanGenericDao.createNode(userData, UserData.class); - titanGenericDao.commit(); - return userData; - } - - public org.openecomp.sdc.be.model.Resource createResource(String userId, String category, String resourceName, String resourceVersion, String parentResourceName, boolean isAbstract, boolean isHighestVersion) { - - String propName1 = "disk_size"; - String propName2 = "num_cpus"; - - List derivedFrom = new ArrayList(); - if (parentResourceName != null) { - derivedFrom.add(parentResourceName); - } - org.openecomp.sdc.be.model.Resource resource = buildResourceMetadata(userId, category, resourceName, resourceVersion); - - resource.setAbstract(isAbstract); - resource.setHighestVersion(isHighestVersion); - - Map properties = new HashMap(); - - PropertyDefinition property1 = new PropertyDefinition(); - property1.setDefaultValue("10"); - property1.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node."); - property1.setType(ToscaType.INTEGER.name().toLowerCase()); - List constraints = new ArrayList(); - GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0"); - log.debug("{}", propertyConstraint1); - - constraints.add(propertyConstraint1); - - LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10"); - constraints.add(propertyConstraint2); - - property1.setConstraints(constraints); - - properties.put(propName1, property1); - - PropertyDefinition property2 = new PropertyDefinition(); - property2.setDefaultValue("2"); - property2.setDescription("Number of (actual or virtual) CPUs associated with the Compute node."); - property2.setType(ToscaType.INTEGER.name().toLowerCase()); - List constraints3 = new ArrayList(); - List range = new ArrayList(); - range.add("1"); - range.add("4"); - - InRangeConstraint propertyConstraint3 = new InRangeConstraint(range); - constraints3.add(propertyConstraint3); - property2.setConstraints(constraints3); - properties.put(propName2, property2); - - resource.setDerivedFrom(derivedFrom); - - resource.setProperties(convertMapToList(properties)); - - Either result = resourceOperation.createResource(resource, true); - - assertTrue(result.isLeft()); - org.openecomp.sdc.be.model.Resource resultResource = result.left().value(); - assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultResource.getLifecycleState()); - - String resourceId = resultResource.getUniqueId(); - - Either either = propertyOperation.getPropertyOfResource(propName1, resourceId); - - assertTrue(either.isLeft()); - PropertyDefinition propertyDefinition = either.left().value(); - assertEquals("check property default value", property1.getDefaultValue(), propertyDefinition.getDefaultValue()); - assertEquals("check property description", property1.getDescription(), propertyDefinition.getDescription()); - assertEquals("check property type", property1.getType(), propertyDefinition.getType()); - assertEquals("check property unique id", property1.getUniqueId(), propertyDefinition.getUniqueId()); - assertEquals("check property consitraints size", property1.getConstraints().size(), propertyDefinition.getConstraints().size()); - - return resultResource; - } - - private org.openecomp.sdc.be.model.Resource buildResourceMetadata(String userId, String category, String resourceName, String resourceVersion) { - - org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource(); - resource.setName(resourceName); - resource.setVersion(resourceVersion); - ; - resource.setDescription("description 1"); - resource.setAbstract(false); - resource.setCreatorUserId(userId); - resource.setContactId("contactId@sdc.com"); - resource.setVendorName("vendor 1"); - resource.setVendorRelease("1.0.0"); - resource.setToscaResourceName(resourceName); - String[] categoryArr = category.split("/"); - resource.addCategory(categoryArr[0], categoryArr[1]); - resource.setIcon("images/my.png"); - List tags = new ArrayList(); - tags.add("TAG1"); - tags.add("TAG2"); - resource.setTags(tags); - return resource; - } - - public static List convertMapToList(Map properties) { - if (properties == null) { - return null; - } - - List definitions = new ArrayList<>(); - for (Entry entry : properties.entrySet()) { - String name = entry.getKey(); - PropertyDefinition propertyDefinition = entry.getValue(); - propertyDefinition.setName(name); - definitions.add(propertyDefinition); - } - - return definitions; - } - - private User convertUserDataToUser(UserData modifierData) { - User modifier = new User(); - modifier.setUserId(modifierData.getUserId()); - modifier.setEmail(modifierData.getEmail()); - modifier.setFirstName(modifierData.getFirstName()); - modifier.setLastName(modifierData.getLastName()); - modifier.setRole(modifierData.getRole()); - return modifier; - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java deleted file mode 100644 index c77769d7d2..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.List; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; -import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; -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.ComponentInstance; -import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.be.resources.data.CapabilityData; -import org.openecomp.sdc.be.resources.data.CapabilityInstData; -import org.openecomp.sdc.be.resources.data.RequirementData; -import org.openecomp.sdc.be.unittests.utils.FactoryUtils; - -import fj.data.Either; - -public class ComponentInstanceOperationTest { - - @InjectMocks - ComponentInstanceOperation componentInstanceOperation = new ComponentInstanceOperation(); - @InjectMocks - private TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); - - @Before - public void beforeTest() { - Mockito.reset(titanGenericDao); - MockitoAnnotations.initMocks(this); - } - - @Test - public void testGetCapabilities() { - - ComponentInstance ri = FactoryUtils.createResourceInstance(); - CapabilityData capData = FactoryUtils.createCapabilityData(); - Either>, TitanOperationStatus> childNodesReturned = prepareChildNodeRetValue(capData); - - Mockito.when(titanGenericDao.getChildrenNodes(Mockito.anyString(), Mockito.anyString(), Mockito.any(GraphEdgeLabels.class), Mockito.any(NodeTypeEnum.class), Mockito.any())).thenReturn(childNodesReturned); - - // ImmutablePair>> instanceAndCapabilities = - // componentInstanceOperation.getCapabilities(ri, - // NodeTypeEnum.Resource); - - Either>, TitanOperationStatus> instanceAndCapabilities = componentInstanceOperation.getCapabilities(ri, NodeTypeEnum.Resource); - - // assertTrue(instanceAndCapabilities.left.getUniqueId().equals(ri.getUniqueId())); - assertTrue(instanceAndCapabilities.left().value().size() == 1); - assertTrue(instanceAndCapabilities.left().value().get(0).left.getUniqueId().equals(capData.getUniqueId())); - - } - - @Test - public void testGetRequirements() { - ComponentInstance ri = FactoryUtils.createResourceInstance(); - RequirementData reqData = FactoryUtils.createRequirementData(); - Either>, TitanOperationStatus> childNodesReturned = prepareChildNodeRetValue(reqData); - - Mockito.when(titanGenericDao.getChildrenNodes(Mockito.anyString(), Mockito.anyString(), Mockito.any(GraphEdgeLabels.class), Mockito.any(NodeTypeEnum.class), Mockito.any())).thenReturn(childNodesReturned); - - // ImmutablePair>> instanceAndCapabilities = - // componentInstanceOperation.getRequirements(ri, - // NodeTypeEnum.Resource); - Either>, TitanOperationStatus> instanceAndCapabilities = componentInstanceOperation.getRequirements(ri, NodeTypeEnum.Resource); - - // assertTrue(instanceAndCapabilities.left.getUniqueId().equals(ri.getUniqueId())); - // assertTrue(instanceAndCapabilities.right.size() == 1); - // assertTrue(instanceAndCapabilities.right.get(0).left.getUniqueId().equals(reqData.getUniqueId())); - - assertTrue(instanceAndCapabilities.left().value().size() == 1); - assertTrue(instanceAndCapabilities.left().value().get(0).left.getUniqueId().equals(reqData.getUniqueId())); - - } - - private CapabilityInstData buildCapabilityInstanceData(String resourceInstanceId, CapabilityDefinition capability) { - CapabilityInstData capabilityInstance = new CapabilityInstData(); - Long creationTime = System.currentTimeMillis(); - String uniqueId = UniqueIdBuilder.buildCapabilityInstanceUid(resourceInstanceId, capability.getName()); - - capabilityInstance.setCreationTime(creationTime); - capabilityInstance.setModificationTime(creationTime); - capabilityInstance.setUniqueId(uniqueId); - - return capabilityInstance; - } - - private Either>, TitanOperationStatus> prepareChildNodeRetValue(GraphNode data) { - ImmutablePair pair = new ImmutablePair<>(data, FactoryUtils.createGraphEdge()); - List> retList = new ArrayList<>(); - retList.add(pair); - return Either.left(retList); - } - -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java deleted file mode 100644 index 061393645a..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java +++ /dev/null @@ -1,359 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Collectors; - -import com.thinkaurelius.titan.core.TitanTransaction; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -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.FilterKeyEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.operations.api.ICapabilityOperation; -import org.openecomp.sdc.be.model.operations.api.IRequirementOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation; -import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.be.resources.data.CapabilityData; -import org.openecomp.sdc.be.resources.data.CapabilityInstData; -import org.openecomp.sdc.be.resources.data.ComponentMetadataData; -import org.openecomp.sdc.be.resources.data.PropertyData; -import org.openecomp.sdc.be.resources.data.PropertyValueData; -import org.openecomp.sdc.be.resources.data.RequirementData; -import org.openecomp.sdc.be.unittests.utils.FactoryUtils; - -import fj.data.Either; - -public class ComponentOperationTest { - @InjectMocks - ComponentOperation compOperation = getAnnonimusImpl(); - - ComponentInstanceOperation componentInstanceOperation = Mockito.mock(ComponentInstanceOperation.class); - TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); - ICapabilityOperation capabilityOperation = Mockito.mock(ICapabilityOperation.class); - IRequirementOperation requirementOperation = Mockito.mock(IRequirementOperation.class); - - @Before - public void beforeTest() { - Mockito.reset(componentInstanceOperation, requirementOperation, capabilityOperation); - MockitoAnnotations.initMocks(this); - } - - @Test - public void testGetCapabilities() { - Resource vf = FactoryUtils.createVF(); - ComponentInstance ri = FactoryUtils.createResourceInstance(); - CapabilityData capData = FactoryUtils.createCapabilityData(); - - FactoryUtils.addComponentInstanceToVF(vf, ri); - Either>, TitanOperationStatus> capDataList = prepareCompOperationReturnValue(ri, capData); - - prepareMocksForCapabilitiesMethods(ri, capDataList); - - Map> capabilities = compOperation.getCapabilities(vf, NodeTypeEnum.Resource, false).left().value(); - assertTrue(capabilities.size() == 1); - Entry> entry = capabilities.entrySet().iterator().next(); - assertTrue(entry.getKey().equals(capData.getType())); - assertTrue(entry.getValue().size() == 1); - assertTrue(entry.getValue().get(0).getUniqueId().equals(capData.getUniqueId())); - } - - @Test - public void testGetRequirments() { - Resource vf = FactoryUtils.createVF(); - ComponentInstance ri = FactoryUtils.createResourceInstance(); - - RequirementData reqData = FactoryUtils.createRequirementData(); - - FactoryUtils.addComponentInstanceToVF(vf, ri); - - Either>, TitanOperationStatus> reqDataEdgeList = prepareCompOperationReturnValue(ri, reqData); - - prepareMocksForRequirmenetsMethods(ri, reqDataEdgeList); - - Map> requirements = compOperation.getRequirements(vf, NodeTypeEnum.Resource, false).left().value(); - assertTrue(requirements.size() == 1); - Entry> entry = requirements.entrySet().iterator().next(); - assertTrue(entry.getKey().equals(FactoryUtils.Constants.DEFAULT_CAPABILITY_TYPE)); - assertTrue(entry.getValue().size() == 1); - assertTrue(entry.getValue().get(0).getUniqueId().equals(reqData.getUniqueId())); - } - - private void prepareMocksForRequirmenetsMethods(ComponentInstance ri, Either>, TitanOperationStatus> reqDataEdgeList) { - - when(componentInstanceOperation.getRequirements(ri, NodeTypeEnum.Resource)).thenReturn(reqDataEdgeList); - when(requirementOperation.getRequirement(Mockito.anyString())).then(createReqDefAnswer()); - } - - private void prepareMocksForCapabilitiesMethods(ComponentInstance ri, Either>, TitanOperationStatus> capDataList) { - when(componentInstanceOperation.getCapabilities(ri, NodeTypeEnum.Resource)).thenReturn(capDataList); - when(capabilityOperation.getCapabilityByCapabilityData(Mockito.any(CapabilityData.class))).then(createCapDefByDataAnswer()); - List> capInstList = new ArrayList<>(); - CapabilityInstData curCapabilityInst = FactoryUtils.createCapabilityInstData(); - GraphEdge edge = new GraphEdge(); - Map properties = new HashMap<>(); - properties.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capDataList.left().value().get(0).getLeft().getUniqueId()); - edge.setProperties(properties); - ImmutablePair pair = new ImmutablePair(curCapabilityInst, edge); - capInstList.add(pair); - when(titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByNameIgnoreCase(ri.getOriginType().getInstanceType().trim())), ri.getUniqueId(), GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, - CapabilityInstData.class)).thenReturn(Either.left(capInstList)); - - when(titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curCapabilityInst.getLabel())), curCapabilityInst.getUniqueId(), GraphEdgeLabels.INSTANCE_OF, NodeTypeEnum.Capability, CapabilityData.class)) - .thenReturn(Either.left(capDataList.left().value().get(0))); - - PropertyValueData propertyValueData = FactoryUtils.createPropertyData(); - ImmutablePair propPair = new ImmutablePair(propertyValueData, null); - List> propPairList = new ArrayList<>(); - propPairList.add(propPair); - when(titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curCapabilityInst.getLabel())), curCapabilityInst.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, - PropertyValueData.class)).thenReturn(Either.left(propPairList)); - - CapabilityDefinition capDef = FactoryUtils.convertCapabilityDataToCapabilityDefinitionAddProperties(capDataList.left().value().get(0).getLeft()); - List propDefList = capDef.getProperties().stream().filter(p -> p.getName().equals("host")).collect(Collectors.toList()); - PropertyDefinition propDef = propDefList.get(0); - PropertyData propData = FactoryUtils.convertCapabilityDefinitionToCapabilityData(propDef); - - ImmutablePair defPropPair = new ImmutablePair(propData, edge); - - when(titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(propertyValueData.getLabel())), propertyValueData.getUniqueId(), GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class)) - .thenReturn(Either.left(defPropPair)); - List capDefList = new ArrayList<>(); - capDefList.add(capDef); - when(componentInstanceOperation.updateCapDefPropertyValues(Mockito.any(ComponentInstance.class), Mockito.any(List.class))).thenReturn(Either.left(capDefList)); - } - - private Either>, TitanOperationStatus> prepareCompOperationReturnValue(ComponentInstance ri, Data data) { - ImmutablePair dataEdgePair = new ImmutablePair<>(data, new GraphEdge()); - List> dataEdgeList = new ArrayList<>(); - dataEdgeList.add(dataEdgePair); - return Either.left(dataEdgeList); - } - - private Answer> createReqDefAnswer() { - return new Answer>() { - - @Override - public Either answer(InvocationOnMock invocation) throws Throwable { - String reqDataId = (String) invocation.getArguments()[0]; - return Either.left(FactoryUtils.convertRequirementDataIDToRequirementDefinition(reqDataId)); - } - }; - } - - private Answer> createCapDefByDataAnswer() { - return new Answer>() { - - @Override - public Either answer(InvocationOnMock invocation) throws Throwable { - CapabilityData capData = (CapabilityData) invocation.getArguments()[0]; - return Either.left(FactoryUtils.convertCapabilityDataToCapabilityDefinitionAddProperties(capData)); - } - }; - } - - private ComponentOperation getAnnonimusImpl() { - return new ComponentOperation() { - - @Override - protected StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type) { - // TODO Auto-generated method stub - return null; - } - - @Override - protected StorageOperationStatus updateDerived(Component component, Component currentComponent, ComponentMetadataData updatedResourceData, Class clazz) { - // TODO Auto-generated method stub - return null; - } - - @Override - protected Either updateComponent(T component, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } - - @Override - protected ComponentMetadataData getMetaDataFromComponent(Component component) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either getLightComponent(String id, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } - - @Override - protected Either getComponentByNameAndVersion(String name, String version, Map additionalParams, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either getComponent(String id, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } - - // @Override - // public Either - // getComponent_tx(String id, boolean inTransaction) { - // // TODO Auto-generated method stub - // return null; - // } - - @Override - public Either, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either cloneComponent(T other, String version, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Component getDefaultComponent() { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean isComponentExist(String componentId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public Either getMetadataComponent(String id, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } - - @Override - Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData) { - // TODO Auto-generated method stub - return null; - } - - @Override - TitanOperationStatus setComponentCategoriesFromGraph(Component component) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either validateComponentNameExists(String componentName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either markComponentToDelete(Component componentToDelete, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either deleteComponent(String id, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either isComponentInUse(String componentId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either, StorageOperationStatus> getAllComponentsMarkedForDeletion() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either getComponent(String id, ComponentParametersView componentParametersView, boolean inTrasnaction) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either, StorageOperationStatus> getFilteredComponents(Map filters, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } - - @Override - protected Either updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterParametersView) { - // TODO Auto-generated method stub - return null; - } - - }; - } - -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java index 759fd2b811..d1389f0f94 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java @@ -20,45 +20,27 @@ package org.openecomp.sdc.be.model.operations.impl; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.HashMap; -import java.util.Map; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; -import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.ModelTestBase; import org.openecomp.sdc.be.model.Operation; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; -import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; import org.openecomp.sdc.be.resources.data.UserData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import fj.data.Either; +import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context-test.xml") @@ -78,9 +60,6 @@ public class InterfaceOperationTest { @javax.annotation.Resource(name = "interface-operation") private InterfaceLifecycleOperation interfaceOperation; - @javax.annotation.Resource(name = "resource-operation") - private ResourceOperation resourceOperation; - @javax.annotation.Resource(name = "property-operation") private PropertyOperation propertyOperation; diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java deleted file mode 100644 index 23090fe143..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java +++ /dev/null @@ -1,1993 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; -import org.junit.runner.RunWith; -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.components.ServiceMetadataDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.CapabilityTypeDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.InterfaceDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.Operation; -import org.openecomp.sdc.be.model.PropertyConstraint; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; -import org.openecomp.sdc.be.model.operations.impl.util.ResourceCreationUtils; -import org.openecomp.sdc.be.model.tosca.ToscaType; -import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint; -import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint; -import org.openecomp.sdc.be.resources.data.CapabilityData; -import org.openecomp.sdc.be.resources.data.ComponentInstanceData; -import org.openecomp.sdc.be.resources.data.InterfaceData; -import org.openecomp.sdc.be.resources.data.OperationData; -import org.openecomp.sdc.be.resources.data.RequirementData; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import org.openecomp.sdc.be.resources.data.ServiceMetadataData; -import org.openecomp.sdc.be.resources.data.UserData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.thinkaurelius.titan.core.TitanGraph; -//import com.tinkerpop.blueprints.Vertex; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:application-context-test.xml") -public class LifecycleOperationTest extends ModelTestBase { - private static Logger log = LoggerFactory.getLogger(LifecycleOperationTest.class.getName()); - private static final String CAPABILITY_HOSTED_ON = "HostedOn"; - - private static final String INTERFACE_OPERATION_CREATE = "create"; - - private static final String INTERFACE_NAME = "standard"; - - private static final String CATEGORY_NAME = "category/mycategory"; - - private static final String SERVICE_NAME = "myService"; - - private static final String REQUIREMENT_NAME = "requirementName"; - - private static final String CAPABILITY_NAME = "capName"; - - private static final String USER_ID = "muUserId"; - - @javax.annotation.Resource - private TitanGenericDao titanGenericDao; - - @javax.annotation.Resource - private ResourceOperation resourceOperation; - - @javax.annotation.Resource - private ServiceOperation serviceOperation; - - @javax.annotation.Resource - private LifecycleOperation lifecycleOperation; - - @javax.annotation.Resource - private CapabilityTypeOperation capabilityTypeOperation; - - @javax.annotation.Resource - private ArtifactOperation artifactOperation; - - @javax.annotation.Resource - private InterfaceLifecycleOperation interfaceOperation; - - @javax.annotation.Resource(name = "property-operation") - private PropertyOperation propertyOperation; - - @javax.annotation.Resource(name = "capability-operation") - private CapabilityOperation capabilityOperation; - - @javax.annotation.Resource(name = "component-instance-operation") - private ComponentInstanceOperation resourceInstanceOperation; - - @javax.annotation.Resource(name = "requirement-operation") - private RequirementOperation requirementOperation; - - User checkoutUser; - User checkinUser; - User rfcUser; - User testerUser; - User adminUser; - - @Rule - public TestName name = new TestName(); - - @BeforeClass - public static void initLifecycleOperation() { - ModelTestBase.init(); - // new ConfigurationSource() { - // - // @Override - // public T getAndWatchConfiguration(Class className, - // ConfigurationListener configurationListener) { - // // TODO Auto-generated method stub - // return null; - // } - // - // @Override - // public void addWatchConfiguration(Class className, - // ConfigurationListener configurationListener) { - // // TODO Auto-generated method stub - // - // } - // }); - // - - } - - @Before - public void setupBefore() { - clearGraph(); - UserData modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "co", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN"); - checkoutUser = convertUserDataToUser(modifierData); - - modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "ci", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN"); - checkinUser = convertUserDataToUser(modifierData); - - modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "rfc", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN"); - rfcUser = convertUserDataToUser(modifierData); - - modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "tester", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "TESTER"); - testerUser = convertUserDataToUser(modifierData); - - modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "admin", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN"); - adminUser = convertUserDataToUser(modifierData); - - modifierData = deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID, "ADMIN"); - adminUser = convertUserDataToUser(modifierData); - - String[] category = CATEGORY_NAME.split("/"); - OperationTestsUtil.deleteAndCreateServiceCategory(CATEGORY_NAME, titanGenericDao); - OperationTestsUtil.deleteAndCreateResourceCategory(category[0], category[1], titanGenericDao); - - } - - @After - public void teardown() { - clearGraph(); - } - - private void clearGraph() { - Either graphResult = titanGenericDao.getGraph(); - TitanGraph graph = graphResult.left().value(); - - Iterable vertices = graph.query().vertices(); - if (vertices != null) { - Iterator iterator = vertices.iterator(); - while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - // graph.removeVertex(vertex); - vertex.remove(); - } - - } - titanGenericDao.commit(); - } - - @Test - @Ignore - public void getOwnerTest() { - - Resource resultResource = createTestResource(checkoutUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - assertEquals("check modifier", checkoutUser.getUserId(), resourceOwner.getUserId()); - - } - - /*********************** CHECKOUT ***************************************************************/ - - @Test - @Ignore - public void checkoutCertifiedTest() { - - Resource resultResource = createTestResource(adminUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null); - String origUniqueId = resultResource.getUniqueId(); - Either origResourceResult = resourceOperation.getResource(origUniqueId); - Resource origResource = origResourceResult.left().value(); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - // checkout - Either checkoutResponse = (Either) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false); - assertEquals("check resource object is returned", true, checkoutResponse.isLeft()); - Resource checkoutResource = checkoutResponse.left().value(); - - assertEquals(checkoutResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(checkoutResource.getVersion(), "1.1"); - assertEquals(checkoutResource.getCreatorUserId(), adminUser.getUserId()); - assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId()); - - // assert owner changed - Either getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Resource, false); - assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); - resourceOwner = getOwnerCheckoutResponse.left().value(); - assertTrue(resourceOwner.equals(checkoutUser)); - - // assert original resource not deleted - Either getOrigResource = resourceOperation.getResource(origUniqueId); - assertEquals("check resource created", true, getOrigResource.isLeft()); - // assertEquals("assert original resource not changed", origResource, - // getOrigResource.left().value()); - } - - @Test - @Ignore - public void checkoutDefaultTest() { - - Resource resultResource = createTestResource(checkinUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); - String origUniqueId = resultResource.getUniqueId(); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - // checkout - Either checkoutResponse = (Either) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false); - assertEquals("check resource object is returned", true, checkoutResponse.isLeft()); - Resource checkoutResource = checkoutResponse.left().value(); - - assertEquals(checkoutResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(checkoutResource.getVersion(), "0.2"); - assertEquals(checkoutResource.getCreatorUserId(), checkinUser.getUserId()); - assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId()); - assertEquals(checkoutResource.isHighestVersion(), true); - - // assert owner changed - Either getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Resource, false); - assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); - resourceOwner = getOwnerCheckoutResponse.left().value(); - assertTrue(resourceOwner.equals(checkoutUser)); - - // assert original resource not deleted - Either getOrigResource = resourceOperation.getResource(origUniqueId); - assertEquals("check resource created", true, getOrigResource.isLeft()); - // assertEquals("assert original resource not changed", origResource, - // getOrigResource.left().value()); - assertEquals("assert original resource not highest version", false, getOrigResource.left().value().isHighestVersion()); - } - - @Test - @Ignore - public void checkoutFullResourceTest() { - - Resource origResource = createFullTestResource(checkinUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - String origUniqueId = origResource.getUniqueId(); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - // checkout - Either checkoutResponse = (Either) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, origResource, checkoutUser, resourceOwner, false); - assertEquals("check resource object is returned", true, checkoutResponse.isLeft()); - Resource checkoutResource = checkoutResponse.left().value(); - - assertEquals(checkoutResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(checkoutResource.getVersion(), "0.2"); - assertEquals(checkoutResource.getCreatorUserId(), checkinUser.getUserId()); - assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId()); - assertEquals(checkoutResource.isHighestVersion(), true); - - assertNotNull(checkoutResource.getArtifacts()); - assertFalse(checkoutResource.getArtifacts().isEmpty()); - assertNotNull(checkoutResource.getInterfaces()); - assertFalse(checkoutResource.getInterfaces().isEmpty()); - Map interfaces = checkoutResource.getInterfaces(); - assertTrue(interfaces.containsKey(INTERFACE_NAME)); - InterfaceDefinition interfaceDef = interfaces.get(INTERFACE_NAME); - Map operations = interfaceDef.getOperationsMap(); - assertNotNull(operations); - assertFalse(operations.isEmpty()); - assertTrue(operations.containsKey(INTERFACE_OPERATION_CREATE)); - Operation op = operations.get(INTERFACE_OPERATION_CREATE); - assertNotNull(op.getImplementation()); - - // assert owner changed - Either getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Resource, false); - assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); - resourceOwner = getOwnerCheckoutResponse.left().value(); - assertTrue(resourceOwner.equals(checkoutUser)); - - // assert original resource not deleted - Either getOrigResource = resourceOperation.getResource(origUniqueId); - assertEquals("check resource created", true, getOrigResource.isLeft()); - // assertEquals("assert original resource not changed", origResource, - // getOrigResource.left().value()); - assertEquals("assert original resource not highest version", false, getOrigResource.left().value().isHighestVersion()); - } - - @Test - @Ignore - public void getResourceOwnerResourceNotExistTest() { - - // create resource metadata - Resource resource = buildResourceMetadata(adminUser.getUserId(), CATEGORY_NAME); - resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); - resource.setUniqueId("my-resource.0.1"); - - Either origResourceResult = resourceOperation.getResource("my-resource.0.1"); - assertEquals("assert resource not exist", true, origResourceResult.isRight()); - - // get resource owner - - Either getOwnerResponse = lifecycleOperation.getComponentOwner("my-resource.0.1", NodeTypeEnum.Resource, false); - - assertEquals("assert no owner", true, getOwnerResponse.isRight()); - StorageOperationStatus status = getOwnerResponse.right().value(); - - assertEquals(StorageOperationStatus.INVALID_ID, status); - - } - - @Test - @Ignore - public void checkoutResourceTwice() { - - Resource resultResource = createTestResource(adminUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null); - String origUniqueId = resultResource.getUniqueId(); - Either origResourceResult = resourceOperation.getResource(origUniqueId); - Resource origResource = origResourceResult.left().value(); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - // first checkout - Either checkoutResponse1 = (Either) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false); - assertEquals("check resource object is returned", true, checkoutResponse1.isLeft()); - - // second checkout - Either checkoutResponse2 = (Either) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, origResource, checkoutUser, resourceOwner, false); - assertEquals("check checkout failed", true, checkoutResponse2.isRight()); - assertEquals(StorageOperationStatus.ENTITY_ALREADY_EXISTS, checkoutResponse2.right().value()); - - } - - /******** SERVICE */ - @Test - public void checkoutServiceDefaultTest() { - - Service resultResource = createTestService(checkinUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); - String origUniqueId = resultResource.getUniqueId(); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - // checkout - Either checkoutResponse = lifecycleOperation.checkoutComponent(NodeTypeEnum.Service, resultResource, checkoutUser, resourceOwner, false); - assertEquals("check resource object is returned", true, checkoutResponse.isLeft()); - Component checkoutResource = checkoutResponse.left().value(); - - assertEquals(checkoutResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(checkoutResource.getVersion(), "0.2"); - assertEquals(checkoutResource.getCreatorUserId(), checkinUser.getUserId()); - assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId()); - assertEquals(checkoutResource.isHighestVersion(), true); - - // assert owner changed - Either getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Service, false); - assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); - resourceOwner = getOwnerCheckoutResponse.left().value(); - assertTrue(resourceOwner.equals(checkoutUser)); - - // assert original resource not deleted - Either getOrigResource = serviceOperation.getService(origUniqueId); - assertEquals("check resource created", true, getOrigResource.isLeft()); - // assertEquals("assert original resource not changed", origResource, - // getOrigResource.left().value()); - assertEquals("assert original resource not highest version", false, getOrigResource.left().value().isHighestVersion()); - } - - @Test - @Ignore - public void checkoutFullServiceTest() { - - Service origService = createTestService(checkinUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); - String origUniqueId = origService.getUniqueId(); - - // add artifacts - addArtifactToService(checkinUser.getUserId(), origService.getUniqueId(), "install_apache"); - addArtifactToService(checkinUser.getUserId(), origService.getUniqueId(), "start_apache"); - - // add resource instances - ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest(); - riTest.setOperations(titanGenericDao, capabilityTypeOperation, requirementOperation, capabilityOperation, resourceOperation, propertyOperation, resourceInstanceOperation); - riTest.addResourceInstancesAndRelation(origService.getUniqueId()); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - Either serviceBeforeCheckout = serviceOperation.getService(origUniqueId, true); - assertTrue(serviceBeforeCheckout.isLeft()); - origService = serviceBeforeCheckout.left().value(); - - // checkout - Either checkoutResponse = lifecycleOperation.checkoutComponent(NodeTypeEnum.Service, origService, checkoutUser, resourceOwner, false); - assertEquals("check resource object is returned", true, checkoutResponse.isLeft()); - Service checkoutResource = (Service) checkoutResponse.left().value(); - - assertEquals(checkoutResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(checkoutResource.getVersion(), "0.2"); - assertEquals(checkoutResource.getCreatorUserId(), checkinUser.getUserId()); - assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId()); - assertEquals(checkoutResource.isHighestVersion(), true); - - assertNotNull(checkoutResource.getArtifacts()); - assertFalse(checkoutResource.getArtifacts().isEmpty()); - assertNotNull(checkoutResource.getComponentInstances()); - assertFalse(checkoutResource.getComponentInstances().isEmpty()); - assertNotNull(checkoutResource.getComponentInstancesRelations()); - assertFalse(checkoutResource.getComponentInstancesRelations().isEmpty()); - - // assert owner changed - Either getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Service, false); - assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); - resourceOwner = getOwnerCheckoutResponse.left().value(); - assertTrue(resourceOwner.equals(checkoutUser)); - - // assert original resource not deleted - Either getOrigResource = serviceOperation.getService(origUniqueId); - assertEquals("check service created", true, getOrigResource.isLeft()); - // assertEquals("assert original resource not changed", origResource, - // getOrigResource.left().value()); - assertEquals("assert original service not highest version", false, getOrigResource.left().value().isHighestVersion()); - } - - @Test - @Ignore - public void checkoutServiceTwice() { - - Service resultResource = createTestService(adminUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null); - String origUniqueId = resultResource.getUniqueId(); - Either origResourceResult = serviceOperation.getService(origUniqueId); - Service origResource = origResourceResult.left().value(); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - // first checkout - Either checkoutResponse1 = lifecycleOperation.checkoutComponent(NodeTypeEnum.Service, resultResource, checkoutUser, resourceOwner, false); - assertEquals("check resource object is returned", true, checkoutResponse1.isLeft()); - - // second checkout - Either checkoutResponse2 = lifecycleOperation.checkoutComponent(NodeTypeEnum.Service, origResource, checkoutUser, resourceOwner, false); - assertEquals("check checkout failed", true, checkoutResponse2.isRight()); - assertEquals(StorageOperationStatus.ENTITY_ALREADY_EXISTS, checkoutResponse2.right().value()); - - } - - /**************************** CHECKIN ********************************************************************/ - - @Test - @Ignore - public void checkinDefaultTest() { - - Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null); - String origUniqueId = resultResource.getUniqueId(); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - // checkin - Either checkinResponse = (Either) lifecycleOperation.checkinComponent(NodeTypeEnum.Resource, resultResource, checkinUser, resourceOwner, false); - assertEquals("check resource object is returned", true, checkinResponse.isLeft()); - Resource checkinResource = checkinResponse.left().value(); - - assertEquals(checkinResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertEquals(checkinResource.getVersion(), "0.1"); - assertEquals(checkinResource.getCreatorUserId(), adminUser.getUserId()); - assertEquals(checkinResource.getLastUpdaterUserId(), checkinUser.getUserId()); - - // assert owner changed - Either getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkinResource.getUniqueId(), NodeTypeEnum.Resource, false); - assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); - resourceOwner = getOwnerCheckoutResponse.left().value(); - assertTrue(resourceOwner.equals(checkinUser)); - - } - - @Test - @Ignore - public void checkinFromRfcTest() { - - Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null); - String origUniqueId = resultResource.getUniqueId(); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - // checkin - Either checkinResponse = (Either) lifecycleOperation.checkinComponent(NodeTypeEnum.Resource, resultResource, checkinUser, resourceOwner, false); - assertEquals("check resource object is returned", true, checkinResponse.isLeft()); - - // rfc - Either rfcResponse = (Either) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, checkinResponse.left().value(), rfcUser, checkinUser, false); - assertEquals("check resource object is returned", true, checkinResponse.isLeft()); - - // checkin (cancel rfc) - checkinResponse = (Either) lifecycleOperation.checkinComponent(NodeTypeEnum.Resource, rfcResponse.left().value(), checkinUser, rfcUser, false); - assertEquals("check resource object is returned", true, checkinResponse.isLeft()); - resultResource = checkinResponse.left().value(); - - assertEquals(resultResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertEquals(resultResource.getVersion(), "0.1"); - assertEquals(resultResource.getCreatorUserId(), adminUser.getUserId()); - assertEquals(resultResource.getLastUpdaterUserId(), checkinUser.getUserId()); - - // assert owner changed - Either getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false); - assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); - resourceOwner = getOwnerCheckoutResponse.left().value(); - assertTrue(resourceOwner.equals(checkinUser)); - - // assert relations - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(resultResource.getUniqueId()); - Map props = new HashMap(); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - Either incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isRight()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - } - - /*** SERVICE */ - @Test - @Ignore - public void checkinServiceDefaultTest() { - - Service resultService = createTestService(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null); - String origUniqueId = resultService.getUniqueId(); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - // checkin - Either checkinResponse = lifecycleOperation.checkinComponent(NodeTypeEnum.Service, resultService, checkinUser, resourceOwner, false); - assertEquals("check service object is returned", true, checkinResponse.isLeft()); - Service checkinResource = (Service) checkinResponse.left().value(); - - assertEquals(checkinResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertEquals(checkinResource.getVersion(), "0.1"); - assertEquals(checkinResource.getCreatorUserId(), adminUser.getUserId()); - assertEquals(checkinResource.getLastUpdaterUserId(), checkinUser.getUserId()); - - // assert owner changed - Either getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkinResource.getUniqueId(), NodeTypeEnum.Service, false); - assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); - resourceOwner = getOwnerCheckoutResponse.left().value(); - assertTrue(resourceOwner.equals(checkinUser)); - - } - - @Test - @Ignore - public void checkinServiceFromRfcTest() { - - Service resultResource = createTestService(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null); - String origUniqueId = resultResource.getUniqueId(); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - // checkin - Either checkinResponse = lifecycleOperation.checkinComponent(NodeTypeEnum.Service, resultResource, checkinUser, resourceOwner, false); - assertEquals("check service object is returned", true, checkinResponse.isLeft()); - - // rfc - Either rfcResponse = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, checkinResponse.left().value(), rfcUser, checkinUser, false); - assertEquals("check service object is returned", true, checkinResponse.isLeft()); - - // checkin (cancel rfc) - checkinResponse = lifecycleOperation.checkinComponent(NodeTypeEnum.Service, rfcResponse.left().value(), checkinUser, rfcUser, false); - assertEquals("check resource object is returned", true, checkinResponse.isLeft()); - resultResource = (Service) checkinResponse.left().value(); - - assertEquals(resultResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertEquals(resultResource.getVersion(), "0.1"); - assertEquals(resultResource.getCreatorUserId(), adminUser.getUserId()); - assertEquals(resultResource.getLastUpdaterUserId(), checkinUser.getUserId()); - - // assert owner changed - Either getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Service, false); - assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); - resourceOwner = getOwnerCheckoutResponse.left().value(); - assertTrue(resourceOwner.equals(checkinUser)); - - // assert relations - ServiceMetadataDataDefinition metadata = new ServiceMetadataDataDefinition(); - metadata.setUniqueId(resultResource.getUniqueId()); - ServiceMetadataData resourceData = new ServiceMetadataData(metadata); - Map props = new HashMap(); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - Either incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isRight()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - } - - /**************************** - * UNDO CHECKOUT - ********************************************************************/ - - @Test - @Ignore - public void undoCheckoutNewResourceTest() { - - Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null); - String origUniqueId = resultResource.getUniqueId(); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - // - - // undo checkout - Either undoCheckoutResponse = (Either) lifecycleOperation.undoCheckout(NodeTypeEnum.Resource, resultResource, adminUser, resourceOwner, false); - assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft()); - - Either origResourceResult = resourceOperation.getResource(origUniqueId); - assertTrue(origResourceResult.isRight()); - /* - * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true); - */ - } - - @Test - @Ignore - public void undoCheckoutNewFullResourceTest() { - - Resource resultResource = createFullTestResource(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - String origUniqueId = resultResource.getUniqueId(); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - // undo checkout - Either undoCheckoutResponse = (Either) lifecycleOperation.undoCheckout(NodeTypeEnum.Resource, resultResource, adminUser, resourceOwner, false); - assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft()); - - Either origResourceResult = resourceOperation.getResource(origUniqueId); - /* - * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true); - */ assertTrue(origResourceResult.isRight()); - - String interfaceId = origUniqueId + "." + INTERFACE_NAME; - Either node = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceId, InterfaceData.class); - assertTrue(node.isRight()); - - String operationId = interfaceId + "." + INTERFACE_OPERATION_CREATE; - Either op = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InterfaceOperation), operationId, OperationData.class); - assertTrue(op.isRight()); - - String capabilityId = "capability." + origUniqueId + "." + CAPABILITY_NAME; - Either capability = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityId, CapabilityData.class); - assertTrue(capability.isRight()); - - String requirementId = origUniqueId + "." + REQUIREMENT_NAME; - Either req = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementId, RequirementData.class); - assertTrue(req.isRight()); - - } - - @Test - @Ignore - public void undoCheckoutExistingResourceTest() { - - Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); - - // get resource owner - Either getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - String prevResourceId = resultResource.getUniqueId(); - Either result2 = (Either) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false); - assertEquals("check resource created", true, result2.isLeft()); - Resource resultResource2 = result2.left().value(); - - // get resource owner - getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource2.getUniqueId(), NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - resourceOwner = getOwnerResponse.left().value(); - assertEquals(resourceOwner, checkoutUser); - - // undo checkout - Either undoCheckoutResponse = (Either) lifecycleOperation.undoCheckout(NodeTypeEnum.Resource, resultResource2, checkoutUser, resourceOwner, false); - assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft()); - - // get previous resource - Either resourceAfterUndo = resourceOperation.getResource(prevResourceId); - assertTrue(resourceAfterUndo.isLeft()); - Resource actualResource = resourceAfterUndo.left().value(); - assertTrue(actualResource.isHighestVersion()); - assertEquals(adminUser.getUserId(), actualResource.getCreatorUserId()); - assertEquals(adminUser.getUserId(), actualResource.getLastUpdaterUserId()); - assertEquals("0.1", actualResource.getVersion()); - assertEquals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, actualResource.getLifecycleState()); - - Either origResourceResult = resourceOperation.getResource(resultResource2.getUniqueId()); - /* - * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true); - */ assertTrue(origResourceResult.isRight()); - - } - - /**** SERVICE ***/ - @Test - @Ignore - public void undoCheckoutNewServiceTest() { - - Service resultResource = createTestService(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null); - String origUniqueId = resultResource.getUniqueId(); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - // - - // undo checkout - Either undoCheckoutResponse = lifecycleOperation.undoCheckout(NodeTypeEnum.Service, resultResource, adminUser, resourceOwner, false); - assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft()); - - Either origResourceResult = serviceOperation.getService(origUniqueId); - /* - * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true); - */ assertTrue(origResourceResult.isRight()); - - } - - @Test - @Ignore - public void undoCheckoutNewFullServiceTest() { - - Service origService = createTestService(checkinUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); - String origUniqueId = origService.getUniqueId(); - - // add artifacts - addArtifactToService(checkinUser.getUserId(), origService.getUniqueId(), "install_apache"); - addArtifactToService(checkinUser.getUserId(), origService.getUniqueId(), "start_apache"); - - // add resource instances - ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest(); - riTest.setOperations(titanGenericDao, capabilityTypeOperation, requirementOperation, capabilityOperation, resourceOperation, propertyOperation, resourceInstanceOperation); - riTest.addResourceInstancesAndRelation(origService.getUniqueId()); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - Either service = serviceOperation.getService(origUniqueId); - assertTrue(service.isLeft()); - - Service resultResource = service.left().value(); - List resourceInstances = resultResource.getComponentInstances(); - - // undo checkout - Either undoCheckoutResponse = lifecycleOperation.undoCheckout(NodeTypeEnum.Service, resultResource, adminUser, resourceOwner, false); - assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft()); - - Either origResourceResult = serviceOperation.getService(origUniqueId); - /* - * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true); - */ assertTrue(origResourceResult.isRight()); - - for (ComponentInstance ri : resourceInstances) { - Either node = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), ri.getUniqueId(), ComponentInstanceData.class); - assertTrue(node.isRight()); - } - - } - - @Test - @Ignore - public void undoCheckoutExistingServiceTest() { - - Service resultResource = createTestService(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); - - // get resource owner - Either getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - String prevResourceId = resultResource.getUniqueId(); - Either result2 = lifecycleOperation.checkoutComponent(NodeTypeEnum.Service, resultResource, checkoutUser, resourceOwner, false); - assertEquals("check resource created", true, result2.isLeft()); - Component resultResource2 = result2.left().value(); - String result2Uid = resultResource.getUniqueId(); - - // get resource owner - getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource2.getUniqueId(), NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - resourceOwner = getOwnerResponse.left().value(); - assertEquals(resourceOwner, checkoutUser); - - // undo checkout - Either undoCheckoutResponse = lifecycleOperation.undoCheckout(NodeTypeEnum.Service, resultResource2, checkoutUser, resourceOwner, false); - assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft()); - - // get previous resource - Either resourceAfterUndo = serviceOperation.getService(prevResourceId); - assertTrue(resourceAfterUndo.isLeft()); - Service actualResource = resourceAfterUndo.left().value(); - assertTrue(actualResource.isHighestVersion()); - assertEquals(adminUser.getUserId(), actualResource.getCreatorUserId()); - assertEquals(adminUser.getUserId(), actualResource.getLastUpdaterUserId()); - assertEquals("0.1", actualResource.getVersion()); - assertEquals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, actualResource.getLifecycleState()); - - Either origResourceResult = serviceOperation.getService(result2Uid); - /* - * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true); - */ assertTrue(origResourceResult.isRight()); - - } - - /**************************** - * CERTIFICATION REQUEST - ********************************************************************/ - - @Test - @Ignore - public void certReqDefaultTest() { - Resource actualResource = testCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - - // assert relations - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId()); - Map props = new HashMap(); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - Either incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(adminUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - } - - @Test - @Ignore - public void atomicCheckinCertReqTest() { - Resource actualResource = testCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - - // assert relations - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId()); - Map props = new HashMap(); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - Either incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - } - - private Resource testCertificationRequest(LifecycleStateEnum preState) { - - Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", preState, null); - String origUniqueId = resultResource.getUniqueId(); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - // checkin - Either certReqResponse = (Either) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, resourceOwner, false); - assertEquals("check resource object is returned", true, certReqResponse.isLeft()); - Resource resourceAfterChange = certReqResponse.left().value(); - - assertEquals(resourceAfterChange.getLifecycleState(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - assertEquals(resourceAfterChange.getVersion(), "0.1"); - assertEquals(resourceAfterChange.getCreatorUserId(), adminUser.getUserId()); - assertEquals(resourceAfterChange.getLastUpdaterUserId(), rfcUser.getUserId()); - - // assert owner changed - Either getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(resourceAfterChange.getUniqueId(), NodeTypeEnum.Resource, false); - assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); - resourceOwner = getOwnerCheckoutResponse.left().value(); - assertTrue(resourceOwner.equals(rfcUser)); - - return resourceAfterChange; - } - - /** SERVICE **/ - @Test - @Ignore - public void certServiceReqDefaultTest() { - Service actualResource = testServiceCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - - // assert relations - ServiceMetadataDataDefinition metadata = new ServiceMetadataDataDefinition(); - metadata.setUniqueId(actualResource.getUniqueId()); - ServiceMetadataData serviceData = new ServiceMetadataData(metadata); - Map props = new HashMap(); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - Either incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(adminUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - } - - @Test - @Ignore - public void atomicServiceCheckinCertReqTest() { - Service actualResource = testServiceCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - - // assert relations - ServiceMetadataDataDefinition metadata = new ServiceMetadataDataDefinition(); - metadata.setUniqueId(actualResource.getUniqueId()); - ServiceMetadataData serviceData = new ServiceMetadataData(metadata); - Map props = new HashMap(); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - Either incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - } - - private Service testServiceCertificationRequest(LifecycleStateEnum preState) { - - Service resultResource = createTestService(adminUser.getUserId(), "0.1", preState, null); - String origUniqueId = resultResource.getUniqueId(); - - Either getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - - // checkin - Either certReqResponse = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultResource, rfcUser, resourceOwner, false); - assertEquals("check resource object is returned", true, certReqResponse.isLeft()); - Service resourceAfterChange = (Service) certReqResponse.left().value(); - - assertEquals(resourceAfterChange.getLifecycleState(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - assertEquals(resourceAfterChange.getVersion(), "0.1"); - assertEquals(resourceAfterChange.getCreatorUserId(), adminUser.getUserId()); - assertEquals(resourceAfterChange.getLastUpdaterUserId(), rfcUser.getUserId()); - - // assert owner changed - Either getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(resourceAfterChange.getUniqueId(), NodeTypeEnum.Service, false); - assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); - resourceOwner = getOwnerCheckoutResponse.left().value(); - assertTrue(resourceOwner.equals(rfcUser)); - - return resourceAfterChange; - } - - /**************************** - * START CERTIFICATION - ********************************************************************/ - - @Test - @Ignore - public void startCertificationTest() { - - Resource resultResource = createTestResource(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); - - // certification request - Either requestCertificationResult = (Either) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, checkinUser, false); - assertTrue(requestCertificationResult.isLeft()); - - // start certification - Either startCertificationResult = (Either) lifecycleOperation.startComponentCertification(NodeTypeEnum.Resource, resultResource, testerUser, rfcUser, false); - - assertEquals(true, startCertificationResult.isLeft()); - Resource actualResource = startCertificationResult.left().value(); - - // get resource owner - Either getOwnerResponse = lifecycleOperation.getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - assertEquals(testerUser.getUserId(), resourceOwner.getUserId()); - - assertTrue(actualResource.isHighestVersion()); - assertEquals(checkinUser.getUserId(), actualResource.getCreatorUserId()); - assertEquals(testerUser.getUserId(), actualResource.getLastUpdaterUserId()); - assertEquals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, actualResource.getLifecycleState()); - - // assert relations - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId()); - Map props = new HashMap(); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - } - - /** SERVICE */ - @Test - @Ignore - public void startServiceCertificationTest() { - - Service resultResource = createTestService(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); - - // certification request - Either requestCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultResource, rfcUser, checkinUser, false); - assertTrue(requestCertificationResult.isLeft()); - - // start certification - Either startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultResource, testerUser, rfcUser, false); - - assertEquals(true, startCertificationResult.isLeft()); - Service actualResource = (Service) startCertificationResult.left().value(); - - // get resource owner - Either getOwnerResponse = lifecycleOperation.getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Service, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - assertEquals(testerUser.getUserId(), resourceOwner.getUserId()); - - assertTrue(actualResource.isHighestVersion()); - assertEquals(checkinUser.getUserId(), actualResource.getCreatorUserId()); - assertEquals(testerUser.getUserId(), actualResource.getLastUpdaterUserId()); - assertEquals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, actualResource.getLifecycleState()); - - // assert relations - ServiceMetadataDataDefinition metadata = new ServiceMetadataDataDefinition(); - metadata.setUniqueId(actualResource.getUniqueId()); - ServiceMetadataData serviceData = new ServiceMetadataData(metadata); - Map props = new HashMap(); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - } - - /**************************** - * FAIL CERTIFICATION - ********************************************************************/ - - @Test - @Ignore - public void failCertificationTest() { - - Resource actualResource = certificationStatusChange(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkinUser); - - // assert relations - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId()); - Map props = new HashMap(); - - // old edges removed - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isRight()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isRight()); - - // new state is checkin - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - } - - /*** SERVICE **/ - - @Test - @Ignore - public void failCertificationServiceTest() { - - Service actualService = certificationStatusChangeService(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkinUser); - - // assert relations - ServiceMetadataData resourceData = new ServiceMetadataData((ServiceMetadataDataDefinition) actualService.getComponentMetadataDefinition().getMetadataDataDefinition()); - Map props = new HashMap(); - - // old edges removed - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isRight()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isRight()); - - // new state is checkin - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - } - - /**************************** - * CANCEL CERTIFICATION - ********************************************************************/ - - @Test - @Ignore - public void cancelCertificationTest() { - - Resource actualResource = certificationStatusChange(LifecycleStateEnum.READY_FOR_CERTIFICATION, rfcUser); - - // assert relations - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId()); - Map props = new HashMap(); - - // old edges removed - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isRight()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - // new state is rfc - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - } - - /** SERVICE **/ - @Test - @Ignore - public void cancelCertificationServiceTest() { - - Service actualService = certificationStatusChangeService(LifecycleStateEnum.READY_FOR_CERTIFICATION, rfcUser); - - // assert relations - ServiceMetadataData ServiceNode = new ServiceMetadataData(); - ServiceNode.getMetadataDataDefinition().setUniqueId(actualService.getUniqueId()); - Map props = new HashMap(); - - // old edges removed - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(ServiceNode, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isRight()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(ServiceNode, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - // new state is rfc - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(ServiceNode, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - } - - /**************************** CERTIFY ********************************************************************/ - - @Test - @Ignore - public void certifyTest() { - - Resource resultResource = createTestResource(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); - - // certification request - Either requestCertificationResult = (Either) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, checkinUser, false); - assertTrue(requestCertificationResult.isLeft()); - - // start certification - Either startCertificationResult = (Either) lifecycleOperation.startComponentCertification(NodeTypeEnum.Resource, resultResource, testerUser, rfcUser, false); - assertEquals(true, startCertificationResult.isLeft()); - Resource actualResource = startCertificationResult.left().value(); - - // cancel certification - Either CertificationResult = lifecycleOperation.certifyComponent(NodeTypeEnum.Resource, actualResource, testerUser, testerUser, false); - - assertEquals(true, CertificationResult.isLeft()); - actualResource = (Resource) CertificationResult.left().value(); - - // get resource owner - Either getOwnerResponse = lifecycleOperation.getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - assertEquals(testerUser.getUserId(), resourceOwner.getUserId()); - - assertTrue(actualResource.isHighestVersion()); - assertEquals(checkinUser.getUserId(), actualResource.getCreatorUserId()); - assertEquals(testerUser.getUserId(), actualResource.getLastUpdaterUserId()); - assertEquals(LifecycleStateEnum.CERTIFIED, actualResource.getLifecycleState()); - - // assert relations - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId()); - Map props = new HashMap(); - - // old edges removed - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isRight()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isRight()); - - // new state is certified - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - } - - /******** SERVICE **/ - - @Test - @Ignore - public void certifyServiceTest() { - - Service resultService = createTestService(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); - - // certification request - Either requestCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService, rfcUser, checkinUser, false); - assertTrue(requestCertificationResult.isLeft()); - - // start certification - Either startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService, testerUser, rfcUser, false); - assertEquals(true, startCertificationResult.isLeft()); - Service actualService = (Service) startCertificationResult.left().value(); - - // cancel certification - Either CertificationResult = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, actualService, testerUser, testerUser, false); - - assertEquals(true, CertificationResult.isLeft()); - actualService = (Service) CertificationResult.left().value(); - - // get resource owner - Either getOwnerResponse = lifecycleOperation.getComponentOwner(actualService.getUniqueId(), NodeTypeEnum.Service, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - assertEquals(testerUser.getUserId(), resourceOwner.getUserId()); - - assertTrue(actualService.isHighestVersion()); - assertEquals(checkinUser.getUserId(), actualService.getCreatorUserId()); - assertEquals(testerUser.getUserId(), actualService.getLastUpdaterUserId()); - assertEquals(LifecycleStateEnum.CERTIFIED, actualService.getLifecycleState()); - - // assert relations - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(actualService.getUniqueId()); - Map props = new HashMap(); - - // old edges removed - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isRight()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isRight()); - - // new state is certified - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props); - assertTrue(incomingRelationByCriteria.isLeft()); - assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); - - } - - @Test - @Ignore - public void testDeleteOldVersionsResource() { - // simulate - createTestResource(checkinUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null); - Resource resourceNewVersion = createTestResource(checkinUser.getUserId(), "1.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); - createTestResource(checkinUser.getUserId(), "1.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, resourceNewVersion.getUUID()); - createTestResource(checkinUser.getUserId(), "1.3", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, resourceNewVersion.getUUID()); - Resource certifiedResource = createTestResource(checkinUser.getUserId(), "2.0", LifecycleStateEnum.CERTIFIED, resourceNewVersion.getUUID()); - - Either deleteOldComponentVersions = lifecycleOperation.deleteOldComponentVersions(NodeTypeEnum.Resource, certifiedResource.getName(), certifiedResource.getUUID(), false); - - assertTrue(deleteOldComponentVersions.isLeft()); - - String resourceName = certifiedResource.getName(); - Either, StorageOperationStatus> resource = resourceOperation.getResourceByNameAndVersion(resourceName, "1.0", false); - assertTrue(resource.isLeft()); - - resource = resourceOperation.getResourceByNameAndVersion(resourceName, "2.0", false); - assertTrue(resource.isLeft()); - - resource = resourceOperation.getResourceByNameAndVersion(resourceName, "1.1", false); - assertTrue(resource.isLeft()); - assertTrue(resource.left().value().size() == 1); - Resource deleted = resource.left().value().get(0); - assertTrue(deleted.getIsDeleted()); - // assertEquals(StorageOperationStatus.NOT_FOUND, - // resource.right().value()); - - resource = resourceOperation.getResourceByNameAndVersion(resourceName, "1.2", false); - // assertTrue(resource.isRight()); - // assertEquals(StorageOperationStatus.NOT_FOUND, - // resource.right().value()); - assertTrue(resource.isLeft()); - assertTrue(resource.left().value().size() == 1); - deleted = resource.left().value().get(0); - assertTrue(deleted.getIsDeleted()); - - resource = resourceOperation.getResourceByNameAndVersion(resourceName, "1.3", false); - // assertTrue(resource.isRight()); - // assertEquals(StorageOperationStatus.NOT_FOUND, - // resource.right().value()); - assertTrue(resource.isLeft()); - assertTrue(resource.left().value().size() == 1); - deleted = resource.left().value().get(0); - assertTrue(deleted.getIsDeleted()); - } - - // @Test - // public void testDeleteOldVersionsResourceWithArtifacts(){ - // // simulate - // Resource resource = createFullTestResource(checkinUser.getUserId(), - // "1.0", LifecycleStateEnum.CERTIFIED); - // - // // checkout - // Either checkoutResource = - // lifecycleOperation.checkoutResource(resource, checkinUser, checkinUser, - // false); - // assertTrue(checkoutResource.isLeft()); - // Either getResource = - // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(), - // "1.1", false); - // assertTrue(getResource.isLeft()); - // - // // rfc - // resource = getResource.left().value(); - // Either requestCertification = - // lifecycleOperation.requestCertification(resource, rfcUser, checkinUser, - // false); - // assertTrue(requestCertification.isLeft()); - // getResource = - // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(), - // "1.1", false); - // assertTrue(getResource.isLeft()); - // - // // start cert - // resource = getResource.left().value(); - // Either startCertification = - // lifecycleOperation.startCertificationResource(resource, testerUser, - // rfcUser, false); - // assertTrue(startCertification.isLeft()); - // getResource = - // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(), - // "1.1", false); - // assertTrue(getResource.isLeft()); - // - // // certify - // resource = getResource.left().value(); - // Either certify = - // lifecycleOperation.certifyResource(resource, testerUser, testerUser, - // false); - // assertTrue(certify.isLeft()); - // getResource = - // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(), - // "1.1", false); - // assertTrue(getResource.isLeft()); - // resource = getResource.left().value(); - // - // - // Either, StorageOperationStatus> - // deleteOldComponentVersions = lifecycleOperation - // .deleteOldComponentVersions(NodeTypeEnum.Resource, - // resource.getResourceName(), resource.getUUID(), false); - // - // assertTrue(deleteOldComponentVersions.isLeft()); - // assertEquals(2, deleteOldComponentVersions.left().value().size()); - // - // String resourceName = resource.getResourceName(); - // getResource = resourceOperation.getResourceByNameAndVersion(resourceName, - // "1.0", false); - // assertTrue(getResource.isLeft()); - // - // getResource = resourceOperation.getResourceByNameAndVersion(resourceName, - // "2.0", false); - // assertTrue(getResource.isLeft()); - // - // getResource = resourceOperation.getResourceByNameAndVersion(resourceName, - // "1.1", false); - // assertTrue(getResource.isRight()); - // assertEquals(StorageOperationStatus.NOT_FOUND, - // getResource.right().value()); - // - // } - - // @Test - // public void testDeleteOldVersionsResourceWithArtifactsDerived(){ - // // simulate - // Resource resourceRoot = createFullTestResource(checkinUser.getUserId(), - // "1.0", LifecycleStateEnum.CERTIFIED); - // Resource resource = buildResourceMetadata(checkinUser.getUserId(), - // CATEGORY_NAME); - // resource.setResourceName("myDerivedResource"); - // resource.setResourceVersion("0.1"); - // resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - // List derived = new ArrayList<>(); - // derived.add(resourceRoot.getResourceName()); - // resource.setDerivedFrom(derived); - // - // Either result = - // resourceOperation.createResource(resource); - // assertEquals("check resource created", true, result.isLeft()); - // resource = result.left().value(); - // - // // resource inherits the artifacts from parent - // assertNotNull(resource.getInterfaces().get(INTERFACE_NAME).getOperations().get(INTERFACE_OPERATION_CREATE).getImplementation()); - // - // // rfc - // Either requestCertification = - // lifecycleOperation.requestCertification(resource, rfcUser, checkinUser, - // false); - // assertTrue(requestCertification.isLeft()); - // Either getResource = - // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(), - // "0.1", false); - // assertTrue(getResource.isLeft()); - // - // // start cert - // resource = getResource.left().value(); - // Either startCertification = - // lifecycleOperation.startCertificationResource(resource, testerUser, - // rfcUser, false); - // assertTrue(startCertification.isLeft()); - // getResource = - // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(), - // "0.1", false); - // assertTrue(getResource.isLeft()); - // - // // certify - // resource = getResource.left().value(); - // Either certify = - // lifecycleOperation.certifyResource(resource, testerUser, testerUser, - // false); - // assertTrue(certify.isLeft()); - // getResource = - // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(), - // "0.1", false); - // assertTrue(getResource.isLeft()); - // resource = getResource.left().value(); - // - // - // Either, StorageOperationStatus> - // deleteOldComponentVersions = lifecycleOperation - // .deleteOldComponentVersions(NodeTypeEnum.Resource, - // resource.getResourceName(), resource.getUUID(), false); - // - // assertTrue(deleteOldComponentVersions.isLeft()); - // - // // resource artifacts are not really the resource's, they are the - // parent's artifacts - // assertTrue(deleteOldComponentVersions.left().value().isEmpty()); - // - // String resourceName = resource.getResourceName(); - // getResource = resourceOperation.getResourceByNameAndVersion(resourceName, - // "1.0", false); - // assertTrue(getResource.isLeft()); - // - // getResource = resourceOperation.getResourceByNameAndVersion(resourceName, - // "0.1", false); - // assertTrue(getResource.isRight()); - // assertEquals(StorageOperationStatus.NOT_FOUND, - // getResource.right().value()); - // - // } - - @Test - @Ignore - public void testDeleteOldVersionsService() { - // simulate - createTestService(checkinUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null); - Service serviceNewUUid = createTestService(checkinUser.getUserId(), "1.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); - createTestService(checkinUser.getUserId(), "1.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, serviceNewUUid.getUUID()); - createTestService(checkinUser.getUserId(), "1.3", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, serviceNewUUid.getUUID()); - Service certifiedService = createTestService(checkinUser.getUserId(), "2.0", LifecycleStateEnum.CERTIFIED, serviceNewUUid.getUUID()); - - Either deleteOldComponentVersions = lifecycleOperation.deleteOldComponentVersions(NodeTypeEnum.Service, certifiedService.getName(), certifiedService.getUUID(), false); - - assertTrue(deleteOldComponentVersions.isLeft()); - - String resourceName = certifiedService.getName(); - Either service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.0", null, false); - assertTrue(service.isLeft()); - - service = serviceOperation.getServiceByNameAndVersion(resourceName, "2.0", null, false); - assertTrue(service.isLeft()); - - service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.1", null, false); - /* - * assertTrue(resource.isRight()); assertEquals(StorageOperationStatus.NOT_FOUND, resource.right().value()); - */ - assertTrue(service.isLeft()); - assertTrue(service.left().value().getIsDeleted()); - - service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.2", null, false); - - service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.3", null, false); - /* - * assertTrue(service.isRight()); assertEquals(StorageOperationStatus.NOT_FOUND, service.right().value()); - */ - assertTrue(service.isLeft()); - assertTrue(service.left().value().getIsDeleted()); - - service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.3", null, false); - /* - * assertTrue(service.isRight()); assertEquals(StorageOperationStatus.NOT_FOUND, service.right().value()); - */ - assertTrue(service.isLeft()); - assertTrue(service.left().value().getIsDeleted()); - - } - - private Resource certificationStatusChange(LifecycleStateEnum nextState, User expectedOwner) { - Resource resultResource = createTestResource(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); - - // certification request - Either requestCertificationResult = (Either) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, checkinUser, false); - assertTrue(requestCertificationResult.isLeft()); - - // start certification - Either startCertificationResult = (Either) lifecycleOperation.startComponentCertification(NodeTypeEnum.Resource, resultResource, testerUser, rfcUser, false); - assertEquals(true, startCertificationResult.isLeft()); - Resource actualResource = startCertificationResult.left().value(); - - // cancel certification - Either failCertificationResult = (Either) lifecycleOperation.cancelOrFailCertification(NodeTypeEnum.Resource, actualResource, testerUser, testerUser, nextState, false); - - assertEquals(true, failCertificationResult.isLeft()); - actualResource = failCertificationResult.left().value(); - - // get resource owner - Either getOwnerResponse = lifecycleOperation.getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - assertEquals(expectedOwner, resourceOwner); - - assertTrue(actualResource.isHighestVersion()); - assertEquals(checkinUser.getUserId(), actualResource.getCreatorUserId()); - assertEquals(testerUser.getUserId(), actualResource.getLastUpdaterUserId()); - assertEquals(nextState, actualResource.getLifecycleState()); - return actualResource; - } - - private Service certificationStatusChangeService(LifecycleStateEnum nextState, User expectedOwner) { - Service resultService = createTestService(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); - - // certification request - Either requestCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService, rfcUser, checkinUser, false); - assertTrue(requestCertificationResult.isLeft()); - - // start certification - Either startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService, testerUser, rfcUser, false); - assertEquals(true, startCertificationResult.isLeft()); - Service actualService = (Service) startCertificationResult.left().value(); - - // cancel certification - Either failCertificationResult = lifecycleOperation.cancelOrFailCertification(NodeTypeEnum.Service, actualService, testerUser, testerUser, nextState, false); - - assertEquals(true, failCertificationResult.isLeft()); - actualService = (Service) failCertificationResult.left().value(); - - // get resource owner - Either getOwnerResponse = lifecycleOperation.getComponentOwner(actualService.getUniqueId(), NodeTypeEnum.Resource, false); - - assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); - User resourceOwner = getOwnerResponse.left().value(); - assertEquals(expectedOwner, resourceOwner); - - assertTrue(actualService.isHighestVersion()); - assertEquals(checkinUser.getUserId(), actualService.getCreatorUserId()); - assertEquals(testerUser.getUserId(), actualService.getLastUpdaterUserId()); - assertEquals(nextState, actualService.getLifecycleState()); - return actualService; - } - - private Resource createTestResource(String userId, String version, LifecycleStateEnum state, String uuid) { - // create resource in graph - - Resource resource2 = buildResourceMetadata(userId, CATEGORY_NAME); - resource2.setVersion(version); - ; - resource2.setLifecycleState(state); - resource2.setUUID(uuid); - - Either result = resourceOperation.createResource(resource2); - assertEquals("check resource created", true, result.isLeft()); - Resource resultResource = result.left().value(); - return resultResource; - } - - private Service createTestService(String userId, String version, LifecycleStateEnum state, String uuid) { - // create resource in graph - - Service service = new Service(); - service.setName(SERVICE_NAME); - service.setVersion(version); - service.setDescription("description 1"); - service.setCreatorUserId(userId); - service.setContactId("contactId@sdc.com"); - CategoryDefinition category = new CategoryDefinition(); - category.setName(CATEGORY_NAME); - - List categories = new ArrayList<>(); - categories.add(category); - service.setCategories(categories); - service.setIcon("images/my.png"); - List tags = new ArrayList(); - tags.add("TAG1"); - tags.add("TAG2"); - service.setTags(tags); - service.setUUID(uuid); - - service.setLifecycleState(state); - - Either result = serviceOperation.createService(service); - assertEquals("check service created", true, result.isLeft()); - Service resultResource = result.left().value(); - return resultResource; - } - - private Resource createFullTestResource(String userId, String version, LifecycleStateEnum state) { - Resource resource2 = buildResourceMetadata(userId, CATEGORY_NAME); - resource2.setVersion(version); - ; - resource2.setLifecycleState(state); - - InterfaceDefinition inter = new InterfaceDefinition(INTERFACE_NAME, "interface description", null); - // inter.setUniqueId(UniqueIdBuilder.buildResourceUniqueId(resource2.getResourceName(), - // resource2.getResourceVersion())+"."+INTERFACE_NAME); - - Operation operation = new Operation(); - operation.setDescription("op description"); - operation.setUniqueId(inter.getUniqueId() + "." + INTERFACE_OPERATION_CREATE); - - ArtifactDataDefinition artifactDataDef = new ArtifactDataDefinition(); - artifactDataDef.setArtifactChecksum("YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI="); - artifactDataDef.setArtifactName("create_myRoot.sh"); - artifactDataDef.setArtifactLabel("create_myRoot"); - artifactDataDef.setArtifactType("SHELL"); - artifactDataDef.setDescription("good description"); - artifactDataDef.setEsId("esId"); - artifactDataDef.setUniqueId(operation.getUniqueId() + "." + artifactDataDef.getArtifactLabel()); - ArtifactDefinition artifactDef = new ArtifactDefinition(artifactDataDef, "UEsDBAoAAAAIAAeLb0bDQz"); - - operation.setImplementation(artifactDef); - operation.setCreationDate(System.currentTimeMillis()); - Map ops = new HashMap<>(); - ops.put(INTERFACE_OPERATION_CREATE, operation); - inter.setOperationsMap(ops); - - Map interfaces = new HashMap<>(); - interfaces.put(INTERFACE_NAME, inter); - - resource2.setInterfaces(interfaces); - - String capabilityTypeName = CAPABILITY_HOSTED_ON; - createCapabilityOnGraph(capabilityTypeName); - - // create capability definition - CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); - capabilityDefinition.setDescription("my capability"); - capabilityDefinition.setType(capabilityTypeName); - capabilityDefinition.setName(CAPABILITY_NAME); - Map> capabilities = new HashMap<>(); - List validSourceTypes = new ArrayList(); - validSourceTypes.add("tosca.nodes.SC"); - capabilityDefinition.setValidSourceTypes(validSourceTypes); - List caplist = new ArrayList(); - caplist.add(capabilityDefinition); - capabilities.put(capabilityTypeName, caplist); - resource2.setCapabilities(capabilities); - - // add requirement definition - RequirementDefinition reqDefinition = new RequirementDefinition(); - // reqDefinition.setNode(reqNodeName); - // reqDefinition.setRelationship(reqRelationship); - - reqDefinition.setCapability(capabilityTypeName); - reqDefinition.setName(REQUIREMENT_NAME); - Map> requirements = new HashMap<>(); - List reqlist = new ArrayList(); - reqlist.add(reqDefinition); - requirements.put(capabilityTypeName, reqlist); - resource2.setRequirements(requirements); - - Either result = resourceOperation.createResource(resource2); - assertEquals("check resource created", true, result.isLeft()); - Resource resultResource = result.left().value(); - - // add artifacts to resource - // ArtifactDataDefinition artifactDataDef = new - // ArtifactDataDefinition(); - artifactDataDef.setArtifactChecksum("YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI="); - artifactDataDef.setArtifactName("create_myRoot.sh"); - artifactDataDef.setArtifactLabel("create_myRoot"); - artifactDataDef.setArtifactType("SHELL"); - artifactDataDef.setDescription("good description"); - artifactDataDef.setEsId("esId"); - artifactDataDef.setUniqueId(resultResource.getUniqueId() + "." + artifactDataDef.getArtifactLabel()); - artifactDef = new ArtifactDefinition(artifactDataDef, "UEsDBAoAAAAIAAeLb0bDQz"); - // artifacts.put("myArtifact", artifactDef); - // resource2.setArtifacts(artifacts); - - Either addArifactToResource = artifactOperation.addArifactToComponent(artifactDef, resultResource.getUniqueId(), NodeTypeEnum.Resource, false, true); - assertTrue(addArifactToResource.isLeft()); - - Either resource = resourceOperation.getResource(resultResource.getUniqueId()); - assertTrue(resource.isLeft()); - - Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); - String json = prettyGson.toJson(resource.left().value()); - log.debug(json); - return resource.left().value(); - } - - private void createCapabilityOnGraph(String capabilityTypeName) { - - CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); - capabilityTypeDefinition.setDescription("desc1"); - capabilityTypeDefinition.setType(capabilityTypeName); - Map properties = new HashMap(); - String propName1 = "disk_size"; - PropertyDefinition property1 = buildProperty1(); - properties.put(propName1, property1); - capabilityTypeDefinition.setProperties(properties); - - Either addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition); - assertTrue(addCapabilityType1.isLeft()); - } - - private User convertUserDataToUser(UserData modifierData) { - User modifier = new User(); - modifier.setUserId(modifierData.getUserId()); - modifier.setEmail(modifierData.getEmail()); - modifier.setFirstName(modifierData.getFirstName()); - modifier.setLastName(modifierData.getLastName()); - modifier.setRole(modifierData.getRole()); - return modifier; - } - - private Resource buildResourceMetadata(String userId, String category) { - // deleteAndCreateCategory(category); - - Resource resource = new Resource(); - resource.setName("my-resource"); - resource.setVersion("1.0"); - ; - resource.setDescription("description 1"); - resource.setAbstract(false); - resource.setCreatorUserId(userId); - resource.setContactId("contactId@sdc.com"); - resource.setVendorName("vendor 1"); - resource.setVendorRelease("1.0.0"); - String[] categoryArr = category.split("/"); - resource.addCategory(categoryArr[0], categoryArr[1]); - resource.setIcon("images/my.png"); - List tags = new ArrayList(); - tags.add("TAG1"); - tags.add("TAG2"); - resource.setTags(tags); - return resource; - } - - public UserData deleteAndCreateUser(String userId, String firstName, String lastName, String role) { - UserData userData = new UserData(); - userData.setUserId(userId); - userData.setFirstName(firstName); - userData.setLastName(lastName); - userData.setRole(role); - - titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); - titanGenericDao.createNode(userData, UserData.class); - titanGenericDao.commit(); - - return userData; - } - - /* - * public void deleteAndCreateCategory(String category) { CategoryData categoryData = new CategoryData(); categoryData.setName(category); - * - * Either node = titanGenericDao.getNode(categoryData.getUniqueIdKey(), categoryData, CategoryData.class); if (node.isRight()){ //titanGenericDao.deleteNode(categoryData, CategoryData.class); - * Either createNode = titanGenericDao .createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode); } - */ - - private PropertyDefinition buildProperty1() { - PropertyDefinition property1 = new PropertyDefinition(); - property1.setDefaultValue("10"); - property1.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node."); - property1.setType(ToscaType.INTEGER.name().toLowerCase()); - List constraints = new ArrayList(); - GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0"); - constraints.add(propertyConstraint1); - - LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10"); - constraints.add(propertyConstraint2); - - property1.setConstraints(constraints); - return property1; - } - - private ArtifactDefinition addArtifactToService(String userId, String serviceId, String artifactName) { - ArtifactDefinition artifactInfo = new ArtifactDefinition(); - - artifactInfo.setArtifactName(artifactName + ".sh"); - artifactInfo.setArtifactType("SHELL"); - artifactInfo.setDescription("hdkfhskdfgh"); - artifactInfo.setPayloadData("UEsDBAoAAAAIAAeLb0bDQz"); - - artifactInfo.setUserIdCreator(userId); - String fullName = "Jim H"; - artifactInfo.setUpdaterFullName(fullName); - long time = System.currentTimeMillis(); - artifactInfo.setCreatorFullName(fullName); - artifactInfo.setCreationDate(time); - artifactInfo.setLastUpdateDate(time); - artifactInfo.setUserIdLastUpdater(userId); - artifactInfo.setArtifactLabel(artifactName); - artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(serviceId, artifactInfo.getArtifactLabel())); - - Either artifact = artifactOperation.addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true); - assertTrue(artifact.isLeft()); - return artifactInfo; - } - -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java deleted file mode 100644 index 62e6adab7f..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java +++ /dev/null @@ -1,218 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Map; -import java.util.Map.Entry; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.CapabiltyInstance; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; -import org.openecomp.sdc.be.resources.data.UserData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import fj.data.Either; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:application-context-test.xml") -public class RequirementOperationTest extends ModelTestBase { - private static Logger log = LoggerFactory.getLogger(RequirementOperationTest.class.getName()); - private Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); - - private static String USER_ID = "muUserId"; - private static String CATEGORY_NAME = "category/mycategory"; - - @javax.annotation.Resource(name = "titan-generic-dao") - private TitanGenericDao titanDao; - - @javax.annotation.Resource(name = "requirement-operation") - private RequirementOperation requirementOperation; - - @javax.annotation.Resource(name = "resource-operation") - private ResourceOperation resourceOperation; - - @javax.annotation.Resource(name = "property-operation") - private PropertyOperation propertyOperation; - - @javax.annotation.Resource(name = "capability-operation") - private CapabilityOperation capabilityOperation; - - @javax.annotation.Resource(name = "capability-type-operation") - private CapabilityTypeOperation capabilityTypeOperation; - - @BeforeClass - public static void setupBeforeClass() { - - // configurationManager = new ConfigurationManager( - // new ConfigurationSource() { - // - // @Override - // public T getAndWatchConfiguration(Class className, - // ConfigurationListener configurationListener) { - // // TODO Auto-generated method stub - // return null; - // } - // - // @Override - // public void addWatchConfiguration(Class className, - // ConfigurationListener configurationListener) { - // // TODO Auto-generated method stub - // - // } - // }); - // - // Configuration configuration = new Configuration(); - // configuration.setTitanInMemoryGraph(true); - // - // configurationManager.setConfiguration(configuration); - ModelTestBase.init(); - } - - @Test - public void testDummy() { - - assertTrue(requirementOperation != null); - - } - - @Test - public void testAddRequirementNotExistCapability() { - - String reqName = "host"; - RequirementDefinition reqDefinition = new RequirementDefinition(); - reqDefinition.setNode("tosca.nodes.Compute"); - reqDefinition.setRelationship("myrelationship"); - reqDefinition.setCapability("mycapability___2"); - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", "0.1", null, true, true); - - Either addRequirementToResource = requirementOperation.addRequirementToResource(reqName, reqDefinition, resource.getUniqueId()); - assertEquals("check error", StorageOperationStatus.INVALID_ID, addRequirementToResource.right().value()); - - } - - @Before - public void createUserAndCategory() { - String[] category = CATEGORY_NAME.split("/"); - OperationTestsUtil.deleteAndCreateResourceCategory(category[0], category[1], titanDao); - deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID); - } - - private UserData deleteAndCreateUser(String userId, String firstName, String lastName) { - UserData userData = new UserData(); - userData.setUserId(userId); - userData.setFirstName(firstName); - userData.setLastName(lastName); - - titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); - titanDao.createNode(userData, UserData.class); - titanDao.commit(); - - return userData; - } - - /* - * private void deleteAndCreateCategory(String category) { CategoryData categoryData = new CategoryData(); categoryData.setName(category); - * - * titanDao.deleteNode(categoryData, CategoryData.class); Either createNode = titanDao .createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode); - * - * } - */ - - @Test - @Ignore - public void testAddRequirementWithCapability() { - - String capabilityTypeName = "tosca.nodes.Container"; - - String reqName = "host"; - RequirementDefinition reqDefinition = new RequirementDefinition(); - reqDefinition.setNode("tosca.nodes.Compute"); - reqDefinition.setRelationship("myrelationship"); - reqDefinition.setCapability(capabilityTypeName); - - CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); - capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); - - capabilityTypeOperationTest.createCapability(capabilityTypeName); - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", "2.0", null, true, true); - - Either addRequirementToResource = requirementOperation.addRequirementToResource(reqName, reqDefinition, resource.getUniqueId()); - - assertEquals("check requirement was added", true, addRequirementToResource.isLeft()); - - Either resource2 = resourceOperation.getResource(resource.getUniqueId()); - String json = prettyGson.toJson(resource2); - log.debug(json); - } - - private void compareProperties(Map capabilityProperties, CapabiltyInstance capabiltyInstance, Map actual) { - - Map properties = capabiltyInstance.getProperties(); - - for (Entry entry : capabilityProperties.entrySet()) { - String paramName = entry.getKey(); - PropertyDefinition propertyDefinition = entry.getValue(); - String defaultValue = propertyDefinition.getDefaultValue(); - - String value = properties.get(paramName); - - String actualValue = null; - if (actual != null) { - actualValue = actual.get(paramName); - } - if (actualValue != null) { - assertEquals("check property value of key " + paramName, value, actualValue); - } else { - assertEquals("check property value of key " + paramName, value, defaultValue); - } - } - - } - -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java deleted file mode 100644 index e631f6ca42..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java +++ /dev/null @@ -1,2250 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -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.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.CapabilityTypeDefinition; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.HeatParameterDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.RelationshipImpl; -import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation; -import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; -import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; -import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation; -import org.openecomp.sdc.be.model.operations.impl.HeatParametersOperation; -import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; -import org.openecomp.sdc.be.model.operations.impl.RequirementOperation; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; -import org.openecomp.sdc.be.model.operations.impl.util.PrintGraph; -import org.openecomp.sdc.be.resources.data.ArtifactData; -import org.openecomp.sdc.be.resources.data.HeatParameterData; -import org.openecomp.sdc.be.resources.data.HeatParameterValueData; -import org.openecomp.sdc.be.resources.data.RelationshipInstData; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import org.openecomp.sdc.be.resources.data.ServiceMetadataData; -import org.openecomp.sdc.be.resources.data.UniqueIdData; -import org.openecomp.sdc.be.resources.data.UserData; -import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import fj.data.Either; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:application-context-test.xml") -public class ResourceInstanceOperationTest extends ModelTestBase { - private static Logger log = LoggerFactory.getLogger(ResourceInstanceOperationTest.class.getName()); - private Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); - - private static String USER_ID = "muUserId"; - private static String CATEGORY_NAME = "category/mycategory"; - - @javax.annotation.Resource(name = "titan-generic-dao") - private TitanGenericDao titanDao; - - @javax.annotation.Resource(name = "requirement-operation") - private RequirementOperation requirementOperation; - - @javax.annotation.Resource(name = "resource-operation") - private ResourceOperation resourceOperation; - - @javax.annotation.Resource(name = "property-operation") - private PropertyOperation propertyOperation; - - @javax.annotation.Resource(name = "capability-operation") - private CapabilityOperation capabilityOperation; - - @javax.annotation.Resource(name = "capability-type-operation") - private CapabilityTypeOperation capabilityTypeOperation; - - @javax.annotation.Resource(name = "component-instance-operation") - private ComponentInstanceOperation resourceInstanceOperation; - - @javax.annotation.Resource - private HeatParametersOperation heatParameterOperation; - - @javax.annotation.Resource - private ArtifactOperation artifactOperation; - - private String CAPABILITY_1 = "mycapability101"; - private String CAPABILITY_2 = "mycapability102"; - - private Integer TEST_CLASS_NUMBER = 1; - - public final static Pattern COMPONENT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_]+"); - - public final static Pattern COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_]+"); - - @BeforeClass - public static void setupBeforeClass() { - - // configurationManager = new ConfigurationManager( - // new ConfigurationSource() { - // - // @Override - // public T getAndWatchConfiguration(Class className, - // ConfigurationListener configurationListener) { - // // TODO Auto-generated method stub - // return null; - // } - // - // @Override - // public void addWatchConfiguration(Class className, - // ConfigurationListener configurationListener) { - // // TODO Auto-generated method stub - // - // } - // }); - // - // Configuration configuration = new Configuration(); - // - // ////inmemory - // boolean useInMemory = true; - // if (useInMemory) { - // configuration.setTitanInMemoryGraph(true); - // } else { - // configuration.setTitanInMemoryGraph(false); - // configuration.setTitanCfgFile("C:\\Git_work\\D2-SDnC\\catalog-be\\src\\main\\resources\\config\\titan.properties"); - // } - // - // - // - // configurationManager.setConfiguration(configuration); - ModelTestBase.init(); - } - - public void setOperations(TitanGenericDao titanDao, CapabilityTypeOperation capabilityTypeOperation, RequirementOperation requirementOperation, CapabilityOperation capabilityOperation, ResourceOperation resourceOperation, - PropertyOperation propertyOperation, ComponentInstanceOperation resourceInstanceOperation2) { - this.titanDao = titanDao; - this.capabilityTypeOperation = capabilityTypeOperation; - this.capabilityOperation = capabilityOperation; - this.requirementOperation = requirementOperation; - this.resourceOperation = resourceOperation; - this.propertyOperation = propertyOperation; - this.resourceInstanceOperation = resourceInstanceOperation2; - } - - @Test - public void testDummy() { - - assertTrue(requirementOperation != null); - - } - - @Test - public void testAddResourceInstanceInvalidServiceId() { - - try { - ComponentInstance instance = buildResourceInstance("tosca.nodes.Apache.2.0", "1", "tosca.nodes.Apache"); - - Either status = resourceInstanceOperation.addComponentInstanceToContainerComponent("service1", NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false); - assertEquals("check failed status - service is not in graph", true, status.isRight()); - assertEquals("check failed status value - service is not in graph", TitanOperationStatus.INVALID_ID, status.right().value()); - } finally { - titanDao.rollback(); - } - - } - - @Test - public void testAddResourceInstanceValidServiceIdInvalidResourceId() { - try { - - ServiceMetadataData serviceData1 = createService("myservice1.1.0"); - - ComponentInstance instance = buildResourceInstance("tosca.nodes.Apache.2.0", "1", "tosca.nodes.Apache"); - - Either status = resourceInstanceOperation.addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false); - - assertEquals("check failed status - service is not in graph", true, status.isRight()); - assertEquals("check failed status value - service is not in graph", TitanOperationStatus.INVALID_ID, status.right().value()); - - } finally { - titanDao.rollback(); - } - - } - - @Test - public void testAddResourceInstanceValidServiceId() { - try { - String serviceName = "myservice1.1.0"; - String resourceName = "tosca.nodes.Apache.2.0"; - ServiceMetadataData serviceData1 = createService(serviceName); - ResourceMetadataData resourceData = createResource(resourceName); - - ComponentInstance instance = buildResourceInstance(resourceData.getMetadataDataDefinition().getUniqueId(), "1", "tosca.nodes.Apache"); - - Either status = resourceInstanceOperation.addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false); - - assertEquals("check success status - service is not in graph", true, status.isLeft()); - - ComponentInstance value = status.left().value(); - assertEquals("check name exists", "tosca.nodes.Apache 1", value.getName()); - - ServiceMetadataData serviceData2 = deleteService(serviceName); - ResourceMetadataData resourceData2 = deleteResource(resourceName); - - } finally { - titanDao.rollback(); - } - } - - @Test - public void testUpdateResourceInstance() { - try { - String serviceName = "myservice1.1.0"; - String resourceName = "tosca.nodes.Apache.2.0"; - ServiceMetadataData serviceData1 = createService(serviceName); - ResourceMetadataData resourceData = createResource(resourceName); - - ComponentInstance instance = buildResourceInstance(resourceData.getMetadataDataDefinition().getUniqueId(), "1", "tosca.nodes.Apache"); - - Either status = resourceInstanceOperation.addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false); - - ComponentInstance resourceInstance = status.left().value(); - Long creationTime = resourceInstance.getCreationTime(); - String name = resourceInstance.getName(); - assertEquals("check success status - service is not in graph", true, status.isLeft()); - - ComponentInstance value = status.left().value(); - assertEquals("check name exists", "tosca.nodes.Apache 1", value.getName()); - - Either u1Res = resourceInstanceOperation.updateResourceInstance((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, resourceInstance.getUniqueId(), value, true); - assertTrue("check update succeed", u1Res.isLeft()); - - Long lastModificationTimeNC = value.getModificationTime(); - String desc = "AAAAA"; - String posX = "15"; - String posY = "12"; - String updatedName = "Shlokshlik"; - value.setDescription(desc); - value.setPosX(posX); - Either u2Res = resourceInstanceOperation.updateResourceInstance((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, resourceInstance.getUniqueId(), value, true); - assertTrue("check update succeed", u2Res.isLeft()); - assertEquals("check resource instance updated", desc, u2Res.left().value().getDescription()); - assertEquals("check resource instance updated", posX, u2Res.left().value().getPosX()); - assertEquals("check resource instance updated", resourceInstance.getPosY(), u2Res.left().value().getPosY()); - assertEquals("check modification time was not updated since it was supplied", u2Res.left().value().getModificationTime(), lastModificationTimeNC); - - Long lastModificationTime = value.getModificationTime(); - value.setPosY(posY); - value.setModificationTime(null); - value.setName(updatedName); - Either u3Res = resourceInstanceOperation.updateResourceInstance((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, resourceInstance.getUniqueId(), value, true); - assertTrue("check update succeed", u3Res.isLeft()); - assertEquals("check resource instance updated", desc, u3Res.left().value().getDescription()); - assertEquals("check resource pos x updated", posX, u3Res.left().value().getPosX()); - assertEquals("check resource pos y updated", posY, u3Res.left().value().getPosY()); - assertTrue("check modification time was updated", u3Res.left().value().getModificationTime() >= lastModificationTime); - assertEquals("check creation time was not updated", creationTime, u3Res.left().value().getCreationTime()); - assertEquals("check name was updated", updatedName, u3Res.left().value().getName()); - - ServiceMetadataData serviceData2 = deleteService(serviceName); - ResourceMetadataData resourceData2 = deleteResource(resourceName); - - } finally { - titanDao.rollback(); - } - } - - @Test - public void testRemoveResourceInstance() { - try { - String serviceName = "myservice1.1.0"; - String resourceName = "tosca.nodes.Apache.2.0"; - ServiceMetadataData serviceData1 = createService(serviceName); - ResourceMetadataData resourceData = createResource(resourceName); - - ComponentInstance instance = buildResourceInstance(resourceData.getMetadataDataDefinition().getUniqueId(), "1", "tosca.nodes.Apache"); - - Either status = resourceInstanceOperation.addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false); - - assertEquals("check success status - service is not in graph", true, status.isLeft()); - - ComponentInstance value = status.left().value(); - assertEquals("check name exists", "tosca.nodes.Apache 1", value.getName()); - - Either status1 = resourceInstanceOperation.removeComponentInstanceFromComponent(NodeTypeEnum.Service, serviceName, value.getUniqueId()); - - assertTrue("check resource service was deleted.", status1.isLeft()); - assertEquals("check resource instance returned.", "tosca.nodes.Apache 1", status1.left().value().getName()); - - ServiceMetadataData serviceData2 = deleteService(serviceName); - ResourceMetadataData resourceData2 = deleteResource(resourceName); - - } finally { - titanDao.rollback(); - } - } - - @Test - public void testRemoveResourceInstanceNotFound() { - try { - String serviceName = "myservice1.1.0"; - ServiceMetadataData serviceData1 = createService(serviceName); - - Either status1 = resourceInstanceOperation.removeComponentInstanceFromComponent(NodeTypeEnum.Service, serviceName, "stam"); - - assertTrue("check resource service was not deleted.", status1.isRight()); - assertEquals("check NOT_FOUND returned.", TitanOperationStatus.NOT_FOUND, status1.right().value()); - - ServiceMetadataData serviceData2 = deleteService(serviceName); - - } finally { - titanDao.rollback(); - } - } - - public ServiceMetadataData createService(String serviceName) { - - ServiceMetadataData serviceData1 = new ServiceMetadataData(); - serviceData1.getMetadataDataDefinition().setUniqueId(serviceName); - Either createNode = titanDao.createNode(serviceData1, ServiceMetadataData.class); - - assertTrue("check service created", createNode.isLeft()); - return createNode.left().value(); - } - - public ServiceMetadataData deleteService(String serviceName) { - - ServiceMetadataData serviceData1 = new ServiceMetadataData(); - serviceData1.getMetadataDataDefinition().setUniqueId(serviceName); - Either createNode = titanDao.deleteNode(serviceData1, ServiceMetadataData.class); - assertTrue("check service deleted", createNode.isLeft()); - return createNode.left().value(); - } - - public ResourceMetadataData createResource(String resourceName) { - - ResourceMetadataData serviceData1 = new ResourceMetadataData(); - serviceData1.getMetadataDataDefinition().setUniqueId(resourceName); - Either createNode = titanDao.createNode(serviceData1, ResourceMetadataData.class); - - assertTrue("check service created", createNode.isLeft()); - return createNode.left().value(); - } - - public ResourceMetadataData deleteResource(String resourceName) { - - ResourceMetadataData serviceData1 = new ResourceMetadataData(); - serviceData1.getMetadataDataDefinition().setUniqueId(resourceName); - Either createNode = titanDao.deleteNode(serviceData1, ResourceMetadataData.class); - - assertTrue("check service created", createNode.isLeft()); - return createNode.left().value(); - } - - @Test - public void testAddResourceInstanceJson() { - addResourceInstanceJson(); - } - - public ComponentInstance addResourceInstanceJson() { - - ComponentInstance resourceInstance = buildResourceInstance("tosca.nodes.Apache.2.0", "1", "tosca.nodes.Apache"); - - String json = prettyGson.toJson(resourceInstance); - log.debug(json); - - return resourceInstance; - - } - - private ComponentInstance buildResourceInstance(String respurceUid, String instanceNumber, String name) { - ComponentInstance resourceInstance = new ComponentInstance(); - // resourceInstance - // .setUniqueId(".tosca.nodes.Apache.2.0." + instanceNumber); - resourceInstance.setName(name); - resourceInstance.setDescription("desc1"); - resourceInstance.setPosX("20"); - resourceInstance.setPosY("40"); - resourceInstance.setComponentUid(respurceUid); - resourceInstance.setCreationTime(System.currentTimeMillis()); - resourceInstance.setModificationTime(System.currentTimeMillis()); - resourceInstance.setNormalizedName(normaliseComponentInstanceName(name)); - - // Map requirements = new HashMap(); - // - // RequirementInstance requirementInstance1 = new RequirementInstance(); - // requirementInstance1.setNode("NA"); - // RelationshipImpl relationshipImpl = new RelationshipImpl(); - // relationshipImpl.setType("tosca.relationships.HostedOn"); - // requirementInstance1.setRelationship(relationshipImpl); - // - // requirements.put("host", requirementInstance1); - // - // RequirementInstance requirementInstance2 = new RequirementInstance(); - // requirementInstance2.setNode("NA"); - // RelationshipImpl relationshipImpl2 = new RelationshipImpl(); - // relationshipImpl2.setType("tosca.relationships.LinkTo"); - // requirementInstance2.setRelationship(relationshipImpl2); - // - // requirements.put("link", requirementInstance2); - // - // resourceInstance.setRequirements(requirements); - return resourceInstance; - } - - @Test - @Ignore - public void testConenctResourceInstancesJson() { - RequirementCapabilityRelDef addRelationship = addRelationship("apache_1", "compute_100"); - String json = prettyGson.toJson(addRelationship); - log.debug(json); - - RequirementCapabilityRelDef capabilityRelDef = prettyGson.fromJson(json, RequirementCapabilityRelDef.class); - log.debug("{}", capabilityRelDef); - - } - - public RequirementCapabilityRelDef addRelationship(String from, String to) { - RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef(); - requirementCapabilityRelDef.setFromNode(from); - requirementCapabilityRelDef.setToNode(to); - List relationships = new ArrayList(); - - String req = "host"; - RelationshipImpl relationshipImpl = new RelationshipImpl(); - relationshipImpl.setType("tosca.nodes.HostedOn"); - RequirementAndRelationshipPair rels = new RequirementAndRelationshipPair(req, relationshipImpl); - relationships.add(rels); - - requirementCapabilityRelDef.setRelationships(relationships); - - return requirementCapabilityRelDef; - } - - @Before - public void createUserAndCategory() { - deleteAndCreateCategory(CATEGORY_NAME); - deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID); - } - - private UserData deleteAndCreateUser(String userId, String firstName, String lastName) { - UserData userData = new UserData(); - userData.setUserId(userId); - userData.setFirstName(firstName); - userData.setLastName(lastName); - - titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); - titanDao.createNode(userData, UserData.class); - titanDao.commit(); - - return userData; - } - - private void deleteAndCreateCategory(String category) { - String[] names = category.split("/"); - OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); - OperationTestsUtil.deleteAndCreateServiceCategory(category, titanDao); - - /* - * CategoryData categoryData = new CategoryData(); categoryData.setName(category); - * - * titanDao.deleteNode(categoryData, CategoryData.class); Either createNode = titanDao .createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode); - */ - } - - @Test - @Ignore - public void testConnectResourceInstances() { - - PrintGraph printGraph1 = new PrintGraph(); - int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); - try { - - String capabilityTypeName = CAPABILITY_2; - String reqName = "host"; - String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; - String rootName = "Root2" + TEST_CLASS_NUMBER; - String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; - String computeNodeName = reqNodeName; - String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; - String reqRelationship = "myrelationship"; - - // Create Capability type - CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); - capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); - CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName); - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - // create root resource - Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true); - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - Either updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - Either fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true); - - String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); - log.debug(rootResourceJson); - - // create software component - Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true); - - resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - // create compute component - Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true); - - // rollbackAndPrint(); - - // Add capabilities to Compute Resource - CapabilityDefinition addCapability = addCapabilityToResource(capabilityTypeName, "host", computeComponent); - - // create requirement definition - - Either addRequirementToResource = addRequirementToResource(capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent); - - String parentReqUniqId = addRequirementToResource.left().value().getUniqueId(); - - // create my resource derived from software component - Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true); - - String serviceName = "myservice.1.0"; - List resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, computeComponent, "host", false, addCapability.getUniqueId(), addRequirementToResource.left().value().getUniqueId()); - - PrintGraph printGraph = new PrintGraph(); - String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value()); - log.debug(webGraph); - - Either resourceFull = resourceOperation.getResource(resource.getUniqueId()); - assertTrue(resourceFull.isLeft()); - List componentInstancesRelations = resourceFull.left().value().getComponentInstancesRelations(); - - RequirementCapabilityRelDef capabilityRelDef = componentInstancesRelations.get(0); - capabilityRelDef.getRelationships().get(0).setRequirement("host"); - - // disconnectResourcesInService(serviceName, resInstances.get(0), - // "host"); - disconnectResourcesInService(serviceName, capabilityRelDef); - - } finally { - rollbackAndPrint(false); - compareGraphSize(numberOfVertices); - } - - } - - @Test - @Ignore - public void testConnectResourceInstances1Requirement2Capabilities() { - - PrintGraph printGraph1 = new PrintGraph(); - int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); - - try { - - String capabilityTypeName1 = CAPABILITY_1; - String capabilityTypeName2 = CAPABILITY_2; - String reqName1 = "host1"; - String reqName2 = "host2"; - String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; - String rootName = "Root2" + TEST_CLASS_NUMBER; - String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; - String computeNodeName = reqNodeName; - String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; - String reqRelationship = "myrelationship"; - - // Create Capability type - CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); - capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); - CapabilityTypeDefinition createCapabilityDef1 = capabilityTypeOperationTest.createCapability(capabilityTypeName1); - CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest.createCapability(capabilityTypeName2); - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - // create root resource - Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true); - - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - Either updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - Either fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true); - - String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); - log.debug(rootResourceJson); - - // create software component - Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true); - - resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - // create compute component - Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true); - - // Add capabilities to Compute Resource - CapabilityDefinition capabilty1 = addCapabilityToResource(capabilityTypeName1, reqName1, computeComponent); - CapabilityDefinition capabilty2 = addCapabilityToResource(capabilityTypeName2, reqName2, computeComponent); - - // rollbackAndPrint(); - - // create requirement definition - - Either addRequirementToResource = addRequirementToResource(capabilityTypeName1, reqName1, reqNodeName, reqRelationship, softwareComponent); - - String requirementId = addRequirementToResource.left().value().getUniqueId(); - String parentReqUniqId = requirementId; - - // create my resource derived from software component - Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true); - - String serviceName = "myservice.1.0"; - List resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, computeComponent, reqName1, false, capabilty1.getUniqueId(), requirementId); - - PrintGraph printGraph = new PrintGraph(); - String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value()); - log.debug(webGraph); - - RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair(); - relationPair.setRequirement(reqName2); - - relationPair.setCapabilityUid(capabilty1.getUniqueId()); - relationPair.setRequirementUid(requirementId); - - Either connectResourcesInService1 = resourceInstanceOperation.connectResourcesInService(serviceName, NodeTypeEnum.Service, resInstances.get(0).getUniqueId(), resInstances.get(1).getUniqueId(), - relationPair); - assertEquals("check cannot associate resource instances", TitanOperationStatus.ILLEGAL_ARGUMENT, connectResourcesInService1.right().value()); - relationPair.setRequirement(reqName1); - Either connectResourcesInService2 = resourceInstanceOperation.connectResourcesInService(serviceName, NodeTypeEnum.Service, resInstances.get(0).getUniqueId(), resInstances.get(1).getUniqueId(), - relationPair); - assertEquals("check cannot associate resource instances", TitanOperationStatus.TITAN_SCHEMA_VIOLATION, connectResourcesInService2.right().value()); - - relationPair.setRequirement(reqName1); - - RequirementCapabilityRelDef capabilityRelDef = new RequirementCapabilityRelDef(); - capabilityRelDef.setFromNode(resInstances.get(0).getUniqueId()); - capabilityRelDef.setToNode(resInstances.get(1).getUniqueId()); - List list = new ArrayList<>(); - list.add(relationPair); - - disconnectResourcesInService(serviceName, capabilityRelDef); - - } finally { - rollbackAndPrint(); - compareGraphSize(numberOfVertices); - } - - } - - private void rollbackAndPrint() { - rollbackAndPrint(false); - } - - private void rollbackAndPrint(boolean print) { - TitanOperationStatus rollback = titanDao.rollback(); - if (print) { - log.debug("rollback status={}", rollback); - PrintGraph printGraph = new PrintGraph(); - printGraph.printGraphVertices(titanDao.getGraph().left().value()); - } - } - - @Test - @Ignore - public void testConnectResourceInstances2Requirement2Capabilities() { - - PrintGraph printGraph1 = new PrintGraph(); - int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); - - try { - - String capabilityTypeName1 = CAPABILITY_1; - String capabilityTypeName2 = CAPABILITY_2; - String reqName1 = "host1"; - String reqName2 = "host2"; - String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; - String rootName = "Root2" + TEST_CLASS_NUMBER; - String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; - String computeNodeName = reqNodeName; - String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; - String reqRelationship = "myrelationship"; - - // Create Capability type - CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); - capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); - CapabilityTypeDefinition createCapabilityDef1 = capabilityTypeOperationTest.createCapability(capabilityTypeName1); - CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest.createCapability(capabilityTypeName2); - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - // create root resource - Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true); - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - Either updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - Either fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true); - - String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); - log.debug(rootResourceJson); - - // rollbackAndPrint(); - // OKKKKKKK - - // create software component - Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true); - - resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - // create compute component - Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true); - - // rollbackAndPrint(); - // OKKKKKKKKKK - - // Add capabilities to Compute Resource - CapabilityDefinition capabilty1 = addCapabilityToResource(capabilityTypeName1, reqName1, computeComponent); - CapabilityDefinition capabilty2 = addCapabilityToResource(capabilityTypeName2, reqName2, computeComponent); - - // rollbackAndPrint(); - - // create requirement definition - - Either addRequirementToResource1 = addRequirementToResource(capabilityTypeName1, reqName1, reqNodeName, reqRelationship, softwareComponent); - - Either addRequirementToResource2 = addRequirementToResource(capabilityTypeName2, reqName2, reqNodeName, reqRelationship, softwareComponent); - - // create my resource derived from software component - String MY_RESOURCE = "my-resource"; - Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, MY_RESOURCE, myResourceVersion, softwareComponent.getName(), true, true); - - String serviceName = "myservice.1.0"; - String requirementId1 = addRequirementToResource1.left().value().getUniqueId(); - String requirementId2 = addRequirementToResource2.left().value().getUniqueId(); - List resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, computeComponent, reqName1, false, capabilty1.getUniqueId(), requirementId1); - - RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair(); - relationPair.setRequirement(reqName2); - relationPair.setCapabilityUid(capabilty2.getUniqueId()); - relationPair.setRequirementUid(requirementId2); - relationPair.setCapabilityOwnerId(resInstances.get(1).getUniqueId()); - relationPair.setRequirementOwnerId(resInstances.get(0).getUniqueId()); - Either connectResourcesInService1 = resourceInstanceOperation.connectResourcesInService(serviceName, NodeTypeEnum.Service, resInstances.get(0).getUniqueId(), resInstances.get(1).getUniqueId(), - relationPair); - assertTrue("check associate resource instances succeed " + reqName2, connectResourcesInService1.isLeft()); - - // rollbackAndPrint(); - - PrintGraph printGraph = new PrintGraph(); - String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value()); - log.debug(webGraph); - - RequirementCapabilityRelDef reqCapDef = new RequirementCapabilityRelDef(); - reqCapDef.setFromNode(resInstances.get(0).getUniqueId()); - reqCapDef.setToNode(resInstances.get(1).getUniqueId()); - - relationPair.setRequirement(reqName1); - relationPair.setCapabilityUid(capabilty1.getUniqueId()); - relationPair.setRequirementUid(requirementId1); - RelationshipImpl relationship = new RelationshipImpl(); - relationship.setType(reqName1); - relationPair.setRelationships(relationship); - - List list = new ArrayList<>(); - list.add(relationPair); - reqCapDef.setRelationships(list); - - disconnectResourcesInService(serviceName, reqCapDef); - - reqCapDef.getRelationships().clear(); - - RequirementAndRelationshipPair relationPair1 = new RequirementAndRelationshipPair(); - relationPair1.setRequirement(reqName2); - relationPair1.setCapabilityUid(capabilty2.getUniqueId()); - relationPair1.setRequirementUid(requirementId2); - relationPair1.setCapabilityOwnerId(resInstances.get(1).getUniqueId()); - relationPair1.setRequirementOwnerId(resInstances.get(0).getUniqueId()); - relationship.setType(reqName2); - relationPair1.setRelationships(relationship); - reqCapDef.getRelationships().add(relationPair1); - - disconnectResourcesInService(serviceName, reqCapDef); - - RequirementCapabilityRelDef relation = new RequirementCapabilityRelDef(); - String fromResUid = resInstances.get(0).getUniqueId(); - String toResUid = resInstances.get(1).getUniqueId(); - relation.setFromNode(fromResUid); - relation.setToNode(toResUid); - List relationships = new ArrayList(); - RequirementAndRelationshipPair immutablePair1 = new RequirementAndRelationshipPair(reqName1, null); - RequirementAndRelationshipPair immutablePair2 = new RequirementAndRelationshipPair(reqName2, null); - immutablePair1.setCapabilityUid(capabilty1.getUniqueId()); - immutablePair1.setRequirementUid(addRequirementToResource1.left().value().getUniqueId()); - immutablePair1.setRequirementOwnerId(resInstances.get(0).getUniqueId()); - immutablePair1.setCapabilityOwnerId(resInstances.get(1).getUniqueId()); - - immutablePair2.setCapabilityUid(capabilty2.getUniqueId()); - immutablePair2.setRequirementUid(addRequirementToResource2.left().value().getUniqueId()); - immutablePair2.setRequirementOwnerId(resInstances.get(0).getUniqueId()); - immutablePair2.setCapabilityOwnerId(resInstances.get(1).getUniqueId()); - - relationships.add(immutablePair1); - relationships.add(immutablePair2); - relation.setRelationships(relationships); - - Either associateResourceInstances = resourceInstanceOperation.associateResourceInstances(serviceName, NodeTypeEnum.Service, relation, true, false); - assertTrue("check return code after associating 2 requirements in one request", associateResourceInstances.isLeft()); - RequirementCapabilityRelDef capabilityRelDef = associateResourceInstances.left().value(); - String fromNode = capabilityRelDef.getFromNode(); - assertEquals("check from node", resInstances.get(0).getUniqueId(), fromNode); - String toNode = capabilityRelDef.getToNode(); - assertEquals("check to node", resInstances.get(1).getUniqueId(), toNode); - List relationships2 = capabilityRelDef.getRelationships(); - assertEquals("check number of relations", 2, relationships2.size()); - - for (RequirementAndRelationshipPair pair : relationships2) { - String key = pair.getRequirement(); - RelationshipImpl relationshipImpl = pair.getRelationship(); - if (key.equals(reqName1)) { - String type = relationshipImpl.getType(); - assertEquals("Check relationship type name", reqRelationship, type); - } else if (key.equals(reqName2)) { - String type = relationshipImpl.getType(); - assertEquals("Check relationship type name", reqRelationship, type); - } else { - assertTrue("requirement " + key + " was not found in the original request", false); - } - } - - verifyGetAllResourceInstanceFromService(reqName1, reqName2, serviceName, fromResUid, toResUid); - - List resourcesPathList = new ArrayList(); - TitanOperationStatus findResourcesPathRecursively = resourceOperation.findResourcesPathRecursively(resource.getUniqueId(), resourcesPathList); - assertEquals("check returned status", TitanOperationStatus.OK, findResourcesPathRecursively); - assertEquals("check list size", 3, resourcesPathList.size()); - - TitanOperationStatus validateTheTargetResourceInstance = resourceInstanceOperation.validateTheTargetResourceInstance(MY_RESOURCE, resource.getUniqueId()); - assertEquals("check resource name in the path", TitanOperationStatus.OK, validateTheTargetResourceInstance); - validateTheTargetResourceInstance = resourceInstanceOperation.validateTheTargetResourceInstance(softwareCompName, resource.getUniqueId()); - assertEquals("check resource name in the path", TitanOperationStatus.OK, validateTheTargetResourceInstance); - - validateTheTargetResourceInstance = resourceInstanceOperation.validateTheTargetResourceInstance(softwareCompName + "STAM", resource.getUniqueId()); - assertEquals("check resource name not in the path", TitanOperationStatus.MATCH_NOT_FOUND, validateTheTargetResourceInstance); - - Either deleteResourceInstance = resourceInstanceOperation.deleteComponentInstance(NodeTypeEnum.Service, serviceName, toResUid, true); - assertTrue("check resource instance was deleted.", deleteResourceInstance.isLeft()); - - } finally { - rollbackAndPrint(false); - compareGraphSize(numberOfVertices); - } - - } - - private void verifyGetAllResourceInstanceFromService(String reqName1, String reqName2, String serviceName, String fromResUid, String toResUid) { - - Either, List>, StorageOperationStatus> allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceName, NodeTypeEnum.Service, NodeTypeEnum.Resource, - true); - // assertTrue("check return code after get all resource instances", - // associateResourceInstances.isLeft()); - ImmutablePair, List> immutablePair = allResourceInstances.left().value(); - List nodes = immutablePair.getKey(); - List edges = immutablePair.getValue(); - assertEquals("check 2 nodes returned", 2, nodes.size()); - assertEquals("check one relation returned", 1, edges.size()); - RequirementCapabilityRelDef requirementCapabilityRelDef = edges.get(0); - assertEquals("check from node", requirementCapabilityRelDef.getFromNode(), fromResUid); - requirementCapabilityRelDef.getToNode(); - assertEquals("check to node", requirementCapabilityRelDef.getToNode(), toResUid); - int size = requirementCapabilityRelDef.getRelationships().size(); - assertEquals("check number of relations", 2, size); - String req1 = requirementCapabilityRelDef.getRelationships().get(0).getRequirement(); - String req2 = requirementCapabilityRelDef.getRelationships().get(1).getRequirement(); - - List requirements = new ArrayList(); - requirements.add(req1); - requirements.add(req2); - - assertTrue("check requirement returned " + reqName1, requirements.contains(reqName1)); - assertTrue("check requirement returned " + reqName2, requirements.contains(reqName2)); - - String nodesStr = prettyGson.toJson(nodes); - String edgesStr = prettyGson.toJson(edges); - - log.debug(nodesStr); - log.debug(edgesStr); - } - - private Either addRequirementToResource(String capabilityTypeName1, String reqName1, String reqNodeName, String reqRelationship, Resource softwareComponent) { - RequirementDefinition reqDefinition1 = new RequirementDefinition(); - reqDefinition1.setNode(reqNodeName); - reqDefinition1.setRelationship(reqRelationship); - reqDefinition1.setCapability(capabilityTypeName1); - // add requirement to software component - Either addRequirementToResource = requirementOperation.addRequirementToResource(reqName1, reqDefinition1, softwareComponent.getUniqueId(), true); - assertEquals("check requirement was added", true, addRequirementToResource.isLeft()); - return addRequirementToResource; - } - - private CapabilityDefinition addCapabilityToResource(String capabilityTypeName1, String reqName1, Resource computeComponent) { - CapabilityDefinition capabilityDefinition1 = new CapabilityDefinition(); - capabilityDefinition1.setDescription("my capability"); - capabilityDefinition1.setType(capabilityTypeName1); - List validSourceTypes = new ArrayList(); - validSourceTypes.add("tosca.nodes.SC"); - capabilityDefinition1.setValidSourceTypes(validSourceTypes); - Either addCapability = capabilityOperation.addCapability(computeComponent.getUniqueId(), reqName1, capabilityDefinition1, true); - assertTrue("check capability created ", addCapability.isLeft()); - return addCapability.left().value(); - } - - @Test - @Ignore - public void testConnectResourceInstancesCapabilityNameDiffFromReqName() { - - PrintGraph printGraph1 = new PrintGraph(); - int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); - - try { - - String capabilityTypeName = CAPABILITY_2; - String reqName = "host"; - String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; - String rootName = "Root2" + TEST_CLASS_NUMBER; - String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; - String computeNodeName = reqNodeName; - String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; - String reqRelationship = "myrelationship"; - - String DIFFERENT_CAPABILITY = "hostDiffernet"; - - // Create Capability type - CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); - capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); - CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName); - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - // create root resource - Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true); - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - Either updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - Either fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true); - - String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); - log.debug(rootResourceJson); - - // create software component - Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true); - - resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - // create compute component - Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true); - - CapabilityDefinition capabilty = addCapabilityToResource(capabilityTypeName, DIFFERENT_CAPABILITY, computeComponent); - - // create requirement definition - - Either addRequirementToResource = addRequirementToResource(capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent); - - String parentReqUniqId = addRequirementToResource.left().value().getUniqueId(); - - // create my resource derived from software component - Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true); - - String serviceName = "myservice.1.0"; - List resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, computeComponent, "host", false, capabilty.getUniqueId(), parentReqUniqId); - - PrintGraph printGraph = new PrintGraph(); - String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value()); - } finally { - rollbackAndPrint(); - - compareGraphSize(numberOfVertices); - } - - } - - @Test - @Ignore - public void testConnectResourceInstancesInvalidCapability() { - - PrintGraph printGraph1 = new PrintGraph(); - int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); - - try { - - String capabilityTypeName = CAPABILITY_2; - String reqName = "host"; - String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; - String rootName = "Root2" + TEST_CLASS_NUMBER; - String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; - String computeNodeName = reqNodeName; - String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; - String reqRelationship = "myrelationship"; - - String capabilityTypeNameOther = CAPABILITY_2 + "othertype"; - - String DIFFERENT_CAPABILITY = "hostDiffernet"; - - // Create Capability type - CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); - capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); - CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName); - - CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest.createCapability(capabilityTypeNameOther); - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - // create root resource - Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true); - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - Either updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - Either fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true); - - String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); - log.debug(rootResourceJson); - - // create software component - Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true); - - resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - // create compute component - Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true); - - addCapabilityToResource(capabilityTypeName, DIFFERENT_CAPABILITY, computeComponent); - - // create requirement definition - - Either addRequirementToResource = addRequirementToResource(capabilityTypeNameOther, reqName, reqNodeName, reqRelationship, softwareComponent); - - String parentReqUniqId = addRequirementToResource.left().value().getUniqueId(); - - // create my resource derived from software component - Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true); - - String serviceName = "myservice.1.0"; - List resInstances = buildServiceAndConnectBetweenResourceInstancesWithError(serviceName, resource, computeComponent, "host", false, TitanOperationStatus.ILLEGAL_ARGUMENT); - - PrintGraph printGraph = new PrintGraph(); - String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value()); - log.debug(webGraph); - - } finally { - rollbackAndPrint(); - - compareGraphSize(numberOfVertices); - } - - } - - private void compareGraphSize(int numberOfVertices, Set toRemoveFromSet) { - PrintGraph printGraph2 = new PrintGraph(); - int numberOfVerticesCurr = printGraph2.getNumberOfVertices(titanDao.getGraph().left().value()); - - Set set = printGraph2.getVerticesSet(titanDao.getGraph().left().value()); - if (toRemoveFromSet != null) { - set.removeAll(toRemoveFromSet); - } - - assertEquals("check all data deleted from graph " + set, numberOfVertices, numberOfVerticesCurr); - } - - private void compareGraphSize(int numberOfVertices) { - PrintGraph printGraph2 = new PrintGraph(); - int numberOfVerticesCurr = printGraph2.getNumberOfVertices(titanDao.getGraph().left().value()); - - assertEquals("check all data deleted from graph " + printGraph2.getVerticesSet(titanDao.getGraph().left().value()), numberOfVertices, numberOfVerticesCurr); - } - - @Test - @Ignore - public void testConnectResourceInstancesRequirementNotFound() { - - PrintGraph printGraph1 = new PrintGraph(); - int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); - try { - - String capabilityTypeName = CAPABILITY_2; - String reqName = "host"; - String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; - String rootName = "Root2" + TEST_CLASS_NUMBER; - String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; - String computeNodeName = reqNodeName; - String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; - String reqRelationship = "myrelationship"; - - String DIFFERENT_CAPABILITY = "hostDiffernet"; - - // Create Capability type - CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); - capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); - CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName); - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - // create root resource - Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true); - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - Either updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - Either fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true); - - String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); - log.debug(rootResourceJson); - - // create software component - Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true); - - resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - // create compute component - Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true); - - addCapabilityToResource(capabilityTypeName, reqName, computeComponent); - - // create requirement definition - - RequirementDefinition reqDefinition = new RequirementDefinition(); - reqDefinition.setNode(reqNodeName); - reqDefinition.setRelationship(reqRelationship); - reqDefinition.setCapability(capabilityTypeName); - // add requirement to software component - Either addRequirementToResource = requirementOperation.addRequirementToResource(reqName + "ssssssss", reqDefinition, softwareComponent.getUniqueId(), true); - assertEquals("check requirement was added", true, addRequirementToResource.isLeft()); - - String parentReqUniqId = addRequirementToResource.left().value().getUniqueId(); - - // create my resource derived from software component - Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true); - - String serviceName = "myservice.1.0"; - List resInstances = buildServiceAndConnectBetweenResourceInstancesWithError(serviceName, resource, computeComponent, "host", false, TitanOperationStatus.ILLEGAL_ARGUMENT); - - PrintGraph printGraph = new PrintGraph(); - String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value()); - log.debug(webGraph); - - } finally { - titanDao.rollback(); - - compareGraphSize(numberOfVertices); - } - - } - - private void disconnectResourcesInService(String serviceName, RequirementCapabilityRelDef reqCapDef) { - - Either, TitanOperationStatus> disconnectResourcesInService = resourceInstanceOperation.disconnectResourcesInService(serviceName, NodeTypeEnum.Service, reqCapDef); - assertTrue("check relatioship instance was deleted", disconnectResourcesInService.isLeft()); - - disconnectResourcesInService = resourceInstanceOperation.disconnectResourcesInService(serviceName, NodeTypeEnum.Service, reqCapDef); - assertTrue("check relatioship instance already was deleted", disconnectResourcesInService.isRight()); - assertEquals("check relatioship instance already was deleted. status NOT_FOUND", TitanOperationStatus.NOT_FOUND, disconnectResourcesInService.right().value()); - } - - private List buildServiceAndConnectBetweenResourceInstancesWithError(String serviceName, Resource resource, Resource computeComponent, String requirement, boolean ignoreCreatingService, - TitanOperationStatus titanOperationStatus) { - - String serviceId = "myservice.1.0"; - - if (false == ignoreCreatingService) { - ServiceMetadataData createService = createService(serviceId); - } - ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", resource.getName()); - - ComponentInstance computeInstance = buildResourceInstance(computeComponent.getUniqueId(), "2", computeComponent.getName()); - - Either myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false); - assertTrue("check instance added to service", myinstanceRes.isLeft()); - ComponentInstance value1 = myinstanceRes.left().value(); - Either computeInstTes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance, NodeTypeEnum.Resource, false); - assertTrue("check instance added to service", computeInstTes.isLeft()); - ComponentInstance value2 = computeInstTes.left().value(); - - RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair(); - relationPair.setRequirement(requirement); - - Either connectResourcesInService = resourceInstanceOperation.connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(), relationPair); - - assertTrue("check relation was not created", connectResourcesInService.isRight()); - assertEquals("check error code after connect resource instances failed", titanOperationStatus, connectResourcesInService.right().value()); - - List resInstances = new ArrayList(); - resInstances.add(value1); - - return resInstances; - - } - - private List buildServiceAndConnectBetweenResourceInstances(String serviceName, Resource resource, Resource computeComponent, String requirement, boolean ignoreCreatingService, String capabilityId, String requirementId) { - - String serviceId = "myservice.1.0"; - - if (false == ignoreCreatingService) { - ServiceMetadataData createService = createService(serviceId); - } - ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", resource.getName()); - - ComponentInstance computeInstance = buildResourceInstance(computeComponent.getUniqueId(), "2", computeComponent.getName()); - - Either myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false); - assertTrue("check instance added to service", myinstanceRes.isLeft()); - ComponentInstance value1 = myinstanceRes.left().value(); - Either computeInstTes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance, NodeTypeEnum.Resource, false); - assertTrue("check instance added to service", computeInstTes.isLeft()); - ComponentInstance value2 = computeInstTes.left().value(); - RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair(); - relationPair.setRequirement(requirement); - - relationPair.setCapabilityUid(capabilityId); - relationPair.setRequirementUid(requirementId); - relationPair.setRequirementOwnerId(value1.getUniqueId()); - relationPair.setCapabilityOwnerId(value2.getUniqueId()); - - Either connectResourcesInService = resourceInstanceOperation.connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(), relationPair); - - assertTrue("check relation created", connectResourcesInService.isLeft()); - - List resInstances = new ArrayList(); - resInstances.add(value1); - resInstances.add(value2); - - return resInstances; - - } - - @Test - @Ignore - public void getAllResourceInstancesThree() { - - PrintGraph printGraph1 = new PrintGraph(); - int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); - try { - - Set vertexSetBeforeMethod = printGraph1.getVerticesSet(titanDao.getGraph().left().value()); - - String capabilityTypeName = CAPABILITY_2; - String reqName = "host"; - String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; - String rootName = "Root2" + TEST_CLASS_NUMBER; - String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; - String computeNodeName = reqNodeName; - String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; - String reqRelationship = "myrelationship"; - - // Create Capability type - CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); - capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); - CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName); - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - // create root resource - Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true); - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - Either updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - Either fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true); - - String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); - log.debug(rootResourceJson); - - // create software component - Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true); - - resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - // create compute component - Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true); - - // rollbackAndPrint(); - - // Add capabilities to Compute Resource - CapabilityDefinition capability = addCapabilityToResource(capabilityTypeName, "host", computeComponent); - - // create requirement definition - - Either addRequirementToResource = addRequirementToResource(capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent); - - String parentReqUniqId = addRequirementToResource.left().value().getUniqueId(); - - // create my resource derived from software component - Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true); - - String serviceId = "myservice.1.0"; - - ServiceMetadataData createService = createService(serviceId); - - Either, List>, StorageOperationStatus> allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource, - true); - assertTrue("check NOT_FOUND is returned", allResourceInstances.isRight()); - assertEquals("check NOT_FOUND is returned", allResourceInstances.right().value(), StorageOperationStatus.NOT_FOUND); - - ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", "my-resource"); - myresourceInstance.setName("my-resource"); - - ComponentInstance computeInstance1 = buildResourceInstance(computeComponent.getUniqueId(), "2", "tosca.nodes.Compute2"); - - Either myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false); - assertTrue("check instance added to service", myinstanceRes.isLeft()); - ComponentInstance value1 = myinstanceRes.left().value(); - - allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource, true); - assertTrue("check resource instances found", allResourceInstances.isLeft()); - ImmutablePair, List> immutablePair = allResourceInstances.left().value(); - List nodes = immutablePair.getKey(); - List edges = immutablePair.getValue(); - - assertEquals("check resource instances size", 1, nodes.size()); - assertEquals("check resource instances size", 0, edges.size()); - - Either computeInstTes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance1, NodeTypeEnum.Resource, false); - assertTrue("check instance added to service", computeInstTes.isLeft()); - ComponentInstance value2 = computeInstTes.left().value(); - - allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource, true); - assertTrue("check resource instances found", allResourceInstances.isLeft()); - immutablePair = allResourceInstances.left().value(); - nodes = immutablePair.getKey(); - edges = immutablePair.getValue(); - - assertEquals("check resource instances size", 2, nodes.size()); - assertEquals("check resource instances size", 0, edges.size()); - - String requirement = "host"; - RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair(); - relationPair.setRequirement(requirement); - relationPair.setCapabilityUid(capability.getUniqueId()); - relationPair.setRequirementUid(addRequirementToResource.left().value().getUniqueId()); - relationPair.setRequirementOwnerId(value1.getUniqueId()); - relationPair.setCapabilityOwnerId(value2.getUniqueId()); - - Either connectResourcesInService = resourceInstanceOperation.connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(), relationPair); - - assertTrue("check relation created", connectResourcesInService.isLeft()); - - allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource, true); - assertTrue("check resource instances found", allResourceInstances.isLeft()); - immutablePair = allResourceInstances.left().value(); - nodes = immutablePair.getKey(); - edges = immutablePair.getValue(); - - assertEquals("check resource instances size", 2, nodes.size()); - assertEquals("check resource instances size", 1, edges.size()); - - List resInstances2 = new ArrayList(); - resInstances2.add(value1); - resInstances2.add(value2); - - ComponentInstance myresourceInstance2 = buildResourceInstance(resource.getUniqueId(), "1", "myresource2"); - - Either newResource = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "3", true, myresourceInstance2, NodeTypeEnum.Resource, false); - - assertTrue("added resource instance successfully", newResource.isLeft()); - - relationPair.setRequirement(requirement); - relationPair.setRequirementOwnerId(newResource.left().value().getUniqueId()); - - Either connectResourcesInService2 = resourceInstanceOperation.connectResourcesInService(serviceId, NodeTypeEnum.Service, newResource.left().value().getUniqueId(), value2.getUniqueId(), - relationPair); - assertTrue("check resource instance was added to service", connectResourcesInService2.isLeft()); - - allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource, true); - assertTrue("check resource instances found", allResourceInstances.isLeft()); - immutablePair = allResourceInstances.left().value(); - nodes = immutablePair.getKey(); - edges = immutablePair.getValue(); - - assertEquals("check resource instances size", 3, nodes.size()); - assertEquals("check resource instances size", 2, edges.size()); - - Either, TitanOperationStatus> deleteAllResourceInstancesOfService = resourceInstanceOperation.deleteAllComponentInstancesInternal(serviceId, NodeTypeEnum.Service); - assertTrue("check resource instances was deleted.", deleteAllResourceInstancesOfService.isLeft()); - assertEquals("check number of deleted resource instances.", 3, deleteAllResourceInstancesOfService.left().value().size()); - - Either, TitanOperationStatus> allRelatinshipInst = titanDao.getAll(NodeTypeEnum.RelationshipInst, RelationshipInstData.class); - assertTrue("allRelatinshipInst is empty", allRelatinshipInst.isRight()); - assertEquals("allRelatinshipInst result is NOT_FOUND", TitanOperationStatus.NOT_FOUND, allRelatinshipInst.right().value()); - - Either deleteComputeResource = resourceOperation.deleteResource(computeComponent.getUniqueId(), true); - assertTrue("delete compute resource succeed", deleteComputeResource.isLeft()); - - Either deleteSCResource = resourceOperation.deleteResource(softwareComponent.getUniqueId(), true); - assertTrue("delete software component resource succeed", deleteSCResource.isLeft()); - - Either deleteMyResource = resourceOperation.deleteResource(resource.getUniqueId(), true); - assertTrue("delete my resource succeed", deleteMyResource.isLeft()); - - Either rootResourceDeleted = resourceOperation.deleteResource(rootResource.getUniqueId(), true); - assertTrue("delete root resource succeed", rootResourceDeleted.isLeft()); - - Set vertexSetAfterDelete = printGraph1.getVerticesSet(titanDao.getGraph().left().value()); - - vertexSetAfterDelete.removeAll(vertexSetBeforeMethod); - - log.debug("vertexSetAfterDelete={}", vertexSetAfterDelete); - log.debug("vertexSetAfterDelete size={}", vertexSetAfterDelete.size()); - - // int numberOfVerticesAfterOperation = - // printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); - // System.out.println(numberOfVerticesAfterOperation); - // 6 - service, 2 tags, capability + 2 parameters - // compareGraphSize(numberOfVertices + 6, vertexSetBeforeMethod); - - } finally { - rollbackAndPrint(false); - compareGraphSize(numberOfVertices); - // printGraph1.printGraphVertices(titanDao.getGraph().left().value()); - } - - } - - public void testCreateRootResource() { - - String name = "tosca.nodes.Root"; - - String state = LifecycleStateEnum.CERTIFIED.name(); - - ResourceMetadataData resourceData1 = new ResourceMetadataData(); - resourceData1.getMetadataDataDefinition().setUniqueId(UniqueIdBuilder.buildResourceUniqueId()); - resourceData1.getMetadataDataDefinition().setName(name); - resourceData1.getMetadataDataDefinition().setState(state); - resourceData1.getMetadataDataDefinition().setHighestVersion(true); - resourceData1.getMetadataDataDefinition().setContactId("contactId"); - Either createNode1 = titanDao.createNode(resourceData1, ResourceMetadataData.class); - - log.debug("{}", createNode1); - - titanDao.commit(); - } - - public void testMultiResourceCertified() { - boolean create = true; - String name = "myresource7"; - if (create) { - - String state = LifecycleStateEnum.CERTIFIED.name(); - boolean isHighestVersion = true; - - ResourceMetadataData resourceData1 = new ResourceMetadataData(); - resourceData1.getMetadataDataDefinition().setUniqueId(name + "." + "1.0"); - resourceData1.getMetadataDataDefinition().setName(name); - resourceData1.getMetadataDataDefinition().setState(state); - resourceData1.getMetadataDataDefinition().setHighestVersion(true); - resourceData1.getMetadataDataDefinition().setContactId("contactId"); - Either createNode1 = titanDao.createNode(resourceData1, ResourceMetadataData.class); - - log.debug("{}", createNode1); - - titanDao.commit(); - - // resourceData1.setUniqueId(name + "." + "2.0"); - // resourceData1.setHighestVersion(true); - // resourceData1.setContactId("contactId"); - // - // Either createNode2 = titanDao - // .createNode(resourceData1, ResourceData.class); - // System.out.println(createNode2); - // - // titanDao.commit(); - - // resourceData1.setHighestVersion(false); - resourceData1.getMetadataDataDefinition().setContactId("222contactId222"); - Either updateNode = titanDao.updateNode(resourceData1, ResourceMetadataData.class); - - titanDao.commit(); - - // TitanGraph titanGraph = titanDao.getGraph().left().value(); - // Iterable> vertices = - // titanGraph.indexQuery("highestVersion", - // "v.highestVersion:true").vertices(); - // for (Result vertex : vertices) { - // Vertex element = vertex.getElement(); - // System.out.println( ElementHelper.getProperties(element)); - // } - - } - - Either, TitanOperationStatus> byCriteria = searchForResource(name); - - log.debug("{}", byCriteria.left().value().size()); - - byCriteria = searchForResource(name); - - log.debug("{}", byCriteria.left().value().size()); - - } - - private Either, TitanOperationStatus> searchForResource(String name) { - Map propertiesToMatch = new HashMap(); - propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); - // propertiesToMatch.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), - // true); - propertiesToMatch.put(GraphPropertiesDictionary.NAME.getProperty(), name); - propertiesToMatch.put(GraphPropertiesDictionary.CONTACT_ID.getProperty(), "contactId"); - // propertiesToMatch.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), - // true); - Either, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class); - return byCriteria; - } - - @Test - public void testCreateResourceInstanceTwice() { - - PrintGraph printGraph1 = new PrintGraph(); - int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); - try { - - String capabilityTypeName = CAPABILITY_2; - String reqName = "host"; - String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; - String rootName = "Root2" + TEST_CLASS_NUMBER; - String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; - String computeNodeName = reqNodeName; - String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; - String reqRelationship = "myrelationship"; - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - // create root resource - Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true); - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - Either updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - Either fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true); - - // create software component - Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true); - - resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - ComponentInstance myresourceInstance = buildResourceInstance(softwareComponent.getUniqueId(), "1", softwareCompName); - - String serviceName = "myservice.1.0"; - ServiceMetadataData createService = createService(serviceName); - Either myinstanceRes1 = resourceInstanceOperation.createComponentInstance(serviceName, NodeTypeEnum.Service, "1", myresourceInstance, NodeTypeEnum.Resource, true); - assertTrue("check resource instance was created", myinstanceRes1.isLeft()); - - Either myinstanceRes2 = resourceInstanceOperation.createComponentInstance(serviceName, NodeTypeEnum.Service, "1", myresourceInstance, NodeTypeEnum.Resource, true); - assertTrue("check resource instance was not created", myinstanceRes2.isRight()); - assertEquals("check error code", StorageOperationStatus.SCHEMA_VIOLATION, myinstanceRes2.right().value()); - - Either deleteResourceInstance = resourceInstanceOperation.deleteComponentInstance(NodeTypeEnum.Service, serviceName, myinstanceRes1.left().value().getUniqueId(), true); - assertTrue("check resource instance was deleted", deleteResourceInstance.isLeft()); - - deleteResourceInstance = resourceInstanceOperation.deleteComponentInstance(NodeTypeEnum.Service, serviceName, myinstanceRes1.left().value().getUniqueId(), true); - assertTrue("check resource instance was not deleted", deleteResourceInstance.isRight()); - assertEquals("check resource instance was not deleted", StorageOperationStatus.NOT_FOUND, deleteResourceInstance.right().value()); - - } finally { - rollbackAndPrint(false); - compareGraphSize(numberOfVertices); - } - - } - - @Test - @Ignore - public void testConnectResourceInstancesTwice() { - - PrintGraph printGraph1 = new PrintGraph(); - int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); - - try { - - String capabilityTypeName1 = CAPABILITY_1; - String capabilityTypeName2 = CAPABILITY_2; - String reqName1 = "host1"; - String reqName2 = "host2"; - String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; - String rootName = "Root2" + TEST_CLASS_NUMBER; - String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; - String computeNodeName = reqNodeName; - String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; - String reqRelationship = "myrelationship"; - - // Create Capability type - CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); - capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); - CapabilityTypeDefinition createCapabilityDef1 = capabilityTypeOperationTest.createCapability(capabilityTypeName1); - CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest.createCapability(capabilityTypeName2); - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - // create root resource - Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true); - - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - Either updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - Either fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true); - - String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); - log.debug(rootResourceJson); - - // create software component - Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true); - - resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - // create compute component - Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true); - - // Add capabilities to Compute Resource - CapabilityDefinition capabilty1 = addCapabilityToResource(capabilityTypeName1, reqName1, computeComponent); - CapabilityDefinition capabilty2 = addCapabilityToResource(capabilityTypeName2, reqName2, computeComponent); - - // rollbackAndPrint(); - - // create requirement definition - - Either addRequirementToResource = addRequirementToResource(capabilityTypeName1, reqName1, reqNodeName, reqRelationship, softwareComponent); - - String parentReqUniqId = addRequirementToResource.left().value().getUniqueId(); - - // create my resource derived from software component - Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true); - - String serviceId = "myservice.1.0"; - - ServiceMetadataData createService = createService(serviceId); - ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", "my-resource"); - - ComponentInstance computeInstance = buildResourceInstance(computeComponent.getUniqueId(), "2", computeNodeName); - - Either myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false); - assertTrue("check instance added to service", myinstanceRes.isLeft()); - ComponentInstance value1 = myinstanceRes.left().value(); - Either computeInstTes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance, NodeTypeEnum.Resource, false); - assertTrue("check instance added to service", computeInstTes.isLeft()); - ComponentInstance value2 = computeInstTes.left().value(); - - RequirementCapabilityRelDef relation = new RequirementCapabilityRelDef(); - String fromResUid = value1.getUniqueId(); - String toResUid = value2.getUniqueId(); - relation.setFromNode(fromResUid); - relation.setToNode(toResUid); - List relationships = new ArrayList(); - RequirementAndRelationshipPair immutablePair1 = new RequirementAndRelationshipPair(reqName1, null); - immutablePair1.setCapabilityUid(capabilty1.getUniqueId()); - immutablePair1.setRequirementUid(parentReqUniqId); - immutablePair1.setRequirementOwnerId(fromResUid); - immutablePair1.setCapabilityOwnerId(toResUid); - relationships.add(immutablePair1); - - relation.setRelationships(relationships); - - Either connectResourcesInService = resourceInstanceOperation.associateResourceInstances(serviceId, NodeTypeEnum.Service, relation, true, false); - assertTrue("check association succeed", connectResourcesInService.isLeft()); - - relationships.clear(); - RequirementAndRelationshipPair immutablePair2 = new RequirementAndRelationshipPair(reqName2, null); - immutablePair2.setCapabilityUid(capabilty2.getUniqueId()); - immutablePair2.setRequirementUid(parentReqUniqId); - relationships.add(immutablePair2); - - RequirementCapabilityRelDef firstRelation = connectResourcesInService.left().value(); - connectResourcesInService = resourceInstanceOperation.associateResourceInstances(serviceId, NodeTypeEnum.Service, relation, true, false); - assertTrue("check association succeed", connectResourcesInService.isRight()); - assertEquals("check association failed", StorageOperationStatus.MATCH_NOT_FOUND, connectResourcesInService.right().value()); - - Either disconnectResourcesInService = resourceInstanceOperation.dissociateResourceInstances(serviceId, NodeTypeEnum.Service, firstRelation, true); - - assertTrue("check dissociation succeed", disconnectResourcesInService.isLeft()); - - disconnectResourcesInService = resourceInstanceOperation.dissociateResourceInstances(serviceId, NodeTypeEnum.Service, relation, true); - - assertTrue("check dissociation failed", disconnectResourcesInService.isRight()); - assertEquals("check association failed", StorageOperationStatus.NOT_FOUND, disconnectResourcesInService.right().value()); - } finally { - rollbackAndPrint(); - compareGraphSize(numberOfVertices); - } - - } - - private Resource createComputeWithCapability(String capabilityTypeName, String computeNodeName, ResourceOperationTest resourceOperationTest, Resource rootResource) { - // create compute component - // String id = UniqueIdBuilder.buildResourceUniqueId(computeNodeName, - // "1.0"); - // if (resourceOperation.getResource(id).isLeft()){ - // resourceOperation.deleteResource(id); - // } - Either, StorageOperationStatus> oldResource = resourceOperation.getResourceByNameAndVersion(computeNodeName, "1.0", false); - if (oldResource.isLeft()) { - for (Resource old : oldResource.left().value()) { - if (old.getResourceType().equals(ResourceTypeEnum.VFC)) { - resourceOperation.deleteResource(old.getUniqueId()); - } - } - - } - - Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true); - - // rollbackAndPrint(); - - // Add capabilities to Compute Resource - addCapabilityToResource(capabilityTypeName, "host", computeComponent); - return resourceOperation.getResource(computeComponent.getUniqueId()).left().value(); - } - - private Resource createSoftwareComponentWithReq(String softwareCompName, ResourceOperationTest resourceOperationTest, Resource rootResource, String capabilityTypeName, String reqName, String reqRelationship, String reqNodeName) { - Either updateNode; - ResourceMetadataData resourceData = new ResourceMetadataData(); - // create software component - // String id = UniqueIdBuilder.buildResourceUniqueId(softwareCompName, - // "1.0"); - // if (resourceOperation.getResource(id).isLeft()){ - // resourceOperation.deleteResource(id); - // } - Either, StorageOperationStatus> oldResource = resourceOperation.getResourceByNameAndVersion(softwareCompName, "1.0", false); - if (oldResource.isLeft()) { - if (oldResource.isLeft()) { - for (Resource old : oldResource.left().value()) { - if (old.getResourceType().equals(ResourceTypeEnum.VFC)) { - resourceOperation.deleteResource(old.getUniqueId()); - } - } - - } - } - - Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true); - - resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - Either addRequirementToResource = addRequirementToResource(capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent); - - String parentReqUniqId = addRequirementToResource.left().value().getUniqueId(); - - return resourceOperation.getResource(softwareComponent.getUniqueId()).left().value(); - } - - private Resource createRootResource(String rootName, ResourceOperationTest resourceOperationTest) { - // create root resource - // String rootId = UniqueIdBuilder.buildResourceUniqueId(rootName, - // "1.0"); - Either, StorageOperationStatus> oldResource = resourceOperation.getResourceByNameAndVersion(rootName, "1.0", false); - if (oldResource.isLeft()) { - for (Resource old : oldResource.left().value()) { - if (old.getResourceType().equals(ResourceTypeEnum.VFC)) { - resourceOperation.deleteResource(old.getUniqueId()); - } - } - - } - Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true); - ResourceMetadataData rootResourceData = new ResourceMetadataData(); - rootResourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); - rootResourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - Either updateNode = titanDao.updateNode(rootResourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - Either fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true); - - String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); - log.debug(rootResourceJson); - return rootResource; - } - - public void addResourceInstancesAndRelation(String serviceId) { - - String rootName = "tosca.nodes.test.root"; - String softwareCompName = "tosca.nodes.test.softwarecomponent"; - String capabilityTypeName = "myCapability"; - String reqName = "host"; - String computeNodeName = "tosca.nodes.test.compute"; - String reqRelationship = "myRelationship"; - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - Resource rootResource = createRootResource(rootName, resourceOperationTest); - // Create Capability type - CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); - capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); - CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName); - - Resource softwareComponentResource = createSoftwareComponentWithReq(softwareCompName, resourceOperationTest, rootResource, capabilityTypeName, reqName, reqRelationship, computeNodeName); - Resource compute = createComputeWithCapability(capabilityTypeName, computeNodeName, resourceOperationTest, rootResource); - - // resource1 - ComponentInstance myresourceInstance = buildResourceInstance(softwareComponentResource.getUniqueId(), "1", "tosca.nodes.test.root"); - - Either myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false); - - assertTrue("check instance added to service", myinstanceRes.isLeft()); - - // resource2 - ComponentInstance computeInstance = buildResourceInstance(compute.getUniqueId(), "2", "tosca.nodes.test.compute"); - ComponentInstance value1 = myinstanceRes.left().value(); - - Either computeInstTes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance, NodeTypeEnum.Resource, false); - assertTrue("check instance added to service", computeInstTes.isLeft()); - ComponentInstance value2 = computeInstTes.left().value(); - - RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair(); - relationPair.setRequirement(reqName); - relationPair.setCapability(capabilityTypeName); - - String capId = ""; - Map> capabilities = compute.getCapabilities(); - for (Map.Entry> entry : capabilities.entrySet()) { - capId = entry.getValue().get(0).getUniqueId(); - } - relationPair.setCapabilityUid(capId); - Map> requirements = softwareComponentResource.getRequirements(); - String reqId = ""; - for (Map.Entry> entry : requirements.entrySet()) { - reqId = entry.getValue().get(0).getUniqueId(); - } - relationPair.setRequirementUid(reqId); - relationPair.setRequirementOwnerId(value1.getUniqueId()); - relationPair.setCapabilityOwnerId(value2.getUniqueId()); - relationPair.setCapabilityUid(capId); - - Either connectResourcesInService = resourceInstanceOperation.connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(), relationPair); - - assertTrue("check relation created", connectResourcesInService.isLeft()); - - } - - @Test - @Ignore - public void addResourceInstancesResourceDeleted() { - - String rootName = "tosca.nodes.test.root"; - String softwareCompName = "tosca.nodes.test.softwarecomponent"; - String capabilityTypeName = "myCapability"; - String reqName = "host"; - String computeNodeName = "tosca.nodes.test.compute"; - String reqRelationship = "myRelationship"; - - ServiceMetadataData origService = createService("myService"); - String serviceId = (String) origService.getUniqueId(); - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - Resource rootResource = createRootResource(rootName, resourceOperationTest); - // Create Capability type - CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); - capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); - capabilityTypeOperationTest.createCapability(capabilityTypeName); - - Resource softwareComponentResource = createSoftwareComponentWithReq(softwareCompName, resourceOperationTest, rootResource, capabilityTypeName, reqName, reqRelationship, computeNodeName); - - deleteResource(softwareComponentResource.getUniqueId()); - - // resource1 - ComponentInstance myresourceInstance = buildResourceInstance(softwareComponentResource.getUniqueId(), "1", "tosca.nodes.test.root"); - - Either myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false); - - assertTrue("check instance not added to service", myinstanceRes.isRight()); - - } - - @Test - @Ignore - public void testDeploymentArtifactsOnRI() { - - String rootName = "tosca.nodes.test.root"; - - ServiceMetadataData origService = createService("testDeploymentArtifactsOnRI"); - String serviceId = (String) origService.getUniqueId(); - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - Resource rootResource = createRootResource(rootName, resourceOperationTest); - ArtifactDefinition addArtifactToResource = addArtifactToResource(USER_ID, rootResource.getUniqueId(), "myArtifact"); - - // resource1 - ComponentInstance myresourceInstance = buildResourceInstance(rootResource.getUniqueId(), "1", rootName); - - Either myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false); - - assertTrue("check instance added to service", myinstanceRes.isLeft()); - - Either, List>, TitanOperationStatus> resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, - NodeTypeEnum.Resource); - assertTrue(resourceInstancesOfService.isLeft()); - List resourceInstanceList = resourceInstancesOfService.left().value().left; - assertTrue(resourceInstanceList.size() == 1); - ComponentInstance resourceInstance = resourceInstanceList.get(0); - assertTrue(resourceInstance.getDeploymentArtifacts().size() == 1); - Map artifacts = resourceInstance.getDeploymentArtifacts(); - assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel())); - - ArtifactDefinition heatEnvArtifact = new ArtifactDefinition(addArtifactToResource); - heatEnvArtifact.setArtifactType("HEAT_ENV"); - heatEnvArtifact.setArtifactLabel(addArtifactToResource.getArtifactLabel() + "env"); - heatEnvArtifact.setUniqueId(null); - - Either either = artifactOperation.addHeatEnvArtifact(heatEnvArtifact, addArtifactToResource, resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true); - assertTrue(either.isLeft()); - - resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource); - assertTrue(resourceInstancesOfService.isLeft()); - resourceInstanceList = resourceInstancesOfService.left().value().left; - assertTrue(resourceInstanceList.size() == 1); - resourceInstance = resourceInstanceList.get(0); - assertTrue(resourceInstance.getDeploymentArtifacts().size() == 2); - artifacts = resourceInstance.getDeploymentArtifacts(); - assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel())); - assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel() + "env")); - ArtifactDefinition heatEnvFromRI = artifacts.get(addArtifactToResource.getArtifactLabel() + "env"); - assertEquals(addArtifactToResource.getUniqueId(), heatEnvFromRI.getGeneratedFromId()); - - List heatParameters = artifacts.get(addArtifactToResource.getArtifactLabel()).getListHeatParameters(); - assertNotNull(heatParameters); - assertTrue(heatParameters.size() == 1); - - List heatEnvParameters = heatEnvFromRI.getListHeatParameters(); - assertNotNull(heatEnvParameters); - assertTrue(heatEnvParameters.size() == 1); - - resourceOperation.deleteResource(rootResource.getUniqueId()); - - } - - @Test - @Ignore - public void deleteResourceInstanceWithArtifacts() { - String rootName = "tosca.nodes.test.root"; - - ServiceMetadataData origService = createService("deleteResourceInstanceWithArtifacts"); - String serviceId = (String) origService.getUniqueId(); - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - Resource rootResource = createRootResource(rootName, resourceOperationTest); - ArtifactDefinition addArtifactToResource = addArtifactToResource(USER_ID, rootResource.getUniqueId(), "myArtifact"); - - // resource1 - ComponentInstance myresourceInstance = buildResourceInstance(rootResource.getUniqueId(), "1", rootName); - - Either myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false); - - ArtifactDefinition heatEnvArtifact = new ArtifactDefinition(addArtifactToResource); - heatEnvArtifact.setArtifactType("HEAT_ENV"); - heatEnvArtifact.setArtifactLabel(addArtifactToResource.getArtifactLabel() + "env"); - heatEnvArtifact.setUniqueId(null); - - assertTrue("check instance added to service", myinstanceRes.isLeft()); - - Either, List>, TitanOperationStatus> resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, - NodeTypeEnum.Resource); - assertTrue(resourceInstancesOfService.isLeft()); - List resourceInstanceList = resourceInstancesOfService.left().value().left; - assertTrue(resourceInstanceList.size() == 1); - ComponentInstance resourceInstance = resourceInstanceList.get(0); - - Either either = artifactOperation.addHeatEnvArtifact(heatEnvArtifact, addArtifactToResource, resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true); - assertTrue(either.isLeft()); - ArtifactDefinition heatEnvDefinition = either.left().value(); - - // delete resource instance - Either deleteResourceInstance = resourceInstanceOperation.deleteComponentInstance(NodeTypeEnum.Service, serviceId, resourceInstance.getUniqueId()); - assertTrue(deleteResourceInstance.isLeft()); - - // check heat env deleted - ArtifactData artifactData = new ArtifactData(); - Either getDeletedArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), heatEnvDefinition.getUniqueId(), ArtifactData.class); - assertTrue(getDeletedArtifact.isRight()); - - // check heat is not deleted - getDeletedArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), addArtifactToResource.getUniqueId(), ArtifactData.class); - assertTrue(getDeletedArtifact.isLeft()); - - HeatParameterData heatParamData = new HeatParameterData(); - Either heatParamNode = titanDao.getNode(heatParamData.getUniqueIdKey(), addArtifactToResource.getHeatParameters().get(0).getUniqueId(), HeatParameterData.class); - assertTrue(heatParamNode.isLeft()); - - resourceOperation.deleteResource(rootResource.getUniqueId()); - - } - - @Test - @Ignore - public void getHeatEnvParams() { - String rootName = "tosca.nodes.test.root"; - - ServiceMetadataData origService = createService("getHeatEnvParams"); - String serviceId = (String) origService.getUniqueId(); - - ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); - - Resource rootResource = createRootResource(rootName, resourceOperationTest); - ArtifactDefinition addArtifactToResource = addArtifactToResource(USER_ID, rootResource.getUniqueId(), "myArtifact"); - - // resource1 - ComponentInstance myresourceInstance = buildResourceInstance(rootResource.getUniqueId(), "1", rootName); - - Either myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false); - - ArtifactDefinition heatEnvArtifact = new ArtifactDefinition(addArtifactToResource); - heatEnvArtifact.setArtifactType("HEAT_ENV"); - heatEnvArtifact.setArtifactLabel(addArtifactToResource.getArtifactLabel() + "env"); - heatEnvArtifact.setUniqueId(null); - - assertTrue("check instance added to service", myinstanceRes.isLeft()); - - Either, List>, TitanOperationStatus> resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, - NodeTypeEnum.Resource); - assertTrue(resourceInstancesOfService.isLeft()); - List resourceInstanceList = resourceInstancesOfService.left().value().left; - assertTrue(resourceInstanceList.size() == 1); - ComponentInstance resourceInstance = resourceInstanceList.get(0); - - Either either = artifactOperation.addHeatEnvArtifact(heatEnvArtifact, addArtifactToResource, resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true); - assertTrue(either.isLeft()); - ArtifactDefinition heatEnvDefinition = either.left().value(); - - // update value - String newHeatValue = "123"; - addHeatValueToEnv(heatEnvDefinition.getUniqueId(), addArtifactToResource.getListHeatParameters().get(0), newHeatValue); - - // check values received - - resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource); - assertTrue(resourceInstancesOfService.isLeft()); - resourceInstanceList = resourceInstancesOfService.left().value().left; - assertTrue(resourceInstanceList.size() == 1); - resourceInstance = resourceInstanceList.get(0); - assertTrue(resourceInstance.getDeploymentArtifacts().size() == 2); - Map artifacts = resourceInstance.getDeploymentArtifacts(); - assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel())); - assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel() + "env")); - - List heatParameters = artifacts.get(addArtifactToResource.getArtifactLabel()).getListHeatParameters(); - assertNotNull(heatParameters); - assertTrue(heatParameters.size() == 1); - HeatParameterDefinition heatParameterTemplate = heatParameters.get(0); - - List heatEnvParameters = artifacts.get(addArtifactToResource.getArtifactLabel() + "env").getListHeatParameters(); - assertNotNull(heatEnvParameters); - assertTrue(heatEnvParameters.size() == 1); - HeatParameterDefinition heatParameterEnv = heatEnvParameters.get(0); - - assertEquals(heatParameterEnv.getDefaultValue(), heatParameterTemplate.getCurrentValue()); - assertEquals(newHeatValue, heatParameterEnv.getCurrentValue()); - assertFalse(newHeatValue.equals(heatParameterTemplate.getCurrentValue())); - - resourceOperation.deleteResource(rootResource.getUniqueId()); - - } - - public void addHeatValueToEnv(String artifactId, HeatParameterDefinition heatDefinition, String value) { - HeatParameterValueData heatValueData = new HeatParameterValueData(); - heatValueData.setValue(value); - heatValueData.setUniqueId(artifactId + "." + heatDefinition.getName()); - Either createValue = titanDao.createNode(heatValueData, HeatParameterValueData.class); - assertTrue(createValue.isLeft()); - HeatParameterValueData value2 = createValue.left().value(); - HeatParameterData heatParamData = new HeatParameterData(heatDefinition); - Either createRelation = titanDao.createRelation(value2, heatParamData, GraphEdgeLabels.PROPERTY_IMPL, null); - assertTrue(createRelation.isLeft()); - Map props = new HashMap(); - props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), heatDefinition.getName()); - Either createRelation2 = titanDao.createRelation(new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId), value2, GraphEdgeLabels.PARAMETER_VALUE, props); - assertTrue(createRelation2.isLeft()); - titanDao.commit(); - - } - - public static String normaliseComponentName(String name) { - String[] split = splitComponentName(name); - StringBuffer sb = new StringBuffer(); - for (String splitElement : split) { - sb.append(splitElement); - } - return sb.toString(); - - } - - private static String[] splitComponentName(String name) { - String normalizedName = name.toLowerCase(); - normalizedName = COMPONENT_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); - String[] split = normalizedName.split(" "); - return split; - } - - public static String normaliseComponentInstanceName(String name) { - String[] split = splitComponentInstanceName(name); - StringBuffer sb = new StringBuffer(); - for (String splitElement : split) { - sb.append(splitElement); - } - return sb.toString(); - - } - - private static String[] splitComponentInstanceName(String name) { - String normalizedName = name.toLowerCase(); - normalizedName = COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); - String[] split = normalizedName.split(" "); - return split; - } - - private ArtifactDefinition addArtifactToResource(String userId, String resourceId, String artifactName) { - ArtifactDefinition artifactInfo = new ArtifactDefinition(); - - artifactInfo.setArtifactName(artifactName + ".yml"); - artifactInfo.setArtifactType("HEAT"); - artifactInfo.setDescription("hdkfhskdfgh"); - artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz"); - artifactInfo.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - - artifactInfo.setUserIdCreator(userId); - String fullName = "Jim H"; - artifactInfo.setUpdaterFullName(fullName); - long time = System.currentTimeMillis(); - artifactInfo.setCreatorFullName(fullName); - artifactInfo.setCreationDate(time); - artifactInfo.setLastUpdateDate(time); - artifactInfo.setUserIdLastUpdater(userId); - artifactInfo.setArtifactLabel(artifactName); - artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel())); - artifactInfo.setEsId(artifactInfo.getUniqueId()); - - List heatParams = new ArrayList(); - HeatParameterDefinition heatParam = new HeatParameterDefinition(); - heatParam.setCurrentValue("11"); - heatParam.setDefaultValue("22"); - heatParam.setDescription("desc"); - heatParam.setName("myParam"); - heatParam.setType("number"); - heatParams.add(heatParam); - artifactInfo.setListHeatParameters(heatParams); - - Either artifact = artifactOperation.addArifactToComponent(artifactInfo, resourceId, NodeTypeEnum.Resource, true, true); - assertTrue(artifact.isLeft()); - return artifact.left().value(); - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java deleted file mode 100644 index efd55d58fb..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java +++ /dev/null @@ -1,953 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -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.FilterKeyEnum; -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.Component; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.PropertyConstraint; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.api.IElementOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; -import org.openecomp.sdc.be.model.tosca.ToscaType; -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.resources.data.PropertyData; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import org.openecomp.sdc.be.resources.data.UserData; -import org.openecomp.sdc.be.resources.data.category.CategoryData; -import org.openecomp.sdc.be.resources.data.category.SubCategoryData; -import org.openecomp.sdc.be.unittests.utils.FactoryUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanGraphQuery; -import com.thinkaurelius.titan.core.TitanVertex; -import com.thinkaurelius.titan.graphdb.query.graph.GraphCentricQueryBuilder; - -import fj.data.Either; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:application-context-test.xml") -public class ResourceOperationTest extends ModelTestBase { - - private static Logger log = LoggerFactory.getLogger(ResourceOperationTest.class.getName()); - @javax.annotation.Resource(name = "titan-generic-dao") - private TitanGenericDao titanDao; - - @javax.annotation.Resource(name = "resource-operation") - private ResourceOperation resourceOperation; - - @javax.annotation.Resource(name = "property-operation") - private PropertyOperation propertyOperation; - - @javax.annotation.Resource(name = "lifecycle-operation") - private LifecycleOperation lifecycleOperation; - - @javax.annotation.Resource(name = "capability-operation") - private CapabilityOperation capabilityOperation; - - @javax.annotation.Resource(name = "capability-type-operation") - private CapabilityTypeOperation capabilityTypeOperation; - - private static String CATEGORY_NAME = "category/mycategory"; - private static String CATEGORY_NAME_UPDATED = "category1/updatedcategory"; - - @BeforeClass - public static void setupBeforeClass() { - - ModelTestBase.init(); - } - - public void setOperations(TitanGenericDao titanGenericDao, ResourceOperation resourceOperation, PropertyOperation propertyOperation) { - this.titanDao = titanGenericDao; - this.resourceOperation = resourceOperation; - this.propertyOperation = propertyOperation; - } - - @Test - public void dummyTest() { - - } - - private Resource buildResourceMetadata(String userId, String category, String resourceName, String resourceVersion) { - - Resource resource = new Resource(); - resource.setName(resourceName); - resource.setVersion(resourceVersion); - ; - resource.setDescription("description 1"); - resource.setAbstract(false); - resource.setCreatorUserId(userId); - resource.setContactId("contactId@sdc.com"); - resource.setVendorName("vendor 1"); - resource.setVendorRelease("1.0.0"); - resource.setToscaResourceName(resourceName); - String[] categoryArr = category.split("/"); - resource.addCategory(categoryArr[0], categoryArr[1]); - resource.setIcon("images/my.png"); - List tags = new ArrayList(); - tags.add("TAG1"); - tags.add("TAG2"); - resource.setTags(tags); - return resource; - } - - private UserData deleteAndCreateUser(String userId, String firstName, String lastName) { - UserData userData = new UserData(); - userData.setUserId(userId); - userData.setFirstName(firstName); - userData.setLastName(lastName); - - titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); - titanDao.createNode(userData, UserData.class); - titanDao.commit(); - - return userData; - } - - private void deleteAndCreateCategory(String category) { - String[] names = category.split("/"); - OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); - } - - public Resource createResource(String userId, String category, String resourceName, String resourceVersion, String parentResourceName, boolean isAbstract, boolean isHighestVersion) { - - String propName1 = "disk_size"; - String propName2 = "num_cpus"; - - List derivedFrom = new ArrayList(); - if (parentResourceName != null) { - derivedFrom.add(parentResourceName); - } - Resource resource = buildResourceMetadata(userId, category, resourceName, resourceVersion); - - resource.setAbstract(isAbstract); - resource.setHighestVersion(isHighestVersion); - - Map properties = new HashMap(); - - PropertyDefinition property1 = new PropertyDefinition(); - property1.setDefaultValue("10"); - property1.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node."); - property1.setType(ToscaType.INTEGER.name().toLowerCase()); - List constraints = new ArrayList(); - GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0"); - log.debug("{}", propertyConstraint1); - - constraints.add(propertyConstraint1); - - LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10"); - constraints.add(propertyConstraint2); - - property1.setConstraints(constraints); - - properties.put(propName1, property1); - - PropertyDefinition property2 = new PropertyDefinition(); - property2.setDefaultValue("2"); - property2.setDescription("Number of (actual or virtual) CPUs associated with the Compute node."); - property2.setType(ToscaType.INTEGER.name().toLowerCase()); - List constraints3 = new ArrayList(); - List range = new ArrayList(); - range.add("1"); - range.add("4"); - - InRangeConstraint propertyConstraint3 = new InRangeConstraint(range); - constraints3.add(propertyConstraint3); - // property2.setConstraints(constraints3); - property2.setConstraints(constraints3); - properties.put(propName2, property2); - - resource.setDerivedFrom(derivedFrom); - - resource.setProperties(convertMapToList(properties)); - - Either result = resourceOperation.createResource(resource, true); - - assertTrue(result.isLeft()); - Resource resultResource = result.left().value(); - - // assertEquals("check resource unique id", - // UniqueIdBuilder.buildResourceUniqueId(resourceName, - // resourceVersion), resultResource.getUniqueId()); - assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultResource.getLifecycleState()); - - // retrieve property from graph - String resourceId = resultResource.getUniqueId(); - // String resourceId = UniqueIdBuilder.buildResourceUniqueId( - // resource.getResourceName(), resource.getResourceVersion()); - - Either either = propertyOperation.getPropertyOfResource(propName1, resourceId); - - assertTrue(either.isLeft()); - PropertyDefinition propertyDefinition = either.left().value(); - assertEquals("check property default value", property1.getDefaultValue(), propertyDefinition.getDefaultValue()); - assertEquals("check property description", property1.getDescription(), propertyDefinition.getDescription()); - assertEquals("check property type", property1.getType(), propertyDefinition.getType()); - assertEquals("check property unique id", property1.getUniqueId(), propertyDefinition.getUniqueId()); - assertEquals("check property consitraints size", property1.getConstraints().size(), propertyDefinition.getConstraints().size()); - - return resultResource; - - } - - public Resource createResourceOverrideProperty(String userId, String category, String resourceName, String resourceVersion, String parentResourceName, boolean isAbstract, boolean isHighestVersion) { - - String propName1 = "disk_size"; - - List derivedFrom = new ArrayList(); - if (parentResourceName != null) { - derivedFrom.add(parentResourceName); - } - - Map properties = new HashMap(); - PropertyDefinition property1 = new PropertyDefinition(); - property1.setDefaultValue("9"); - property1.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node."); - property1.setType(ToscaType.INTEGER.name().toLowerCase()); - List constraints = new ArrayList(); - GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0"); - log.debug("{}", propertyConstraint1); - constraints.add(propertyConstraint1); - LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10"); - constraints.add(propertyConstraint2); - property1.setConstraints(constraints); - properties.put(propName1, property1); - - Resource resource = buildResourceMetadata(userId, category, resourceName, resourceVersion); - resource.setAbstract(isAbstract); - resource.setHighestVersion(isHighestVersion); - resource.setDerivedFrom(derivedFrom); - resource.setProperties(convertMapToList(properties)); - - Either result = resourceOperation.createResource(resource, true); - - assertTrue(result.isLeft()); - Resource resultResource = result.left().value(); - - // assertEquals("check resource unique id", - // UniqueIdBuilder.buildResourceUniqueId(resourceName, - // resourceVersion), resultResource.getUniqueId()); - assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultResource.getLifecycleState()); - - // retrieve property from graph - String resourceId = resultResource.getUniqueId(); - // String resourceId = UniqueIdBuilder.buildResourceUniqueId( - // resource.getResourceName(), resource.getResourceVersion()); - - Either either = propertyOperation.getPropertyOfResource(propName1, resourceId); - - assertTrue(either.isLeft()); - PropertyDefinition propertyDefinition = either.left().value(); - assertEquals("check property default value", property1.getDefaultValue(), propertyDefinition.getDefaultValue()); - assertEquals("check property description", property1.getDescription(), propertyDefinition.getDescription()); - assertEquals("check property type", property1.getType(), propertyDefinition.getType()); - assertEquals("check property unique id", property1.getUniqueId(), propertyDefinition.getUniqueId()); - assertEquals("check property consitraints size", property1.getConstraints().size(), propertyDefinition.getConstraints().size()); - - return resultResource; - } - - public static List convertMapToList(Map properties) { - if (properties == null) { - return null; - } - - List definitions = new ArrayList<>(); - for (Entry entry : properties.entrySet()) { - String name = entry.getKey(); - PropertyDefinition propertyDefinition = entry.getValue(); - propertyDefinition.setName(name); - definitions.add(propertyDefinition); - } - - return definitions; - } - - @Test - public void testFollowed() { - String rootName = "Root123"; - - String userId = "jh0003"; - String category = CATEGORY_NAME; - deleteAndCreateUser(userId, "first_" + userId, "last_" + userId); - deleteAndCreateCategory(category); - - Resource rootResource = createResource(userId, category, rootName, "1.0", null, false, true); - log.debug(" *** create **"); - log.debug("{}", rootResource); - String resourceId = rootResource.getUniqueId(); - - Set lifecycleStates = new HashSet(); - lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - Set lastStateStates = new HashSet(); - lastStateStates.add(LifecycleStateEnum.CERTIFIED); - - Either, StorageOperationStatus> followed = resourceOperation.getFollowed(userId, lifecycleStates, lastStateStates, false); - assertTrue(followed.isLeft()); - List list = followed.left().value(); - - assertEquals(1, list.size()); - resourceOperation.deleteResource(resourceId); - - followed = resourceOperation.getFollowed(userId, lifecycleStates, lastStateStates, false); - assertTrue(followed.isLeft()); - list = followed.left().value(); - assertTrue(list.isEmpty()); - - } - - @Ignore - @Test - public void testGetLatestVersion() { - String rootName = "Root123"; - - String userId = "jh0003"; - String category = "category/mycategory"; - deleteAndCreateUser(userId, "first_" + userId, "last_" + userId); - deleteAndCreateCategory(category); - - Either latestByName = resourceOperation.getLatestByName(rootName, true); - assertTrue(latestByName.isRight()); - assertEquals(StorageOperationStatus.NOT_FOUND, latestByName.right().value()); - - Resource rootResource = createResource(userId, category, rootName, "1.0", null, false, true); - - latestByName = resourceOperation.getLatestByName(rootName, true); - assertTrue(latestByName.isLeft()); - - Resource rootResourceHighest = createResource(userId, category, rootName, "1.3", null, false, true); - - latestByName = resourceOperation.getLatestByName(rootName, false); - assertTrue(latestByName.isLeft()); - assertEquals(rootResourceHighest.getUniqueId(), latestByName.left().value().getUniqueId()); - - resourceOperation.deleteResource(rootResource.getUniqueId()); - resourceOperation.deleteResource(rootResourceHighest.getUniqueId()); - } - - @Test - public void testOverrideResource() { - String rootName = "Root123"; - - String userId = "jh0003"; - String category = CATEGORY_NAME; - String updatedCategory = CATEGORY_NAME_UPDATED; - deleteAndCreateUser(userId, "first_" + userId, "last_" + userId); - deleteAndCreateCategory(category); - deleteAndCreateCategory(updatedCategory); - - Resource rootResource = createResource(userId, category, rootName, "1.1", null, false, true); - - rootResource.setCategories(null); - String[] updateArr = updatedCategory.split("/"); - rootResource.addCategory(updateArr[0], updateArr[1]); - List properties = rootResource.getProperties(); - PropertyDefinition propertyDefinition = findProperty(properties, "disk_size"); - - rootResource.setProperties(new ArrayList()); - propertyDefinition.setName("myProperty"); - rootResource.getProperties().add(propertyDefinition); - - Either overrideResource = resourceOperation.overrideResource(rootResource, rootResource, false); - - assertTrue(overrideResource.isLeft()); - Resource resourceAfter = overrideResource.left().value(); - assertEquals(1, resourceAfter.getProperties().size()); - - assertNotNull(findProperty(resourceAfter.getProperties(), "myProperty")); - assertEquals(1, resourceAfter.getCategories().size()); - assertEquals(1, resourceAfter.getCategories().get(0).getSubcategories().size()); - - assertEquals(updateArr[0], resourceAfter.getCategories().get(0).getName()); - assertEquals(updateArr[1], resourceAfter.getCategories().get(0).getSubcategories().get(0).getName()); - - resourceOperation.deleteResource(rootResource.getUniqueId()); - } - - @Test - public void testResourceWithCapabilities() { - String rootName = "Root123"; - - String userId = "jh0003"; - String category = CATEGORY_NAME; - String updatedCategory = CATEGORY_NAME_UPDATED; - deleteAndCreateUser(userId, "first_" + userId, "last_" + userId); - deleteAndCreateCategory(category); - deleteAndCreateCategory(updatedCategory); - - Resource rootResource = createResource(userId, category, rootName, "1.1", null, false, true); - - CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); - capabilityTypeDefinition.setType("tosca.capabilities.Container"); - PropertyDefinition delaultProperty1 = new PropertyDefinition(); - delaultProperty1.setName("def"); - delaultProperty1.setType("string"); - delaultProperty1.setDefaultValue("def"); - - PropertyDefinition delaultProperty2 = new PropertyDefinition(); - delaultProperty2.setName("host"); - delaultProperty2.setType("string"); - delaultProperty2.setDefaultValue("true"); - - HashMap props = new HashMap(); - props.put(delaultProperty1.getName(), delaultProperty1); - props.put(delaultProperty2.getName(), delaultProperty2); - capabilityTypeDefinition.setProperties(props); - - Either addTypeRes = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition); - assertTrue(addTypeRes.isLeft()); - - CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); - capabilityDefinition.setDescription("firstCap"); - capabilityDefinition.setName("firstCap"); - capabilityDefinition.setType("tosca.capabilities.Container"); - - List properties = new ArrayList(); - ComponentInstanceProperty propertyDefinition1 = new ComponentInstanceProperty(); - propertyDefinition1.setName("version"); - propertyDefinition1.setType("string"); - propertyDefinition1.setDefaultValue("007"); - properties.add(propertyDefinition1); - - ComponentInstanceProperty propertyDefinition2 = new ComponentInstanceProperty(); - propertyDefinition2.setName("host"); - propertyDefinition2.setType("string"); - propertyDefinition2.setDefaultValue("localhost"); - properties.add(propertyDefinition2); - - capabilityDefinition.setProperties(properties); - - Either addCapabilityRes = capabilityOperation.addCapability(rootResource.getUniqueId(), capabilityDefinition.getName(), capabilityDefinition); - assertTrue(addCapabilityRes.isLeft()); - - List newProperties = new ArrayList(); - propertyDefinition1 = new ComponentInstanceProperty(); - propertyDefinition1.setName("num_cpu"); - propertyDefinition1.setType("string"); - propertyDefinition1.setDefaultValue("4"); - newProperties.add(propertyDefinition1); - - propertyDefinition2 = new ComponentInstanceProperty(); - propertyDefinition2.setName("port"); - propertyDefinition2.setType("string"); - propertyDefinition2.setDefaultValue("4444"); - newProperties.add(propertyDefinition2); - - CapabilityDefinition addedCap = addCapabilityRes.left().value(); - - Either, StorageOperationStatus> updatePropertiesRes = capabilityOperation.updatePropertiesOfCapability(addedCap.getUniqueId(), addedCap.getType(), newProperties); - assertTrue(updatePropertiesRes.isLeft()); - - PropertyDefinition invalidProperty = new PropertyDefinition(); - invalidProperty.setName("port"); - invalidProperty.setType("rrr"); - invalidProperty.setDefaultValue("666"); - newProperties.add(invalidProperty); - - Either, StorageOperationStatus> updatePropertiesInvalidRes = capabilityOperation.updatePropertiesOfCapability(addedCap.getUniqueId(), addedCap.getType(), newProperties); - assertTrue(updatePropertiesInvalidRes.isRight()); - - Either getCapabilityRes = capabilityOperation.getCapability(addedCap.getUniqueId()); - assertTrue(getCapabilityRes.isLeft()); - - Either>, TitanOperationStatus> deletePropertiesOfCapabilityRes = capabilityOperation.deletePropertiesOfCapability(addedCap.getUniqueId()); - assertTrue(deletePropertiesOfCapabilityRes.isLeft()); - - StorageOperationStatus deleteCapabilityRes = capabilityOperation.deleteCapabilityFromGraph(addedCap.getUniqueId()); - assertTrue(deleteCapabilityRes.equals(StorageOperationStatus.OK)); - - getCapabilityRes = capabilityOperation.getCapability(addedCap.getUniqueId()); - assertTrue(getCapabilityRes.isRight() && getCapabilityRes.right().value().equals(StorageOperationStatus.NOT_FOUND)); - - resourceOperation.deleteResource(rootResource.getUniqueId()); - } - - private PropertyDefinition findProperty(List properties, String propName) { - - if (properties == null) { - return null; - } - - for (PropertyDefinition propertyDefinition : properties) { - String name = propertyDefinition.getName(); - if (name.equals(propName)) { - return propertyDefinition; - } - } - - return null; - } - - @Test - public void testOverrideResourceNotExist() { - String rootName = "Root123"; - - String userId = "jh0003"; - String category = CATEGORY_NAME; - deleteAndCreateUser(userId, "first_" + userId, "last_" + userId); - deleteAndCreateCategory(category); - - Resource rootResource = buildResourceMetadata(userId, category, rootName, "1.1"); - rootResource.setUniqueId(UniqueIdBuilder.buildResourceUniqueId()); - - Either overrideResource = resourceOperation.overrideResource(rootResource, rootResource, false); - - assertTrue(overrideResource.isRight()); - - } - - @Ignore - @Test - public void testCatalogResource() { - String resName = "myResource"; - String userId = "jh0003"; - String category = CATEGORY_NAME; - deleteAndCreateCategory(category); - // resourceOperation.deleteResource(UniqueIdBuilder.buildResourceUniqueId(resName,"0.1")); - Resource newResource = createResource(userId, category, resName, "0.1", null, false, true); - String resourceId = newResource.getUniqueId(); - - Map propertiesToMatch = new HashMap<>(); - propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); - - Either, StorageOperationStatus> catalog = resourceOperation.getCatalogData(propertiesToMatch, false); - assertTrue(catalog.isLeft()); - Set catalogSet = catalog.left().value(); - Set idSet = new HashSet<>(); - for (Resource resource : catalogSet) { - idSet.add(resource.getUniqueId()); - } - assertTrue(idSet.contains(resourceId)); - resourceOperation.deleteResource(resourceId); - } - - @Ignore - @Test - public void testTesterFollowed() { - String rootName = "Test1"; - String rootName2 = "Test2"; - String rootName3 = "Test3"; - String userId = "jh0003"; - String testerUserId = "tt0004"; - String category = CATEGORY_NAME; - deleteAndCreateUser(testerUserId, "tester", "last"); - deleteAndCreateCategory(category); - - String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User); - Either findUser = titanDao.getNode(key, userId, UserData.class); - User adminUser = OperationTestsUtil.convertUserDataToUser(findUser.left().value()); - Either findTesterUser = titanDao.getNode(key, testerUserId, UserData.class); - User testerUser = OperationTestsUtil.convertUserDataToUser(findTesterUser.left().value()); - - // Create 3 new resources - Resource resultResource = createResource(userId, category, rootName, "1.0", null, false, true); - log.debug("{}", resultResource); - String resourceId = resultResource.getUniqueId(); - Resource resultResource2 = createResource(userId, category, rootName2, "1.0", null, false, true); - log.debug("{}", resultResource2); - String resourceId2 = resultResource2.getUniqueId(); - Resource resultResource3 = createResource(userId, category, rootName3, "1.0", null, false, true); - log.debug("{}", resultResource3); - String resourceId3 = resultResource3.getUniqueId(); - - // update 1 resource to READY_FOR_CERTIFICATION - Either certReqResponse = (Either) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, resultResource, adminUser, adminUser, false); - Resource RFCResource = certReqResponse.left().value(); - assertEquals(RFCResource.getLifecycleState(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - - // update 1 resource to CERTIFICATION_IN_PROGRESS - Either startCertificationResponse = (Either) lifecycleOperation.startComponentCertification(NodeTypeEnum.Resource, resultResource2, testerUser, adminUser, false); - Resource IPResource = startCertificationResponse.left().value(); - assertEquals(IPResource.getLifecycleState(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - - Set lifecycleStates = new HashSet(); - lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - - Either, StorageOperationStatus> resources = resourceOperation.getTesterFollowed(testerUserId, lifecycleStates, false); - - assertTrue(resources.isLeft()); - List result = resources.left().value(); - - List idSet = new ArrayList(); - for (Resource resource : result) { - idSet.add(resource.getUniqueId()); - } - assertTrue(idSet.contains(resourceId)); - assertTrue(idSet.contains(resourceId2)); - assertFalse(idSet.contains(resourceId3)); - resourceOperation.deleteResource(resourceId); - resourceOperation.deleteResource(resourceId2); - resourceOperation.deleteResource(resourceId3); - - } - - @Test - public void getVersionListNotDeleted() { - String resName = "myResource"; - String userId = "jh0003"; - String category = CATEGORY_NAME; - deleteAndCreateCategory(category); - - Resource newResource = createResource(userId, category, resName, "0.1", null, false, true); - String resourceId1 = newResource.getUniqueId(); - - User admin = new User("j", "h", userId, null, "ADMIN", System.currentTimeMillis()); - Either checkoutResource = (Either) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, newResource, admin, admin, false); - assertTrue(checkoutResource.isLeft()); - Resource newResource2 = checkoutResource.left().value(); - String resourceId2 = newResource2.getUniqueId(); - - Resource newResource3 = createResource(userId, category, resName, "0.1", null, false, true); - String resourceId3 = newResource3.getUniqueId(); - - Either, TitanOperationStatus> versionList = resourceOperation.getVersionList(NodeTypeEnum.Resource, "0.2", newResource2.getUUID(), newResource2.getSystemName(), ResourceMetadataData.class); - assertTrue(versionList.isLeft()); - Map versionMap = versionList.left().value(); - - assertTrue(versionMap.size() == 2); - assertTrue(versionMap.containsValue(resourceId1)); - assertTrue(versionMap.containsValue(resourceId2)); - assertFalse(versionMap.containsValue(resourceId3)); - - Either deleteResource = resourceOperation.deleteResource(resourceId1); - assertTrue(deleteResource.isLeft()); - deleteResource = resourceOperation.deleteResource(resourceId2); - assertTrue(deleteResource.isLeft()); - deleteResource = resourceOperation.deleteResource(resourceId3); - assertTrue(deleteResource.isLeft()); - - } - - @Test - public void getVersionListWithDeleted() { - String resName = "myResource"; - String userId = "jh0003"; - String category = CATEGORY_NAME; - deleteAndCreateCategory(category); - - Resource newResource = createResource(userId, category, resName, "0.1", null, false, true); - String resourceId1 = newResource.getUniqueId(); - - User admin = new User("j", "h", userId, null, "ADMIN", System.currentTimeMillis()); - Either checkoutResource = (Either) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, newResource, admin, admin, false); - assertTrue(checkoutResource.isLeft()); - Resource newResource2 = checkoutResource.left().value(); - String resourceId2 = newResource2.getUniqueId(); - - Either resource = resourceOperation.getResource(resourceId1, false); - assertTrue(resource.isLeft()); - Either markResourceToDelete = resourceOperation.markComponentToDelete(resource.left().value(), false); - assertTrue(markResourceToDelete.isLeft()); - - Either, TitanOperationStatus> versionList = resourceOperation.getVersionList(NodeTypeEnum.Resource, "0.2", newResource2.getUUID(), newResource2.getSystemName(), ResourceMetadataData.class); - - assertTrue(versionList.isLeft()); - Map versionMap = versionList.left().value(); - - assertTrue(versionMap.size() == 1); - assertFalse(versionMap.containsValue(resourceId1)); - assertTrue(versionMap.containsValue(resourceId2)); - - Either deleteResource = resourceOperation.deleteResource(resourceId1); - assertTrue(deleteResource.isLeft()); - deleteResource = resourceOperation.deleteResource(resourceId2); - assertTrue(deleteResource.isLeft()); - } - - // @Test - // public void getVersionListAfterCertify(){ - // String resName = "myResource"; - // String category = CATEGORY_NAME; - // deleteAndCreateCategory(category); - // - // Resource newResource = createResource(userId, category, resName, "1.0", - // null, false, true); - // String resourceId1 = newResource.getUniqueId(); - // - // User admin = new User("j", "h", userId, null, "ADMIN", - // System.currentTimeMillis()); - // Either checkoutResource = - // lifecycleOperation.checkoutResource(newResource, admin, admin, false); - // assertTrue(checkoutResource.isLeft()); - // Resource resourceToDelete = checkoutResource.left().value(); - // String deletedId = resourceToDelete.getUniqueId(); - // - // Either resource = - // resourceOperation.getResource(deletedId, false); - // assertTrue(resource.isLeft()); - // Either markResourceToDelete = - // resourceOperation.markResourceToDelete(resource.left().value(), false); - // assertTrue(markResourceToDelete.isLeft()); - // - // - // Resource newResource2 = createResource(userId, category, resName, "2.0", - // null, false, true); - // String resourceId2 = newResource2.getUniqueId(); - // - // - // Either, TitanOperationStatus> versionList = - // resourceOperation - // .getVersionList(NodeTypeEnum.Resource, "2.0", - // newResource2.getUUID(), newResource2.getSystemName(), - // ResourceData.class); - // assertTrue(versionList.isLeft()); - // Map versionMap = versionList.left().value(); - // - // assertTrue(versionMap.size()==2); - // assertTrue(versionMap.containsValue(resourceId1)); - // assertTrue(versionMap.containsValue(resourceId2)); - // - // assertFalse(versionMap.containsValue(deletedId)); - // - // Either deleteResource = - // resourceOperation.deleteResource(resourceId1); - // assertTrue(deleteResource.isLeft()); - // deleteResource = resourceOperation.deleteResource(resourceId2); - // assertTrue(deleteResource.isLeft()); - // deleteResource = resourceOperation.deleteResource(deletedId); - // assertTrue(deleteResource.isLeft()); - // - // } - -// @Test - public void testDerviedPropertiesInResource() { - - try { - String userId = "jh0003"; - String category = CATEGORY_NAME; - - deleteAndCreateUser(userId, "first_" + userId, "last_" + userId); - deleteAndCreateCategory(category); - - Resource createResource1 = createResource(userId, category, "myResource1", "0.1", null, true, false); - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(createResource1.getUniqueId()); - resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - Either updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - String json = gson.toJson(createResource1); - log.debug(json); - - Resource createResource2 = createResourceOverrideProperty(userId, category, "myResource2", "0.1", createResource1.getName(), true, false); - - json = gson.toJson(createResource2); - log.debug(json); - - List propList1 = new ArrayList<>(); - TitanOperationStatus findAllResourcePropertiesRecursively1 = propertyOperation.findAllResourcePropertiesRecursively(createResource1.getUniqueId(), propList1); - assertEquals("check search properties succeed", findAllResourcePropertiesRecursively1, TitanOperationStatus.OK); - - List propList2 = new ArrayList<>(); - TitanOperationStatus findAllResourcePropertiesRecursively2 = propertyOperation.findAllResourcePropertiesRecursively(createResource2.getUniqueId(), propList2); - assertEquals("check search properties succeed", findAllResourcePropertiesRecursively2, TitanOperationStatus.OK); - // checks that properties with the same names have been overrided properly - // the sizes of the property lists should be same (we have 2 properties "disk_size" and "num_cpus" only) - assertEquals("check number of properties", propList1.size(), propList2.size()); - // checks that not overrided property default value in child's list equals to the same property of the parent - assertEquals("check values of properties are the same", propList1.stream().filter(prop->prop.getName().equals("num_cpus")).findAny().get().getDefaultValue() - , propList2.stream().filter(prop->prop.getName().equals("num_cpus")).findAny().get().getDefaultValue()); - // checks that an overrided property default value in child's list doesn't equal to the same property of the parent - assertTrue(!propList1.stream().filter(prop->prop.getName().equals("disk_size")).findAny().get().getDefaultValue().equals( - propList2.stream().filter(prop->prop.getName().equals("disk_size")).findAny().get().getDefaultValue())); - - resourceOperation.deleteResource(createResource1.getUniqueId()); - resourceOperation.deleteResource(createResource2.getUniqueId()); - - } finally { - - } - - /* - * "properties": { "disk_size": { "constraints": [ { "greaterThan": "0" }, { "lessOrEqual": "10" } ], "uniqueId": "res_myresource1.0.1.disk_size", "type": "integer", "required": false, "defaultValue": "10", "description": - * "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node." , "isPassword": false }, "num_cpus": { "constraints": [ { "inRange": [ "1", "4" ] } ], "uniqueId": "res_myresource1.0.1.num_cpus", "type": - * "integer", "required": false, "defaultValue": "2", "description": "Number of (actual or virtual) CPUs associated with the Compute node." , "isPassword": false } }, - */ - } - - @Test - public void getFilteredComponentsTest() { - - TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); - IElementOperation elementOperation = Mockito.mock(ElementOperation.class); - IElementOperation prevElementOperation = this.resourceOperation.getElementOperation(); - this.resourceOperation.setElementOperation(elementOperation); - this.resourceOperation.setTitanGenericDao(titanGenericDao); - - String subCategoryName = "Database"; - String categoryName = "Generic"; - String resourceTypeName = "VFC"; - - Map filters = new HashMap<>(); - filters.put(FilterKeyEnum.CATEGORY, categoryName); - filters.put(FilterKeyEnum.SUB_CATEGORY, subCategoryName); - filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeName); - - prepareMocks(titanGenericDao, elementOperation, subCategoryName, categoryName, resourceTypeName); - try{ - //search by category, subCategory and resourceType - Either, StorageOperationStatus> getFilteredComponentsRes = - this.resourceOperation.getFilteredComponents(filters, false); - assertTrue(getFilteredComponentsRes.isLeft()); - - //search by category and resourceType - filters.remove(FilterKeyEnum.SUB_CATEGORY); - getFilteredComponentsRes = - this.resourceOperation.getFilteredComponents(filters, false); - assertTrue(getFilteredComponentsRes.isLeft()); - - //search by resourceType - filters.remove(FilterKeyEnum.CATEGORY); - getFilteredComponentsRes = - this.resourceOperation.getFilteredComponents(filters, false); - assertTrue(getFilteredComponentsRes.isLeft()); - }finally{ - this.resourceOperation.setTitanGenericDao(this.titanDao); - this.resourceOperation.setElementOperation(prevElementOperation); - } - - - } - - @SuppressWarnings("unchecked") - private void prepareMocks(TitanGenericDao titanGenericDao, IElementOperation elementOperation, String subCategoryName, String categoryName, String resourceTypeName) { - //prepare resource - ResourceMetadataData resourceMeta = FactoryUtils.createResourceByType(resourceTypeName); - ImmutablePair resourcePair = new ImmutablePair(resourceMeta, new GraphEdge()); - List> resourcePairList = new ArrayList<>(); - resourcePairList.add(resourcePair); - Either>, TitanOperationStatus> parentNodes = Either.left(resourcePairList); - Map resourceProps = new HashMap(); - resourceProps.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceTypeName); - resourceProps.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - List resourceList = new ArrayList<>(); - resourceList.add(resourceMeta); - Either, TitanOperationStatus> getResources = Either.left(resourceList); - - //prepare subcategory - SubCategoryData subCategoryData = new SubCategoryData(NodeTypeEnum.ResourceSubcategory); - subCategoryData.getSubCategoryDataDefinition().setName(subCategoryName); - subCategoryData.getSubCategoryDataDefinition().setUniqueId(UUID.randomUUID().toString()); - GraphEdge graphEdge = new GraphEdge(); - Optional> subCategory = Optional.of(new ImmutablePair<>(subCategoryData, graphEdge)); - List> subcategoriesList = new ArrayList<>(); - subcategoriesList.add(subCategory.get()); - Either>, TitanOperationStatus> subcategories = Either.left(subcategoriesList); - - //prepare category - CategoryData categoryData = new CategoryData(NodeTypeEnum.ResourceNewCategory); - categoryData.getCategoryDataDefinition().setUniqueId(UUID.randomUUID().toString()); - categoryData.getCategoryDataDefinition().setName(categoryName); - Either categoryResult = Either.left(categoryData); - List categoryDataList = new ArrayList<>(); - categoryDataList.add(categoryResult.left().value()); - Either, TitanOperationStatus> categoryNode = - Either.left(new ImmutablePair(categoryData, new GraphEdge())); - Map categoryProps = new HashMap<>(); - categoryProps.put(GraphPropertiesDictionary.NAME.getProperty(), categoryName); - - //prepare graph - Either graphResult = Either.left(Mockito.mock(TitanGraph.class)); - TitanGraph titanGraph = graphResult.left().value(); - TitanVertex vertex = Mockito.mock(TitanVertex.class); - Iterator iterCreator = Mockito.mock(Iterator.class); - Vertex vertexCreator = Mockito.mock(Vertex.class); - Edge edge = Mockito.mock(Edge.class); - List verteciesList= new ArrayList<>(); - verteciesList.add(vertex); - Iterable vertecies = new ArrayList<>(verteciesList); - @SuppressWarnings("rawtypes") - TitanGraphQuery qBuilder = Mockito.mock(GraphCentricQueryBuilder.class); - - when(titanGenericDao.getByCriteria(NodeTypeEnum.ResourceNewCategory, categoryProps, CategoryData.class)).thenReturn(Either.left(categoryDataList)); - when(elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class)).thenReturn(categoryResult); - when(titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), categoryData.getCategoryDataDefinition().getUniqueId(), - GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class)).thenReturn(subcategories); - when(titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), null, - GraphEdgeLabels.CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class)).thenReturn(subcategories); - when(titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceSubcategory), (String) subCategoryData.getSubCategoryDataDefinition().getUniqueId(), - GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceNewCategory, CategoryData.class)).thenReturn(categoryNode); - when(titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceSubcategory), subCategoryData.getSubCategoryDataDefinition().getUniqueId(), - GraphEdgeLabels.CATEGORY, NodeTypeEnum.Resource, ResourceMetadataData.class)).thenReturn(parentNodes); - when(titanGenericDao.getGraph()).thenReturn(graphResult); - when(vertex.edges(Direction.IN, GraphEdgeLabels.CREATOR.name())).thenReturn(iterCreator); - when(vertex.edges(Direction.IN, GraphEdgeLabels.LAST_MODIFIER.name())).thenReturn(iterCreator); - when(iterCreator.hasNext()).thenReturn(true); - when(iterCreator.next()).thenReturn(edge); - when(edge.outVertex()).thenReturn(vertexCreator); - when(titanGenericDao.getProperties(vertex)).thenReturn(resourceProps); - when(titanGraph.query()).thenReturn(qBuilder); - when(qBuilder.has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceMeta.getUniqueId())).thenReturn(qBuilder); - when(qBuilder.vertices()).thenReturn(vertecies); - when(titanGenericDao.getByCriteria(NodeTypeEnum.Resource, resourceProps, ResourceMetadataData.class)) - .thenReturn(getResources); - } - -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java deleted file mode 100644 index 52686fbfa9..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java +++ /dev/null @@ -1,884 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -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.ArtifactDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.DistributionStatusEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; -import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; -import org.openecomp.sdc.be.resources.data.ArtifactData; -import org.openecomp.sdc.be.resources.data.UserData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.thinkaurelius.titan.core.TitanGraph; -//import com.tinkerpop.blueprints.Vertex; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:application-context-test.xml") -public class ServiceOperationTest extends ModelTestBase { - - @javax.annotation.Resource(name = "titan-generic-dao") - private TitanGenericDao titanDao; - - @javax.annotation.Resource(name = "service-operation") - private ServiceOperation serviceOperation; - - @javax.annotation.Resource - private IGraphLockOperation graphLockOperation; - - @javax.annotation.Resource - private ArtifactOperation artifactOperation; - - @javax.annotation.Resource(name = "requirement-operation") - private RequirementOperation requirementOperation; - - @javax.annotation.Resource(name = "resource-operation") - private ResourceOperation resourceOperation; - - @javax.annotation.Resource(name = "property-operation") - private PropertyOperation propertyOperation; - - @javax.annotation.Resource(name = "capability-operation") - private CapabilityOperation capabilityOperation; - - @javax.annotation.Resource(name = "capability-type-operation") - private CapabilityTypeOperation capabilityTypeOperation; - - @javax.annotation.Resource(name = "component-instance-operation") - private ComponentInstanceOperation resourceInstanceOperation; - - @javax.annotation.Resource(name = "lifecycle-operation") - private LifecycleOperation lifecycleOperation; - - private static Logger log = LoggerFactory.getLogger(ServiceOperation.class.getName()); - private static String USER_ID = "muUserId"; - private static String CATEGORY_NAME = "category/mycategory"; - - @BeforeClass - public static void setupBeforeClass() { - // ExternalConfiguration.setAppName("catalog-model"); - // String appConfigDir = "src/test/resources/config/catalog-model"; - // ConfigurationSource configurationSource = new - // FSConfigurationSource(ExternalConfiguration.getChangeListener(), - // appConfigDir); - - // configurationManager = new ConfigurationManager(new - // ConfigurationSource() { - // - // @Override - // public T getAndWatchConfiguration(Class className, - // ConfigurationListener configurationListener) { - // // TODO Auto-generated method stub - // return null; - // } - // - // @Override - // public void addWatchConfiguration(Class className, - // ConfigurationListener configurationListener) { - // // TODO Auto-generated method stub - // - // } - // }); - - // String appConfigDir = "src/test/resources/config"; - // ConfigurationSource configurationSource = new - // FSConfigurationSource(ExternalConfiguration.getChangeListener(), - // appConfigDir); - // configurationManager = new ConfigurationManager(configurationSource); - // - // Configuration configuration = new Configuration(); - // configuration.setTitanInMemoryGraph(true); - //// configuration.setTitanInMemoryGraph(false); - //// configuration.setTitanCfgFile("C:\\Dev\\d2\\D2-SDnC\\catalog-be\\src\\main\\resources\\config\\titan.properties"); - // - // configurationManager.setConfiguration(configuration); - - ModelTestBase.init(); - } - - @Before - public void createUserAndCategory() { - deleteAndCreateCategory(CATEGORY_NAME); - deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID, null); - } - - @Test - public void dummyTest() { - - } - - @Test - public void testCreateService() { - String category = CATEGORY_NAME; - String serviceName = "servceTest"; - String serviceVersion = "0.1"; - String userId = USER_ID; - Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); - log.debug(" *** create **"); - log.debug("{}", serviceAfterSave); - String uniqueId = serviceAfterSave.getUniqueId(); - - Either serviceGet = serviceOperation.getService(uniqueId); - assertTrue(serviceGet.isLeft()); - log.debug(" *** get **"); - log.debug("{}", serviceGet.left().value()); - - Either serviceDelete = serviceOperation.deleteService(uniqueId); - - assertTrue(serviceDelete.isLeft()); - log.debug(" *** delete **"); - log.debug("{}", serviceDelete.left().value()); - - Either, TitanOperationStatus> artifacts = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, null, ArtifactData.class); - assertTrue(artifacts.isRight()); - assertEquals(TitanOperationStatus.NOT_FOUND, artifacts.right().value()); - - serviceOperation.deleteService(serviceAfterSave.getUniqueId()); - } - - @Test - public void testUtilsService() { - String category = CATEGORY_NAME; - String serviceName = "servceTest2"; - String serviceVersion = "0.1"; - String userId = USER_ID; - Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); - log.debug(" *** create **"); - log.debug("{}", serviceAfterSave); - String uniqueId = serviceAfterSave.getUniqueId(); - - boolean canWorkOnComponent = ComponentValidationUtils.canWorkOnComponent(serviceAfterSave, userId); - assertTrue(canWorkOnComponent); - - StorageOperationStatus lockComponent = graphLockOperation.lockComponent(uniqueId, NodeTypeEnum.Service); - assertEquals(StorageOperationStatus.OK, lockComponent); - - lockComponent = graphLockOperation.unlockComponent(uniqueId, NodeTypeEnum.Service); - assertEquals(StorageOperationStatus.OK, lockComponent); - - Either serviceDelete = serviceOperation.deleteService(uniqueId); - } - - @Test - public void testInstanceCounter() { - String category = CATEGORY_NAME; - String serviceName = "servceTest2"; - String serviceVersion = "0.1"; - String userId = USER_ID; - Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); - log.debug(" *** create **"); - log.debug("{}", serviceAfterSave); - - Either counter = serviceOperation.increaseAndGetComponentInstanceCounter(serviceAfterSave.getUniqueId(), NodeTypeEnum.Service, false); - assertTrue(counter.isLeft()); - assertEquals(new Integer(1), (Integer) counter.left().value()); - - counter = serviceOperation.increaseAndGetComponentInstanceCounter(serviceAfterSave.getUniqueId(), NodeTypeEnum.Service, false); - assertTrue(counter.isLeft()); - assertEquals(new Integer(2), (Integer) counter.left().value()); - Either serviceDelete = serviceOperation.deleteService(serviceAfterSave.getUniqueId()); - } - - @Test - public void testAddArtifactToService() { - String category = CATEGORY_NAME; - String serviceName = "servceTest2"; - String serviceVersion = "0.1"; - String userId = USER_ID; - Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); - log.debug("{}", serviceAfterSave); - String serviceId = serviceAfterSave.getUniqueId(); - - ArtifactDefinition artifactInfo = addArtifactToService(userId, serviceId, "install_apache"); - - Either service = serviceOperation.getService(serviceId); - assertTrue(service.isLeft()); - - Map artifacts = service.left().value().getArtifacts(); - assertEquals(1, artifacts.size()); - - for (Map.Entry entry : artifacts.entrySet()) { - String artifactId = entry.getValue().getUniqueId(); - String description = entry.getValue().getDescription(); - assertEquals("hdkfhskdfgh", description); - - artifactInfo.setDescription("jghlsk new desfnjdh"); - - artifactOperation.updateArifactOnResource(artifactInfo, serviceId, artifactId, NodeTypeEnum.Service, false); - } - - service = serviceOperation.getService(serviceId); - assertTrue(service.isLeft()); - - artifacts = service.left().value().getArtifacts(); - for (Map.Entry entry : artifacts.entrySet()) { - String artifactId = entry.getValue().getUniqueId(); - String description = entry.getValue().getDescription(); - assertEquals("jghlsk new desfnjdh", description); - - artifactOperation.removeArifactFromResource(serviceId, artifactId, NodeTypeEnum.Service, true, false); - } - service = serviceOperation.getService(serviceId); - assertTrue(service.isLeft()); - - artifacts = service.left().value().getArtifacts(); - assertEquals(0, artifacts.size()); - - Either serviceDelete = serviceOperation.deleteService(serviceId); - - Either, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, null, ArtifactData.class); - assertTrue(byCriteria.isRight()); - assertEquals(TitanOperationStatus.NOT_FOUND, byCriteria.right().value()); - - serviceOperation.deleteService(serviceAfterSave.getUniqueId()); - - } - - private ArtifactDefinition addArtifactToService(String userId, String serviceId, String artifactName) { - ArtifactDefinition artifactInfo = new ArtifactDefinition(); - - artifactInfo.setArtifactName(artifactName + ".sh"); - artifactInfo.setArtifactType("SHELL"); - artifactInfo.setDescription("hdkfhskdfgh"); - artifactInfo.setPayloadData("UEsDBAoAAAAIAAeLb0bDQz"); - - artifactInfo.setUserIdCreator(userId); - String fullName = "Jim H"; - artifactInfo.setUpdaterFullName(fullName); - long time = System.currentTimeMillis(); - artifactInfo.setCreatorFullName(fullName); - artifactInfo.setCreationDate(time); - artifactInfo.setLastUpdateDate(time); - artifactInfo.setUserIdLastUpdater(userId); - artifactInfo.setArtifactLabel(artifactName); - artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(serviceId, artifactInfo.getArtifactLabel())); - - Either artifact = artifactOperation.addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true); - assertTrue(artifact.isLeft()); - return artifactInfo; - } - - @Test - public void testFollowed() { - String category = CATEGORY_NAME; - String serviceName = "servceTest2"; - String serviceVersion = "0.1"; - String userId = USER_ID; - Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); - log.debug("{}", serviceAfterSave); - String serviceId = serviceAfterSave.getUniqueId(); - - Set lifecycleStates = new HashSet(); - lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - Set lastStateStates = new HashSet(); - lastStateStates.add(LifecycleStateEnum.CERTIFIED); - - Either, StorageOperationStatus> followed = serviceOperation.getFollowed(userId, lifecycleStates, lastStateStates, false); - assertTrue(followed.isLeft()); - List list = followed.left().value(); - assertEquals(1, list.size()); - serviceOperation.deleteService(serviceId); - } - - @Test - public void testUpdateService() { - String category = CATEGORY_NAME; - String serviceName = "12"; - String serviceVersion = "0.1"; - String userId = USER_ID; - Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); - log.debug("{}", serviceAfterSave); - String serviceId = serviceAfterSave.getUniqueId(); - serviceAfterSave.setDescription("new description"); - Either updateService = serviceOperation.updateService(serviceAfterSave, false); - assertTrue(updateService.isLeft()); - - titanDao.commit(); - - Either serviceAfterUpdate = serviceOperation.getService(serviceId, false); - assertTrue(serviceAfterUpdate.isLeft()); - - serviceOperation.deleteService(serviceId); - assertEquals("new description", serviceAfterUpdate.left().value().getDescription()); - - } - - public Service createService(String userId, String category, String serviceName, String serviceVersion, boolean isHighestVersion) { - - Service service = buildServiceMetadata(userId, category, serviceName, serviceVersion); - - service.setHighestVersion(isHighestVersion); - - Either result = serviceOperation.createService(service, true); - - log.info(result.toString()); - assertTrue(result.isLeft()); - Service resultService = result.left().value(); - - // assertEquals("check resource unique id", - // UniqueIdBuilder.buildServiceUniqueId(serviceName, serviceVersion), - // resultService.getUniqueId()); - assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultService.getLifecycleState()); - - return resultService; - } - - // @Test - public void testCloneFullService() { - // try{ - String userId = USER_ID; - Service origService = createService(userId, CATEGORY_NAME, "my-service", "1.0", true); - - // add artifacts - addArtifactToService(userId, origService.getUniqueId(), "install_apache"); - addArtifactToService(userId, origService.getUniqueId(), "start_apache"); - - // add resource instances - ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest(); - riTest.setOperations(titanDao, capabilityTypeOperation, requirementOperation, capabilityOperation, resourceOperation, propertyOperation, resourceInstanceOperation); - riTest.addResourceInstancesAndRelation(origService.getUniqueId()); - - Either service2 = serviceOperation.getService(origService.getUniqueId(), false); - assertTrue(service2.isLeft()); - origService = service2.left().value(); - - Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); - String json = prettyGson.toJson(origService); - log.debug(json); - - Service fullService = origService; - - Either createService = serviceOperation.cloneService(fullService, "2.0", false); - assertTrue(createService.isLeft()); - Either serviceAfterCreate = serviceOperation.getServiceByNameAndVersion("my-service", "2.0", null, false); - assertTrue(serviceAfterCreate.isLeft()); - fullService = serviceAfterCreate.left().value(); - - Either getOrigService = serviceOperation.getServiceByNameAndVersion("my-service", "1.0", null, false); - assertTrue(getOrigService.isLeft()); - origService = getOrigService.left().value(); - - // assertEquals(origService.getComponentMetadataDefinition(), - // fullService.getComponentMetadataDefinition()); - assertEquals(origService.getArtifacts().size(), fullService.getArtifacts().size()); - assertEquals(origService.getComponentInstances().size(), fullService.getComponentInstances().size()); - assertEquals(origService.getComponentInstancesRelations().size(), fullService.getComponentInstancesRelations().size()); - - origService.setUniqueId(fullService.getUniqueId()); - origService.setVersion(fullService.getVersion()); - - assertEquals(origService.getComponentMetadataDefinition(), fullService.getComponentMetadataDefinition()); - assertEquals(origService.getCategories(), fullService.getCategories()); - - serviceOperation.deleteService(origService.getUniqueId()); - serviceOperation.deleteService(serviceAfterCreate.left().value().getUniqueId()); - - // } finally { - // titanDao.rollback(); - // Either serviceAfterCreate = - // serviceOperation.getService(UniqueIdBuilder.buildServiceUniqueId("my-service", - // "2.0"), true); - // assertTrue(serviceAfterCreate.isRight()); - // - // Either getOrigService = - // serviceOperation.getService(UniqueIdBuilder.buildServiceUniqueId("my-service", - // "1.0"), true); - // assertTrue(getOrigService.isRight()); - // titanDao.rollback(); - // } - } - - // @Test - public void testCloneServiceWithoutResourceInstances() { - String userId = USER_ID; - Service origService = createService(userId, CATEGORY_NAME, "my-service", "1.0", true); - - // add artifacts - addArtifactToService(userId, origService.getUniqueId(), "install_apache"); - addArtifactToService(userId, origService.getUniqueId(), "start_apache"); - - Either service2 = serviceOperation.getService(origService.getUniqueId(), false); - assertTrue(service2.isLeft()); - origService = service2.left().value(); - - Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); - String json = prettyGson.toJson(origService); - log.debug(json); - - Service fullService = origService; - - Either createService = serviceOperation.cloneService(fullService, "2.0", false); - assertTrue(createService.isLeft()); - Either serviceAfterCreate = serviceOperation.getServiceByNameAndVersion("my-service", "2.0", null, false); - assertTrue(serviceAfterCreate.isLeft()); - fullService = serviceAfterCreate.left().value(); - - Either getOrigService = serviceOperation.getServiceByNameAndVersion("my-service", "1.0", null, false); - assertTrue(getOrigService.isLeft()); - origService = getOrigService.left().value(); - - // assertEquals(origService.getComponentMetadataDefinition(), - // fullService.getComponentMetadataDefinition()); - assertEquals(origService.getArtifacts().size(), fullService.getArtifacts().size()); - assertEquals(origService.getComponentInstances(), fullService.getComponentInstances()); - assertEquals(origService.getComponentInstancesRelations(), fullService.getComponentInstancesRelations()); - - origService.setUniqueId(fullService.getUniqueId()); - origService.setVersion(fullService.getVersion()); - - assertEquals(origService.getComponentMetadataDefinition(), fullService.getComponentMetadataDefinition()); - assertEquals(origService.getCategories(), fullService.getCategories()); - - serviceOperation.deleteService(getOrigService.left().value().getUniqueId()); - serviceOperation.deleteService(serviceAfterCreate.left().value().getUniqueId()); - - // } finally { - // titanDao.rollback(); - // } - } - - // @Test - public void testCloneServiceWithoutArtifacts() { - String userId = USER_ID; - Service origService = createService(userId, CATEGORY_NAME, "my-service", "1.0", true); - - // add resource instances - ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest(); - riTest.setOperations(titanDao, capabilityTypeOperation, requirementOperation, capabilityOperation, resourceOperation, propertyOperation, resourceInstanceOperation); - riTest.addResourceInstancesAndRelation(origService.getUniqueId()); - - Either service2 = serviceOperation.getService(origService.getUniqueId(), false); - assertTrue(service2.isLeft()); - origService = service2.left().value(); - - Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); - String json = prettyGson.toJson(origService); - log.debug(json); - - Service fullService = origService; - - Either createService = serviceOperation.cloneService(fullService, "2.0", false); - assertTrue(createService.isLeft()); - Either serviceAfterCreate = serviceOperation.getServiceByNameAndVersion("my-service", "2.0", null, false); - assertTrue(serviceAfterCreate.isLeft()); - fullService = serviceAfterCreate.left().value(); - - Either getOrigService = serviceOperation.getServiceByNameAndVersion("my-service", "1.0", null, false); - assertTrue(getOrigService.isLeft()); - origService = getOrigService.left().value(); - - assertEquals(origService.getArtifacts(), fullService.getArtifacts()); - assertEquals(origService.getComponentInstances().size(), fullService.getComponentInstances().size()); - assertEquals(origService.getComponentInstancesRelations().size(), fullService.getComponentInstancesRelations().size()); - - origService.setUniqueId(fullService.getUniqueId()); - origService.setVersion(fullService.getVersion()); - - assertEquals(origService.getComponentMetadataDefinition(), fullService.getComponentMetadataDefinition()); - assertEquals(origService.getCategories(), fullService.getCategories()); - - serviceOperation.deleteService(serviceAfterCreate.left().value().getUniqueId()); - serviceOperation.deleteService(getOrigService.left().value().getUniqueId()); - - // } finally { - // titanDao.rollback(); - // } - } - - // @Test - public void testCloneServiceSimple() { - String userId = USER_ID; - String serviceName = "serviceToClone"; - - Service origService = createService(userId, CATEGORY_NAME, serviceName, "1.0", true); - - Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); - String json = prettyGson.toJson(origService); - log.debug(json); - - Service fullService = origService; - - Either createService = serviceOperation.cloneService(fullService, "2.0", false); - assertTrue(createService.isLeft()); - Either serviceAfterCreate = serviceOperation.getServiceByNameAndVersion(serviceName, "2.0", null, false); - assertTrue(serviceAfterCreate.isLeft()); - fullService = serviceAfterCreate.left().value(); - - Either getOrigService = serviceOperation.getServiceByNameAndVersion(serviceName, "1.0", null, false); - assertTrue(getOrigService.isLeft()); - origService = getOrigService.left().value(); - - // assertEquals(origService.getComponentMetadataDefinition(), - // fullService.getComponentMetadataDefinition()); - assertEquals(origService.getArtifacts(), fullService.getArtifacts()); - assertEquals(origService.getComponentInstances(), fullService.getComponentInstances()); - assertEquals(origService.getComponentInstancesRelations(), fullService.getComponentInstancesRelations()); - origService.setUniqueId(fullService.getUniqueId()); - origService.setVersion(fullService.getVersion()); - - assertEquals(origService.getComponentMetadataDefinition(), fullService.getComponentMetadataDefinition()); - assertEquals(origService.getCategories(), fullService.getCategories()); - - serviceOperation.deleteService(getOrigService.left().value().getUniqueId()); - serviceOperation.deleteService(serviceAfterCreate.left().value().getUniqueId()); - - // } finally { - // titanDao.rollback(); - // } - } - - private Service buildServiceMetadata(String userId, String category, String serviceName, String serviceVersion) { - - Service service = new Service(); - service.setName(serviceName); - service.setVersion(serviceVersion); - service.setDescription("description 1"); - - service.setCreatorUserId(userId); - service.setContactId("contactId@sdc.com"); - CategoryDefinition categoryDef = new CategoryDefinition(); - categoryDef.setName(category); - - List categories = new ArrayList<>(); - categories.add(categoryDef); - service.setCategories(categories); - - service.setIcon("images/my.png"); - List tags = new ArrayList(); - tags.add("TAG1"); - tags.add("TAG2"); - service.setTags(tags); - return service; - } - - private void deleteAndCreateCategory(String category) { - String[] names = category.split("/"); - OperationTestsUtil.deleteAndCreateServiceCategory(category, titanDao); - OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); - - /* - * CategoryData categoryData = new CategoryData(); categoryData.setName(category); - * - * titanDao.deleteNode(categoryData, CategoryData.class); Either createNode = titanDao.createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode); - */ - - } - - private UserData deleteAndCreateUser(String userId, String firstName, String lastName, String role) { - UserData userData = new UserData(); - userData.setUserId(userId); - userData.setFirstName(firstName); - userData.setLastName(lastName); - if (role != null && !role.isEmpty()) { - userData.setRole(role); - } else { - userData.setRole("ADMIN"); - } - - titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); - titanDao.createNode(userData, UserData.class); - titanDao.commit(); - - return userData; - } - - @Test - public void testCatalogService() { - String userId = USER_ID; - String category = CATEGORY_NAME; - String serviceName = "MyService"; - String serviceVersion = "0.1"; - Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); - log.debug("{}", serviceAfterSave); - String serviceId = serviceAfterSave.getUniqueId(); - - Map propertiesToMatch = new HashMap<>(); - propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); - - Either, StorageOperationStatus> catalog = serviceOperation.getCatalogData(propertiesToMatch, false); - assertTrue(catalog.isLeft()); - Set catalogSet = catalog.left().value(); - Set idSet = new HashSet<>(); - for (Service service : catalogSet) { - idSet.add(service.getUniqueId()); - } - assertTrue(idSet.contains(serviceId)); - serviceOperation.deleteService(serviceId); - } - - @After - public void teardown() { - clearGraph(); - } - - private void clearGraph() { - Either graphResult = titanDao.getGraph(); - TitanGraph graph = graphResult.left().value(); - - Iterable vertices = graph.query().vertices(); - if (vertices != null) { - Iterator iterator = vertices.iterator(); - while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - // graph.removeVertex(vertex); - vertex.remove(); - } - - } - titanDao.commit(); - } - - @Test - public void testTesterFollowed() { - String serviceName = "Test1"; - String serviceName2 = "Test2"; - String serviceName3 = "Test3"; - String userId = USER_ID; - String testerUserId = "tt0004"; - String category = CATEGORY_NAME; - deleteAndCreateUser(testerUserId, "tester", "last", "TESTER"); - // deleteAndCreateCategory(category); - - String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User); - Either findUser = titanDao.getNode(key, userId, UserData.class); - User adminUser = OperationTestsUtil.convertUserDataToUser(findUser.left().value()); - Either findTesterUser = titanDao.getNode(key, testerUserId, UserData.class); - User testerUser = OperationTestsUtil.convertUserDataToUser(findTesterUser.left().value()); - - // Create 3 new services - Service resultService = createService(userId, category, serviceName, "0.1", false); - log.debug("{}", resultService); - String serviceId = resultService.getUniqueId(); - Service resultService2 = createService(userId, category, serviceName2, "0.1", false); - log.debug("{}", resultService2); - String serviceId2 = resultService2.getUniqueId(); - Service resultService3 = createService(userId, category, serviceName3, "0.1", false); - log.debug("{}", resultService3); - String serviceId3 = resultService3.getUniqueId(); - - // update 1 service to READY_FOR_CERTIFICATION - Either certReqResponse = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false); - Service RFCService = (Service) certReqResponse.left().value(); - assertEquals(RFCService.getLifecycleState(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - - // update 1 service to CERTIFICATION_IN_PROGRESS - Either startCertificationResponse = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService2, testerUser, adminUser, false); - Service IPService = (Service) startCertificationResponse.left().value(); - assertEquals(IPService.getLifecycleState(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - - Set lifecycleStates = new HashSet(); - lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - - Either, StorageOperationStatus> services = serviceOperation.getTesterFollowed(testerUserId, lifecycleStates, false); - - assertTrue(services.isLeft()); - List result = services.left().value(); - - List ids = new ArrayList<>(); - for (Service service : result) { - ids.add(service.getUniqueId()); - } - assertTrue(ids.contains(serviceId)); - assertTrue(ids.contains(serviceId2)); - assertFalse(ids.contains(serviceId3)); - serviceOperation.deleteService(serviceId); - serviceOperation.deleteService(serviceId2); - serviceOperation.deleteService(serviceId3); - - } - - @Test - public void testOpsFollowed() { - String serviceName = "Test1"; - String serviceName2 = "Test2"; - String serviceName3 = "Test3"; - String serviceName4 = "Test4"; - String userId = USER_ID; - String category = CATEGORY_NAME; - String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User); - Either findUser = titanDao.getNode(key, userId, UserData.class); - User adminUser = OperationTestsUtil.convertUserDataToUser(findUser.left().value()); - - // Create 4 new services - Service resultService = createService(userId, category, serviceName, "0.1", false); - log.debug("{}", resultService); - String serviceId = resultService.getUniqueId(); - Service resultService2 = createService(userId, category, serviceName2, "0.1", false); - log.debug("{}", resultService2); - String serviceId2 = resultService2.getUniqueId(); - Service resultService3 = createService(userId, category, serviceName3, "0.1", false); - log.debug("{}", resultService3); - String serviceId3 = resultService3.getUniqueId(); - Service resultService4 = createService(userId, category, serviceName4, "0.1", false); - log.debug("{}", resultService3); - String serviceId4 = resultService4.getUniqueId(); - - // update 1 service to CERTIFIED dist status DISTRIBUTED - Either reqCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false); - Either startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService, adminUser, adminUser, false); - Service actualService = (Service) startCertificationResult.left().value(); - - Either certResponse = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false); - Service certifiedService = (Service) certResponse.left().value(); - serviceOperation.updateDestributionStatus(resultService, adminUser, DistributionStatusEnum.DISTRIBUTED); - - // update 1 service to CERTIFIED dist status DISTRIBUTION_APPROVED - Either reqCertificationResult2 = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false); - Either startCertificationResult2 = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false); - Service actualService2 = (Service) startCertificationResult2.left().value(); - - Either certResponse2 = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false); - Service certifiedService2 = (Service) certResponse2.left().value(); - serviceOperation.updateDestributionStatus(resultService2, adminUser, DistributionStatusEnum.DISTRIBUTION_APPROVED); - - // update 1 service to CERTIFIED dist status DISTRIBUTION_REJECTED - Either reqCertificationResult3 = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService3, adminUser, adminUser, false); - Either startCertificationResult3 = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService3, adminUser, adminUser, false); - Service actualService3 = (Service) startCertificationResult3.left().value(); - - Either certResponse3 = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, actualService3, adminUser, adminUser, false); - Service certifiedService3 = (Service) certResponse3.left().value(); - serviceOperation.updateDestributionStatus(certifiedService3, adminUser, DistributionStatusEnum.DISTRIBUTION_REJECTED); - - Map propertiesToMatch = new HashMap<>(); - propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); - - Set distStatus = new HashSet(); - distStatus.add(DistributionStatusEnum.DISTRIBUTION_APPROVED); - distStatus.add(DistributionStatusEnum.DISTRIBUTED); - - Either, StorageOperationStatus> services = serviceOperation.getCertifiedServicesWithDistStatus(propertiesToMatch, distStatus, false); - - assertTrue(services.isLeft()); - Set result = services.left().value(); - - List ids = new ArrayList<>(); - for (Service service : result) { - ids.add(service.getUniqueId()); - } - assertTrue(ids.contains(certifiedService.getUniqueId())); - assertTrue(ids.contains(certifiedService2.getUniqueId())); - assertFalse(ids.contains(certifiedService3.getUniqueId())); - assertFalse(ids.contains(resultService4.getUniqueId())); - serviceOperation.deleteService(serviceId); - serviceOperation.deleteService(serviceId2); - serviceOperation.deleteService(serviceId3); - serviceOperation.deleteService(serviceId4); - } - - @Test - public void testGovernorFollowed() { - String serviceName = "Test1"; - String serviceName2 = "Test2"; - String serviceName3 = "Test3"; - String userId = USER_ID; - String category = CATEGORY_NAME; - String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User); - Either findUser = titanDao.getNode(key, userId, UserData.class); - User adminUser = OperationTestsUtil.convertUserDataToUser(findUser.left().value()); - - // Create 3 new services - Service resultService = createService(userId, category, serviceName, "0.1", false); - log.debug("{}", resultService); - String serviceId = resultService.getUniqueId(); - Service resultService2 = createService(userId, category, serviceName2, "0.1", false); - log.debug("{}", resultService2); - String serviceId2 = resultService2.getUniqueId(); - Service resultService3 = createService(userId, category, serviceName3, "0.1", false); - log.debug("{}", resultService3); - String serviceId3 = resultService3.getUniqueId(); - - // update 1 service to CERTIFIED + DISTRIBUTED - Either reqCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false); - Either startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService, adminUser, adminUser, false); - Service actualService = (Service) startCertificationResult.left().value(); - - Either certResponse = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, actualService, adminUser, adminUser, false); - Service certifiedService = (Service) certResponse.left().value(); - serviceOperation.updateDestributionStatus(certifiedService, adminUser, DistributionStatusEnum.DISTRIBUTED); - - // update 1 service to CERTIFIED dist status + DISTRIBUTION_REJECTED - Either reqCertificationResult2 = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false); - Either startCertificationResult2 = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false); - Service actualService2 = (Service) startCertificationResult2.left().value(); - - Either certResponse2 = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, actualService2, adminUser, adminUser, false); - Service certifiedService2 = (Service) certResponse2.left().value(); - serviceOperation.updateDestributionStatus(certifiedService2, adminUser, DistributionStatusEnum.DISTRIBUTED); - - Map propertiesToMatch = new HashMap<>(); - propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); - - Either, StorageOperationStatus> services = serviceOperation.getCertifiedServicesWithDistStatus(propertiesToMatch, null, false); - - assertTrue(services.isLeft()); - Set result = services.left().value(); - - List ids = new ArrayList<>(); - for (Service service : result) { - ids.add(service.getUniqueId()); - } - assertTrue(ids.contains(certifiedService.getUniqueId())); - assertTrue(ids.contains(certifiedService2.getUniqueId())); - assertFalse(ids.contains(serviceId3)); - serviceOperation.deleteService(serviceId); - serviceOperation.deleteService(serviceId2); - serviceOperation.deleteService(serviceId3); - } - -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorTest.java deleted file mode 100644 index 069282367f..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.operations.impl; - -import org.junit.Before; -import org.junit.Test; -import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator; - -import java.util.Collections; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -public class ToscaDefinitionPathCalculatorTest { - - private static final String INSTANCE_ID = "123"; - private static final String OWNER_ID = "321"; - - private ToscaDefinitionPathCalculator toscaDefinitionPathCalculator; - - - @Before - public void setUp() throws Exception { - toscaDefinitionPathCalculator = new ToscaDefinitionPathCalculatorImpl(); - } - - @Test - public void calculatePath_ownerAndComponentInstanceEqual() throws Exception { - ComponentInstance instance = getComponentInstance(INSTANCE_ID); - GraphEdge edge = createEdgeWithOwner(INSTANCE_ID); - List definitionPath = toscaDefinitionPathCalculator.calculateToscaDefinitionPath(instance, edge); - assertEquals(1, definitionPath.size()); - assertEquals(INSTANCE_ID, definitionPath.get(0)); - } - - @Test - public void calculatePath() throws Exception { - ComponentInstance instance = getComponentInstance(INSTANCE_ID); - GraphEdge edge = createEdgeWithOwner(OWNER_ID); - List definitionPath = toscaDefinitionPathCalculator.calculateToscaDefinitionPath(instance, edge); - assertEquals(2, definitionPath.size()); - assertEquals(INSTANCE_ID, definitionPath.get(0)); - assertEquals(OWNER_ID, definitionPath.get(1)); - - } - - - private ComponentInstance getComponentInstance(String instanceId) { - ComponentInstance instance = new ComponentInstance(); - instance.setUniqueId(instanceId); - return instance; - } - - private GraphEdge createEdgeWithOwner(String owner) { - GraphEdge edge = new GraphEdge(); - edge.setProperties(Collections.singletonMap(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), owner)); - return edge; - } - -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java index ed496b5e92..3a8bb7f8e7 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java @@ -20,24 +20,7 @@ package org.openecomp.sdc.be.model.operations.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.temporal.TemporalField; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - +import fj.data.Either; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Graph; @@ -59,12 +42,17 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ModelTestBase; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation; import org.openecomp.sdc.be.resources.data.UserData; import org.openecomp.sdc.common.api.UserRoleEnum; -import fj.data.Either; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.*; public class UserAdminOperationTest extends ModelTestBase { private static final TitanGenericDao titanGenericDao = mock(TitanGenericDao.class); @@ -97,33 +85,6 @@ public class UserAdminOperationTest extends ModelTestBase { assertTrue(eitherUser.isLeft()); User user = eitherUser.left().value(); assertTrue(user.getStatus() == UserStatusEnum.INACTIVE); - - } - - /* - * @Test public void testDeActivateUserDataFail(){ UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, false); - * - * Either eitherUser = userAdminOperation.deActivateUser(userAdminOperation.convertToUser( userData)); - * - * verify(titanGenericDao, times(0)).updateNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); verify(titanGenericDao, times(0)).deleteNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); assertTrue(eitherUser.isRight()); - * assertTrue(eitherUser.right().value() == StorageOperationStatus.USER_INACTIVE); - * - * } - */ - - @Test - public void testGetAllUsers() throws Exception { - UserData user1 = mockTitanGet("user1", UserRoleEnum.ADMIN, true); - UserData user2 = mockTitanGet("user2", UserRoleEnum.DESIGNER, false); - UserData user3 = mockTitanGet("user3", UserRoleEnum.PRODUCT_MANAGER, true); - when(titanGenericDao.getAll(NodeTypeEnum.User, UserData.class)).thenReturn(Either.left(Arrays.asList(user1, user2, user3))); - - List allUsers = userAdminOperation.getAllUsers().left().value(); - assertEquals(3, allUsers.size()); - assertUserEquals(user1, allUsers.get(0)); - assertUserEquals(user2, allUsers.get(1)); - assertUserEquals(user3, allUsers.get(2)); - verify(titanGenericDao).commit(); } @Test diff --git a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_1_cleanup_jettydir.rb b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_1_cleanup_jettydir.rb index 70e4bd06fb..d989eb20bb 100644 --- a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_1_cleanup_jettydir.rb +++ b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_1_cleanup_jettydir.rb @@ -46,12 +46,3 @@ directory "BE_create_catalog-be" do mode '0755' action :create end - - -directory "BE_create_catalog-be" do - path "/var/lib/jetty/config/onboarding-be" - owner 'jetty' - group 'jetty' - mode '0755' - action :create -end \ No newline at end of file diff --git a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_setup_configuration.rb b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_setup_configuration.rb index 2dd430ce7a..d76e95de1d 100644 --- a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_setup_configuration.rb +++ b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_setup_configuration.rb @@ -53,20 +53,6 @@ cookbook_file "ArtifactGenerator" do end -template "onboarding-be-config" do - path "/#{jetty_base}/config/onboarding-be/onboarding_configuration.yaml" - source "BE-onboarding-configuration.yaml.erb" - owner "m98835" - group "mechid" - mode "0755" - variables({ - :catalog_ip => node['HOST_IP'], - :catalog_port => node['BE'][:http_port], - :ssl_port => node['BE'][:https_port] -}) -end - - cookbook_file "/#{jetty_base}/etc/keystore" do source "keystore" owner "jetty" diff --git a/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_1_cleanup_jettydir.rb b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_1_cleanup_jettydir.rb index 29301a9418..25983700d2 100644 --- a/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_1_cleanup_jettydir.rb +++ b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_1_cleanup_jettydir.rb @@ -47,3 +47,11 @@ directory "FE_create_catalog-fe" do action :create end + +directory "FE_create_catalog-fe" do + path "/var/lib/jetty/config/onboarding-fe" + owner 'jetty' + group 'jetty' + mode '0755' + action :create +end \ No newline at end of file diff --git a/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_2_setup_configuration.rb b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_2_setup_configuration.rb index 64d71768cd..165d10c1f2 100644 --- a/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_2_setup_configuration.rb +++ b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_2_setup_configuration.rb @@ -11,3 +11,17 @@ template "catalog-fe-config" do :ssl_port => node['BE'][:https_port] }) end + + +template "onboarding-fe-config" do + path "/#{jetty_base}/config/onboarding-fe/onboarding_configuration.yaml" + source "FE-onboarding-configuration.yaml.erb" + owner "jetty" + group "jetty" + mode "0755" + variables({ + :catalog_ip => node['HOST_IP'], + :catalog_port => node['BE'][:http_port], + :ssl_port => node['BE'][:https_port] +}) +end \ No newline at end of file diff --git a/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-onboarding-configuration.yaml.erb b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-onboarding-configuration.yaml.erb new file mode 100644 index 0000000000..4646661dfb --- /dev/null +++ b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-onboarding-configuration.yaml.erb @@ -0,0 +1,5 @@ +notifications: + pollingIntervalMsec: 2000 + selectionSize: 100 + beHost: <%= @catalog_ip %> + beHttpPort: <%= @catalog_port %> \ No newline at end of file diff --git a/sdc-os-chef/sdc-frontend/startup.sh b/sdc-os-chef/sdc-frontend/startup.sh index ee6e7f528a..82f01576ef 100644 --- a/sdc-os-chef/sdc-frontend/startup.sh +++ b/sdc-os-chef/sdc-frontend/startup.sh @@ -5,7 +5,7 @@ cd /root/chef-solo echo "normal['HOST_IP'] = \"${HOST_IP}\"" > /root/chef-solo/cookbooks/sdc-catalog-fe/attributes/default.rb chef-solo -c solo.rb -E ${CHEFNAME} -sed -i '/^set -e/aJAVA_OPTIONS=\"-XX:MaxPermSize=256m -Xmx1500m -Dconfig.home=${JETTY_BASE}\/config -Dlog.home=${JETTY_BASE}\/logs -Dlogback.configurationFile=${JETTY_BASE}\/config\/catalog-fe\/logback.xml -Dconfiguration.yaml=${JETTY_BASE}\/config\/catalog-fe\/configuration.yaml\"' /docker-entrypoint.sh +sed -i '/^set -e/aJAVA_OPTIONS=\"-XX:MaxPermSize=256m -Xmx1500m -Dconfig.home=${JETTY_BASE}\/config -Dlog.home=${JETTY_BASE}\/logs -Dlogback.configurationFile=${JETTY_BASE}\/config\/catalog-fe\/logback.xml -Dconfiguration.yaml=${JETTY_BASE}\/config\/catalog-fe\/configuration.yaml -Donboarding_configuration.yaml=${JETTY_BASE}\/config\/onboarding-fe\/onboarding_configuration.yaml\"' /docker-entrypoint.sh sed -i '/^set -e/aTMPDIR=${JETTY_BASE}\/temp' /docker-entrypoint.sh cd /var/lib/jetty diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java index 3a42d22d0e..9b4d97e0a7 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java @@ -372,6 +372,10 @@ public class Service extends SetupCDTest { @Test public void addDeploymentArtifactToVFInstanceTest() throws Exception{ + if(true){ + throw new SkipException("Open bug 321669"); + } + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL,ArtifactTypeEnum.SNMP_POLL.getType()); @@ -401,6 +405,10 @@ public class Service extends SetupCDTest { @Test public void deleteDeploymentArtifactFromVFInstanceNextVersionTest() throws Exception{ + if(true){ + throw new SkipException("Open bug 322930"); + } + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL,ArtifactTypeEnum.SNMP_POLL.getType()); @@ -426,6 +434,10 @@ public class Service extends SetupCDTest { @Test public void updateDeploymentArtifactOnVFInstanceNextVersionTest() throws Exception{ + if(true){ + throw new SkipException("Open bug 322930"); + } + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL,ArtifactTypeEnum.SNMP_POLL.getType()); -- cgit 1.2.3-korg