From 2623c8402a57e2035db69a9d92d2851050916801 Mon Sep 17 00:00:00 2001 From: shrikantawachar Date: Mon, 20 May 2019 12:11:54 +0530 Subject: Upgrade SDC from Titan to Janus Graph Upgrade SDC from Titan to Janus Graph Change-Id: I67fb8b8e60cc6751697bc5ff2f06754c92803786 Issue-ID: SDC-2296 Signed-off-by: shrikantawachar --- asdctool/pom.xml | 38 +- .../cassandra-actions/recipes/03-schemaCreation.rb | 16 +- .../templates/default/configuration.yaml.erb | 16 +- .../templates/default/janusgraph.properties.erb | 29 + .../templates/default/titan.properties.erb | 29 - .../java/org/openecomp/sdc/asdctool/Utils.java | 10 +- .../configuration/GetConsumersConfiguration.java | 10 +- .../configuration/VrfObjectFixConfiguration.java | 30 +- .../sdc/asdctool/impl/ArtifactUuidFix.java | 63 +- .../sdc/asdctool/impl/GraphJsonValidator.java | 4 +- .../sdc/asdctool/impl/GraphMLConverter.java | 80 +- .../sdc/asdctool/impl/JanusGraphInitializer.java | 204 ++ .../openecomp/sdc/asdctool/impl/ProductLogic.java | 22 +- .../sdc/asdctool/impl/TitanGraphInitializer.java | 204 -- .../impl/TitanToJanusGraphMigration.groovy | 66 + .../sdc/asdctool/impl/UpdatePropertyOnVertex.java | 22 +- .../sdc/asdctool/impl/VrfObjectFixHandler.java | 33 +- .../asdctool/impl/internal/tool/CsarGenerator.java | 44 +- .../impl/internal/tool/DeleteComponentHandler.java | 83 +- .../config/ValidationToolConfiguration.java | 29 +- .../executers/ArtifactValidatorExecuter.java | 13 +- .../TopologyTemplateValidatorExecuter.java | 9 +- .../tasks/artifacts/ArtifactValidationUtils.java | 6 +- .../validator/tasks/moduleJson/ModuleJsonTask.java | 6 +- .../sdc/asdctool/main/DataSchemaMenu.java | 16 +- .../sdc/asdctool/main/ExportImportMenu.java | 8 +- .../openecomp/sdc/asdctool/main/RemoveUtils.java | 2 +- .../sdc/asdctool/main/UpdateIsVnfMenu.java | 2 +- .../tasks/mig1710/UpgradeMigration1710.java | 79 +- .../tasks/mig1802/SdcCatalogMigration.java | 59 +- .../tasks/mig1806/ForwardPathMigration.java | 66 +- .../tasks/mig1806/ResourceLifecycleMigration.java | 23 +- .../tasks/mig1806/SDCInstancesMigration.java | 34 +- .../tasks/mig1806/SdcArchiveMigration.java | 34 +- .../tasks/mig1902/InterfaceOperationMigration.java | 42 +- .../servlets/ExportImportJanusGraphServlet.java | 165 ++ .../servlets/ExportImportTitanServlet.java | 165 -- .../src/main/resources/config/configuration.yaml | 16 +- .../config/janusgraph-migration.properties | 4 + .../main/resources/config/janusgraph.properties | 28 + .../resources/config/titan-migration.properties | 4 - .../src/main/resources/config/titan.properties | 28 - .../main/resources/scripts/deleteAllProducts.sh | 6 +- asdctool/src/main/resources/scripts/exportUsers.sh | 6 +- .../resources/scripts/janusGraphSchemaCreation.sh | 33 + .../main/resources/scripts/titanSchemaCreation.sh | 33 - asdctool/src/main/resources/scripts/updateIsVnf.sh | 2 +- .../java/org/openecomp/sdc/asdctool/UtilsTest.java | 4 +- .../GetConsumersConfigurationTest.java | 6 +- .../sdc/asdctool/impl/ArtifactUuidFixTest.java | 26 +- .../sdc/asdctool/impl/GraphJsonValidatorTest.java | 12 +- .../sdc/asdctool/impl/GraphMLConverterTest.java | 18 +- .../sdc/asdctool/impl/GraphMLDataAnalyzerTest.java | 2 +- .../asdctool/impl/JanusGraphInitializerTest.java | 16 + .../sdc/asdctool/impl/ProductLogicTest.java | 4 +- .../asdctool/impl/TitanGraphInitializerTest.java | 16 - .../asdctool/impl/UpdatePropertyOnVertexTest.java | 10 +- .../sdc/asdctool/impl/VrfObjectFixHandlerTest.java | 24 +- .../impl/internal/tool/CsarGeneratorTest.java | 11 +- .../internal/tool/DeleteComponentHandlerTest.java | 14 +- .../config/ValidationToolConfigurationTest.java | 18 +- .../tasks/moduleJson/ModuleJsonTaskTest.java | 4 +- .../tasks/mig1710/UpgradeMigration1710Test.java | 50 +- .../tasks/mig1802/SdcCatalogMigrationTest.java | 8 +- .../tasks/mig1806/ForwardPathMigrationTest.java | 8 +- .../mig1806/ResourceLifecycleMigrationTest.java | 6 +- .../tasks/mig1806/SDCInstancesMigrationTest.java | 19 +- .../tasks/mig1806/SdcArchiveMigrationTest.java | 6 +- .../ExportImportJanusGraphServletTest.java | 38 + .../servlets/ExportImportTitanServletTest.java | 38 - build.gradle | 10 +- catalog-be/pom.xml | 33 +- .../cookbooks/sdc-catalog-be/attributes/default.rb | 2 +- .../recipes/BE_2_setup_configuration.rb | 16 +- .../templates/default/BE-configuration.yaml.erb | 16 +- .../templates/default/BE-janusgraph.properties.erb | 28 + .../templates/default/BE-titan.properties.erb | 28 - .../csar/YamlTemplateParsingHandler.java | 14 +- .../ServiceDistributionArtifactsBuilder.java | 2 +- .../health/HealthCheckBusinessLogic.java | 28 +- .../impl/AdditionalInformationBusinessLogic.java | 6 +- .../be/components/impl/ArchiveBusinessLogic.java | 14 +- .../be/components/impl/ArtifactsBusinessLogic.java | 18 +- .../sdc/be/components/impl/BaseBusinessLogic.java | 53 +- .../components/impl/CapabilitiesBusinessLogic.java | 46 +- .../be/components/impl/CassandraHealthCheck.java | 19 +- .../be/components/impl/CommonImportManager.java | 10 +- .../be/components/impl/ComponentBusinessLogic.java | 8 +- .../impl/ComponentInstanceBusinessLogic.java | 68 +- .../sdc/be/components/impl/DataTypesService.java | 8 +- .../be/components/impl/ElementBusinessLogic.java | 23 +- .../components/impl/ExternalRefsBusinessLogic.java | 4 +- .../sdc/be/components/impl/GroupBusinessLogic.java | 56 +- .../be/components/impl/GroupBusinessLogicNew.java | 2 +- .../be/components/impl/GroupTypeBusinessLogic.java | 12 +- .../be/components/impl/GroupTypeImportManager.java | 2 +- .../be/components/impl/InputsBusinessLogic.java | 25 +- .../impl/InterfaceOperationBusinessLogic.java | 34 +- .../be/components/impl/PolicyBusinessLogic.java | 2 +- .../components/impl/PolicyTypeBusinessLogic.java | 8 +- .../components/impl/PolicyTypeImportManager.java | 2 +- .../be/components/impl/ProductBusinessLogic.java | 10 +- .../be/components/impl/PropertyBusinessLogic.java | 10 +- .../impl/RelationshipTypeBusinessLogic.java | 8 +- .../impl/RelationshipTypeImportManager.java | 2 +- .../components/impl/RequirementBusinessLogic.java | 26 +- .../be/components/impl/ResourceBusinessLogic.java | 54 +- .../be/components/impl/ResourceImportManager.java | 2 +- .../be/components/impl/ServiceBusinessLogic.java | 74 +- .../impl/generic/GenericTypeBusinessLogic.java | 2 +- .../impl/instance/GroupMembersUpdateOperation.java | 2 +- .../impl/policy/PolicyTargetsUpdateHandler.java | 2 +- .../be/components/impl/utils/ExceptionUtils.java | 20 +- .../lifecycle/CertificationChangeTransition.java | 20 +- .../lifecycle/CertificationRequestTransition.java | 18 +- .../be/components/lifecycle/CheckinTransition.java | 20 +- .../components/lifecycle/CheckoutTransition.java | 20 +- .../components/lifecycle/LifeCycleTransition.java | 12 +- .../lifecycle/LifecycleBusinessLogic.java | 41 +- .../lifecycle/StartCertificationTransition.java | 18 +- .../lifecycle/UndoCheckoutTransition.java | 18 +- .../merge/GlobalInputsFilteringBusinessLogic.java | 2 +- .../be/components/merge/TopologyComparator.java | 2 +- .../merge/group/ComponentGroupMergeCommand.java | 2 +- .../merge/group/GroupPropertiesMergeCommand.java | 2 +- .../merge/input/ComponentInputsMergeBL.java | 2 +- .../merge/input/GlobalInputsMergeCommand.java | 2 +- .../components/merge/input/InputsMergeCommand.java | 2 +- .../ComponentCapabilitiesPropertiesMergeBL.java | 2 +- .../instance/ComponentInstanceArtifactsMerge.java | 2 +- .../ComponentInstanceForwardingPathMerge.java | 2 +- .../instance/ComponentInstanceInputsMergeBL.java | 2 +- .../ComponentInstanceInputsRedeclareHandler.java | 2 +- .../instance/ComponentInstanceInterfacesMerge.java | 2 +- .../ComponentInstanceMergeDataBusinessLogic.java | 2 +- .../ComponentInstancePropertiesMergeBL.java | 2 +- .../ComponentInstancePropsAndInputsMerge.java | 2 +- .../instance/ComponentInstanceRelationMerge.java | 2 +- .../merge/instance/ExternalRefsMergeBL.java | 2 +- .../merge/policy/PoliciesMergeCommand.java | 2 +- .../PropertyDataValueMergeBusinessLogic.java | 4 +- .../components/merge/utils/MergeInstanceUtils.java | 4 +- .../components/path/ForwardingPathValidator.java | 2 +- .../ComponentInstanceInputPropertyDeclarator.java | 2 +- .../ComponentInstancePropertyDeclarator.java | 2 +- .../property/ComponentPropertyDeclarator.java | 2 +- .../property/DefaultPropertyDeclarator.java | 8 +- .../property/PolicyPropertyDeclarator.java | 2 +- ...omponentInstancePropertyToPolicyDeclarator.java | 2 +- .../ComponentPropertyToPolicyDeclarator.java | 2 +- .../components/upgrade/UpgradeBusinessLogic.java | 14 +- .../validation/ComponentValidations.java | 2 +- .../components/validation/NodeFilterValidator.java | 2 +- .../components/validation/PropertyValidator.java | 8 +- .../validation/ServiceDistributionValidation.java | 2 +- .../ecomp/converters/AssetMetadataConverter.java | 2 +- .../openecomp/sdc/be/filters/BeServletFilter.java | 18 +- .../be/filters/ComponentsAvailabilityFilter.java | 2 +- .../be/tosca/CapabilityRequirementConverter.java | 4 +- .../java/org/openecomp/sdc/be/tosca/CsarUtils.java | 4 +- .../sdc/be/tosca/GroupExportParserImpl.java | 4 +- .../sdc/be/tosca/PolicyExportParserImpl.java | 4 +- .../openecomp/sdc/be/tosca/ToscaExportHandler.java | 12 +- .../org/openecomp/sdc/be/tosca/ToscaUtils.java | 3 - .../be/tosca/utils/ForwardingPathToscaUtil.java | 2 +- .../openecomp/sdc/be/user/UserBusinessLogic.java | 8 +- .../common/transaction/api/ITransactionSdnc.java | 2 +- .../common/transaction/api/TransactionUtils.java | 2 +- .../transaction/impl/JanusGraphCommitHandler.java | 52 + .../impl/JanusGraphRollbackHandler.java | 55 + .../transaction/impl/TitanCommitHandler.java | 52 - .../transaction/impl/TitanRollbackHandler.java | 55 - .../transaction/mngr/TransactionManager.java | 7 +- .../transaction/mngr/TransactionSdncImpl.java | 21 +- .../src/main/resources/config/configuration.yaml | 14 +- .../main/resources/config/janusgraph.properties | 11 + .../src/main/resources/config/titan.properties | 11 - .../java/org/openecomp/sdc/be/MockGenerator.java | 4 +- .../components/BaseServiceBusinessLogicTest.java | 11 +- .../components/HealthCheckBusinessLogicTest.java | 16 +- .../be/components/PropertyBusinessLogicTest.java | 24 +- .../be/components/ResourceImportManagerTest.java | 4 +- .../be/components/ServiceDistributionBLTest.java | 2 +- .../be/components/csar/CsarBusinessLogicTest.java | 2 +- .../ServiceDistributionArtifactsBuilderTest.java | 2 +- .../health/HealthCheckBusinessLogicTest.java | 4 +- .../AdditionalInformationBusinessLogicTest.java | 6 +- .../components/impl/ArchiveBusinessLogicTest.java | 4 +- .../components/impl/ArtifactBusinessLogicTest.java | 12 +- .../impl/ArtifactsBusinessLogicTest.java | 22 +- .../impl/AttributeBusinessLogicTest.java | 19 +- .../impl/CapabilitiesBusinessLogicTest.java | 20 +- .../impl/CapabilityTypeImportManagerTest.java | 6 +- .../components/impl/CommonImportManagerTest.java | 22 +- .../impl/ComponentInstanceBusinessLogicTest.java | 23 +- .../components/impl/DataTypeBusinessLogicTest.java | 2 +- .../be/components/impl/DataTypesServiceTest.java | 12 +- .../sdc/be/components/impl/ElementBLTest.java | 21 +- .../components/impl/ElementBusinessLogicTest.java | 6 +- .../be/components/impl/GroupBusinessLogicTest.java | 16 +- .../components/impl/InputsBusinessLogicTest.java | 35 +- .../impl/InterfaceOperationBusinessLogicTest.java | 16 +- .../components/impl/PolicyBusinessLogicTest.java | 16 +- .../impl/PolicyPropertiesBusinessLogicTest.java | 10 +- .../impl/PolicyTypeBusinessLogicTest.java | 4 +- .../components/impl/ProductBusinessLogicTest.java | 6 +- .../impl/RequirementBusinessLogicTest.java | 18 +- .../components/impl/ResourceBusinessLogicTest.java | 18 +- .../impl/ResourceInstanceBusinessLogicTest.java | 2 +- .../components/impl/ServiceBusinessLogicTest.java | 10 +- .../impl/generic/GenericTypeBusinessLogicTest.java | 2 +- .../instance/GroupMembersUpdateOperationTest.java | 2 +- .../instance/PolicyTargetsUpdateOperationTest.java | 2 +- .../policy/PolicyTargetsUpdateHandlerTest.java | 2 +- .../impl/utils/YamlTemplateParsingHandlerTest.java | 6 +- .../CertificationChangeTransitionTest.java | 12 +- .../lifecycle/CertificationRequestTest.java | 7 +- .../CertificationRequestTransitionTest.java | 10 +- .../sdc/be/components/lifecycle/CheckinTest.java | 3 +- .../sdc/be/components/lifecycle/CheckoutTest.java | 3 +- .../be/components/lifecycle/LifecycleTestBase.java | 14 +- .../be/components/lifecycle/UndoCheckoutTest.java | 3 +- .../GlobalInputsFilteringBusinessLogicTest.java | 2 +- .../components/merge/TopologyComparatorTest.java | 2 +- .../group/ComponentGroupMergeCommandTest.java | 2 +- .../group/GroupPropertiesMergeCommandTest.java | 2 +- .../merge/input/BaseComponentInputsMerge.java | 2 +- ...ComponentCapabilitiesPropertiesMergeBLTest.java | 2 +- .../ComponentInstanceArtifactsMergeTest.java | 2 +- .../ComponentInstanceCapabilitiesMergeBLTest.java | 2 +- ...omponentInstanceInputsRedeclareHandlerTest.java | 2 +- .../ComponentInstanceInterfacesMergeTest.java | 2 +- ...omponentInstanceMergeDataBusinessLogicTest.java | 2 +- .../ComponentInstancePropsAndInputsMergeTest.java | 2 +- .../ComponentInstanceRelationMergeTest.java | 2 +- .../merge/instance/ExternalRefsMergeBLTest.java | 2 +- .../ComponentInstanceForwardingPathMergeTest.java | 2 +- .../merge/policy/PoliciesMergeCommandTest.java | 2 +- .../ComponentInstanceInputsMergeBLTest.java | 2 +- .../ComponentInstancePropertiesMergeBLTest.java | 2 +- .../merge/utils/MergeInstanceUtilsTest.java | 10 +- .../be/components/path/BaseForwardingPathTest.java | 29 +- .../path/ForwardingPathValidatorTest.java | 2 +- .../beans/ForwardingPathToscaOperationFacade.java | 2 +- .../path/beans/InMemoryJanusGraphClient.java | 216 ++ .../path/beans/InMemoryTitanGraphClient.java | 211 -- .../components/path/beans/JanusGraphTestSetup.java | 166 ++ .../components/path/beans/TitanGraphTestSetup.java | 166 -- .../be/components/path/utils/GraphTestUtils.java | 44 +- ...ponentInstanceInputPropertyDeceleratorTest.java | 2 +- ...mponentInstanceInputPropertyDeclaratorTest.java | 2 +- .../ComponentInstancePropertyDeclaratorTest.java | 2 +- .../property/ComponentPropertyDeclaratorTest.java | 2 +- .../ComponentPropertyToPolicyDeclaratorTest.java | 2 +- .../property/PolicyPropertyDeceleratorTest.java | 2 +- .../property/PolicyPropertyDeclaratorTest.java | 2 +- ...nentInstancePropertyToPolicyDeclaratorTest.java | 5 +- .../upgrade/UpgradeBusinessLogicTest.java | 11 +- .../validation/AnnotationValidatorTest.java | 4 +- .../validation/ComponentValidationsTest.java | 2 +- .../ServiceDistributionValidationTest.java | 2 +- .../PropertyValueConstraintValidationUtilTest.java | 28 +- .../servlet/ExternalRefServletTest.java | 58 +- .../sdc/be/servlets/ArchiveEndpointTest.java | 81 +- .../be/servlets/AutomatedUpgradeEndpointTest.java | 13 +- .../sdc/be/servlets/GroupEndpointTest.java | 2 +- .../sdc/be/servlets/GroupTypesEndpointTest.java | 19 +- .../sdc/be/servlets/PolicyServletTest.java | 2 +- .../sdc/be/servlets/TypesUploadEndpointTest.java | 46 +- .../tosca/CapabilityRequirementConverterTest.java | 4 +- .../org/openecomp/sdc/be/tosca/CsarUtilsTest.java | 6 +- .../sdc/be/tosca/ToscaExportHandlerTest.java | 11 +- .../sdc/be/user/UserBusinessLogicTest.java | 11 +- .../transaction/mngr/SdncTransactionTest.java | 150 +- .../resources/config/catalog-be/configuration.yaml | 14 +- .../src/test/resources/paths/path-context.xml | 8 +- catalog-dao/pom.xml | 14 +- .../sdc/be/dao/DAOJanusGraphStrategy.java | 32 + .../org/openecomp/sdc/be/dao/DAOTitanStrategy.java | 32 - .../sdc/be/dao/JanusGraphClientStrategy.java | 27 + .../openecomp/sdc/be/dao/TitanClientStrategy.java | 27 - .../be/dao/cassandra/schema/SdcSchemaBuilder.java | 2 +- .../sdc/be/dao/config/DAOSpringConfig.java | 2 +- .../sdc/be/dao/config/JanusGraphSpringConfig.java | 54 + .../sdc/be/dao/config/TitanSpringConfig.java | 53 - .../sdc/be/dao/impl/HealingPipelineDao.java | 14 +- .../sdc/be/dao/impl/heal/HealJanusGraphDao.java | 38 + .../sdc/be/dao/impl/heal/HealNodeGraphDao.java | 4 +- .../sdc/be/dao/impl/heal/HealTitanGraphDao.java | 38 - .../janusgraph/HealingJanusGraphGenericDao.java | 126 + .../sdc/be/dao/janusgraph/JanusGraphClient.java | 412 +++ .../be/dao/janusgraph/JanusGraphGenericDao.java | 1770 +++++++++++++ .../dao/janusgraph/JanusGraphOperationStatus.java | 26 + .../sdc/be/dao/janusgraph/JanusGraphUtils.java | 27 + .../openecomp/sdc/be/dao/janusgraph/QueryType.java | 28 + .../SimpleJanusGraphTransactionManager.java | 70 + .../sdc/be/dao/jsongraph/GraphVertex.java | 8 +- .../sdc/be/dao/jsongraph/HealingJanusGraphDao.java | 64 + .../sdc/be/dao/jsongraph/HealingTitanDao.java | 64 - .../sdc/be/dao/jsongraph/JanusGraphDao.java | 1077 ++++++++ .../openecomp/sdc/be/dao/jsongraph/TitanDao.java | 1078 -------- .../heal/AbstractJanusGraphVertexHeal.java | 22 + .../jsongraph/heal/AbstractTitanVertexHeal.java | 22 - .../sdc/be/dao/titan/HealingTitanGenericDao.java | 128 - .../org/openecomp/sdc/be/dao/titan/QueryType.java | 28 - .../sdc/be/dao/titan/TitanGenericDao.java | 1769 ------------- .../sdc/be/dao/titan/TitanGraphClient.java | 408 --- .../sdc/be/dao/titan/TitanOperationStatus.java | 26 - .../org/openecomp/sdc/be/dao/titan/TitanUtils.java | 27 - .../SimpleTitanTransactionManager.java | 70 - .../data/auditing/AuditingTypesConstants.java | 2 +- .../be/dao/cassandra/HealingPipelineDaoTest.java | 36 +- .../sdc/be/dao/janusgraph/JanusGraphUtilsTest.java | 21 + .../sdc/be/dao/jsongraph/GraphVertexTest.java | 6 +- .../be/dao/jsongraph/JanusGraphDaoMockTest.java | 586 ++++ .../sdc/be/dao/jsongraph/JanusGraphDaoTest.java | 312 +++ .../sdc/be/dao/jsongraph/TitanDaoMockTest.java | 586 ---- .../sdc/be/dao/jsongraph/TitanDaoTest.java | 312 --- .../openecomp/sdc/be/dao/titan/TitanUtilsTest.java | 21 - .../sdc/be/resources/JanusGraphGenericDaoTest.java | 630 +++++ .../sdc/be/resources/TitanGenericDaoTest.java | 631 ----- .../test/resources/application-context-test.xml | 2 +- .../config/catalog-dao/configuration.yaml | 6 +- .../sdc/fe/servlets/HealthCheckService.java | 2 +- catalog-model/pom.xml | 14 +- .../sdc/be/config/CatalogModelSpringConfig.java | 4 +- .../java/org/openecomp/sdc/be/model/Component.java | 2 +- .../sdc/be/model/DerivedNodeTypeResolver.java | 4 +- .../java/org/openecomp/sdc/be/model/Service.java | 6 +- .../sdc/be/model/cache/ApplicationCache.java | 6 +- .../be/model/cache/ApplicationDataTypeCache.java | 20 +- .../sdc/be/model/cache/ComponentCache.java | 6 +- .../org/openecomp/sdc/be/model/cache/DaoInfo.java | 2 +- .../sdc/be/model/cache/workers/SyncWorker.java | 26 +- .../model/jsonjanusgraph/datamodel/NodeType.java | 71 + .../jsonjanusgraph/datamodel/TopologyTemplate.java | 310 +++ .../jsonjanusgraph/datamodel/ToscaElement.java | 344 +++ .../datamodel/ToscaElementTypeEnum.java | 49 + .../jsonjanusgraph/enums/JsonConstantKeysEnum.java | 42 + .../operations/ArchiveOperation.java | 292 ++ .../operations/ArtifactsOperations.java | 760 ++++++ .../jsonjanusgraph/operations/BaseOperation.java | 1518 +++++++++++ .../ByToscaNameDerivedNodeTypeResolver.java | 56 + .../operations/CapabilitiesOperation.java | 156 ++ .../operations/CategoryOperation.java | 94 + .../operations/ExternalReferencesOperation.java | 297 +++ .../operations/ForwardingPathOperation.java | 118 + .../jsonjanusgraph/operations/GroupsOperation.java | 397 +++ .../operations/InstancesOperation.java | 25 + .../operations/InterfaceOperation.java | 98 + .../operations/NodeFilterOperation.java | 176 ++ .../operations/NodeTemplateOperation.java | 2417 +++++++++++++++++ .../operations/NodeTypeOperation.java | 979 +++++++ .../jsonjanusgraph/operations/PolicyOperation.java | 62 + .../operations/RequirementOperation.java | 92 + .../operations/TopologyTemplateOperation.java | 1623 ++++++++++++ .../operations/ToscaDataOperation.java | 25 + .../operations/ToscaElementLifecycleOperation.java | 1636 ++++++++++++ .../operations/ToscaElementOperation.java | 1405 ++++++++++ .../operations/ToscaOperationFacade.java | 2792 ++++++++++++++++++++ .../operations/UpgradeOperation.java | 231 ++ .../utils/CapabilityRequirementNameResolver.java | 394 +++ .../be/model/jsonjanusgraph/utils/IdMapper.java | 53 + .../model/jsonjanusgraph/utils/ModelConverter.java | 1730 ++++++++++++ .../sdc/be/model/jsontitan/datamodel/NodeType.java | 71 - .../jsontitan/datamodel/TopologyTemplate.java | 311 --- .../be/model/jsontitan/datamodel/ToscaElement.java | 344 --- .../jsontitan/datamodel/ToscaElementTypeEnum.java | 49 - .../jsontitan/enums/JsonConstantKeysEnum.java | 42 - .../jsontitan/operations/ArchiveOperation.java | 284 -- .../jsontitan/operations/ArtifactsOperations.java | 758 ------ .../model/jsontitan/operations/BaseOperation.java | 1495 ----------- .../ByToscaNameDerivedNodeTypeResolver.java | 55 - .../operations/CapabilitiesOperation.java | 155 -- .../jsontitan/operations/CategoryOperation.java | 91 - .../operations/ExternalReferencesOperation.java | 297 --- .../operations/ForwardingPathOperation.java | 117 - .../jsontitan/operations/GroupsOperation.java | 395 --- .../jsontitan/operations/InstancesOperation.java | 25 - .../jsontitan/operations/InterfaceOperation.java | 98 - .../jsontitan/operations/NodeFilterOperation.java | 175 -- .../operations/NodeTemplateOperation.java | 2400 ----------------- .../jsontitan/operations/NodeTypeOperation.java | 962 ------- .../jsontitan/operations/PolicyOperation.java | 62 - .../jsontitan/operations/RequirementOperation.java | 92 - .../operations/TopologyTemplateOperation.java | 1624 ------------ .../jsontitan/operations/ToscaDataOperation.java | 25 - .../operations/ToscaElementLifecycleOperation.java | 1583 ----------- .../operations/ToscaElementOperation.java | 1360 ---------- .../jsontitan/operations/ToscaOperationFacade.java | 2743 ------------------- .../jsontitan/operations/UpgradeOperation.java | 225 -- .../utils/CapabilityRequirementNameResolver.java | 394 --- .../sdc/be/model/jsontitan/utils/IdMapper.java | 53 - .../be/model/jsontitan/utils/ModelConverter.java | 1731 ------------ .../sdc/be/model/operations/StorageException.java | 12 +- .../api/IAdditionalInformationOperation.java | 28 +- .../model/operations/api/IArtifactOperation.java | 4 +- .../model/operations/api/ICapabilityOperation.java | 4 +- .../operations/api/ICapabilityTypeOperation.java | 4 +- .../be/model/operations/api/IInputsOperation.java | 4 +- .../model/operations/impl/AbstractOperation.java | 70 +- .../impl/AdditionalInformationOperation.java | 271 +- .../model/operations/impl/ArtifactOperation.java | 153 +- .../operations/impl/CacheMangerOperation.java | 10 +- .../model/operations/impl/CapabilityOperation.java | 106 +- .../operations/impl/CapabilityTypeOperation.java | 116 +- .../operations/impl/CommonTypeOperations.java | 35 +- .../impl/ComponentInstanceOperation.java | 209 +- .../model/operations/impl/ConsumerOperation.java | 48 +- .../model/operations/impl/DaoStatusConverter.java | 10 +- .../impl/DefaultDerivedFromOperation.java | 53 +- .../be/model/operations/impl/ElementOperation.java | 262 +- .../model/operations/impl/GraphLockOperation.java | 32 +- .../operations/impl/GroupInstanceOperation.java | 224 +- .../be/model/operations/impl/GroupOperation.java | 101 +- .../model/operations/impl/GroupTypeOperation.java | 150 +- .../operations/impl/HeatParametersOperation.java | 130 +- .../be/model/operations/impl/InputsOperation.java | 72 +- .../impl/InterfaceLifecycleOperation.java | 271 +- .../be/model/operations/impl/OperationUtils.java | 33 +- .../model/operations/impl/PolicyTypeOperation.java | 46 +- .../model/operations/impl/PropertyOperation.java | 541 ++-- .../operations/impl/RelationshipTypeOperation.java | 135 +- .../model/operations/impl/UserAdminOperation.java | 82 +- .../operations/utils/ComponentValidationUtils.java | 2 +- .../org/openecomp/sdc/be/model/ModelTestBase.java | 18 +- .../model/cache/ApplicationDataTypeCacheTest.java | 24 +- .../sdc/be/model/cache/ComponentCacheTest.java | 2 +- .../openecomp/sdc/be/model/cache/DaoInfoTest.java | 2 +- .../be/model/cache/jobs/CheckAndUpdateJobTest.java | 2 +- .../model/config/ModelOperationsSpringConfig.java | 3 +- .../jsonjanusgraph/datamodel/NodeTypeTest.java | 173 ++ .../datamodel/TopologyTemplateTest.java | 422 +++ .../datamodel/ToscaElementTypeEnumTest.java | 25 + .../enums/JsonConstantKeysEnumTest.java | 22 + .../operations/ArchiveOperationTest.java | 495 ++++ .../operations/ArtifactsOperationsTest.java | 83 + .../operations/CapabilitiesOperationTest.java | 87 + .../ExternalReferencesOperationTest.java | 227 ++ .../operations/GroupsOperationTest.java | 105 + .../operations/InterfaceOperationTest.java | 497 ++++ .../operations/NodeTemplateOperationGraphTest.java | 244 ++ .../operations/NodeTemplateOperationTest.java | 366 +++ .../operations/PolicyOperationIntegrationTest.java | 133 + .../operations/PolicyOperationTest.java | 94 + ...TemplateOperationCapabilityIntegrationTest.java | 197 ++ .../operations/TopologyTemplateOperationTest.java | 185 ++ .../ToscaElementOperationCatalogTest.java | 73 + .../operations/ToscaElementOperationTest.java | 363 +++ .../operations/ToscaElementOperationTestImpl.java | 74 + .../ToscaOperationFacadePoliciesTest.java | 134 + .../operations/ToscaOperationFacadeTest.java | 692 +++++ .../operations/UpgradeOperationTest.java | 183 ++ .../jsonjanusgraph/utils/CapabilityTestUtils.java | 85 + .../model/jsonjanusgraph/utils/GraphTestUtils.java | 129 + .../model/jsonjanusgraph/utils/IdMapperTest.java | 37 + .../jsonjanusgraph/utils/ModelConverterTest.java | 137 + .../be/model/jsontitan/datamodel/NodeTypeTest.java | 173 -- .../jsontitan/datamodel/TopologyTemplateTest.java | 423 --- .../datamodel/ToscaElementTypeEnumTest.java | 25 - .../jsontitan/enums/JsonConstantKeysEnumTest.java | 22 - .../jsontitan/operations/ArchiveOperationTest.java | 486 ---- .../operations/ArtifactsOperationsTest.java | 83 - .../operations/CapabilitiesOperationTest.java | 87 - .../ExternalReferencesOperationTest.java | 226 -- .../jsontitan/operations/GroupsOperationTest.java | 105 - .../operations/InterfaceOperationTest.java | 497 ---- .../operations/NodeTemplateOperationGraphTest.java | 244 -- .../operations/NodeTemplateOperationTest.java | 364 --- .../operations/PolicyOperationIntegrationTest.java | 134 - .../jsontitan/operations/PolicyOperationTest.java | 93 - ...TemplateOperationCapabilityIntegrationTest.java | 198 -- .../operations/TopologyTemplateOperationTest.java | 177 -- .../ToscaElementOperationCatalogTest.java | 73 - .../operations/ToscaElementOperationTest.java | 363 --- .../operations/ToscaElementOperationTestImpl.java | 74 - .../ToscaOperationFacadePoliciesTest.java | 135 - .../operations/ToscaOperationFacadeTest.java | 688 ----- .../jsontitan/operations/UpgradeOperationTest.java | 183 -- .../model/jsontitan/utils/CapabilityTestUtils.java | 85 - .../be/model/jsontitan/utils/GraphTestUtils.java | 129 - .../sdc/be/model/jsontitan/utils/IdMapperTest.java | 37 - .../model/jsontitan/utils/ModelConverterTest.java | 137 - .../impl/AdditionalInformationOperationTest.java | 56 +- .../impl/AnnotationTypeOperationsTest.java | 10 +- .../operations/impl/ArtifactOperationTest.java | 75 +- .../impl/CapabilityTypeOperationTest.java | 39 +- .../impl/ComponentInstanceOperationTest.java | 22 +- .../operations/impl/ElementOperationTest.java | 14 +- .../operations/impl/GroupTypeOperationTest.java | 78 +- .../impl/HeatParametersOperationTest.java | 38 +- .../impl/InterfaceLifecycleOperationTest.java | 39 +- .../operations/impl/PolicyTypeOperationTest.java | 32 +- .../operations/impl/PropertyOperationTest.java | 74 +- .../impl/RelationshipTypeOperationTest.java | 51 +- .../impl/ToscaElementLifecycleOperationTest.java | 71 +- .../operations/impl/UserAdminOperationTest.java | 86 +- .../operations/impl/util/OperationTestsUtil.java | 30 +- .../be/model/operations/impl/util/PrintGraph.java | 40 +- .../test/resources/application-context-test.xml | 6 +- .../config/catalog-model/configuration.yaml | 14 +- .../src/test/resources/config/configuration.yaml | 14 +- .../sdc/be/config/BeEcompErrorManager.java | 8 +- .../org/openecomp/sdc/be/config/Configuration.java | 77 +- .../org/openecomp/sdc/common/api/Constants.java | 2 +- .../openecomp/sdc/common/api/HealthCheckInfo.java | 2 +- .../sdc/common/config/EcompErrorCode.java | 10 +- .../sdc/common/config/EcompErrorEnum.java | 12 +- .../sdc/common/test/BaseConfDependent.java | 2 +- .../sdc/be/config/BeEcompErrorManagerTest.java | 8 +- .../openecomp/sdc/be/config/ConfigurationTest.java | 60 +- .../resources/config/common/configuration.yaml | 14 +- docs/configuration.rst | 58 +- docs/release-notes.rst | 1 - docs/sdcsdks.rst | 14 - .../sdc-onboard-backend/attributes/default.rb | 2 +- .../src/main/resources/configuration.yaml | 10 +- .../src/test/resources/configuration.yaml | 10 +- pom.xml | 3 +- sdc-os-chef/environments/Template.json | 2 +- .../configmaps/sdc-environment-configmap.yaml | 2 +- test-apis-ci/pom.xml | 13 +- .../files/default/conf/log4j.properties | 2 +- .../sanityApiTests_2_setup_configuration.rb | 8 +- .../templates/default/BE-janusgraph.properties.erb | 25 + .../templates/default/BE-titan.properties.erb | 25 - .../templates/default/sdc-sanity.yaml.erb | 4 +- .../sdc/ci/tests/api/ComponentBaseTest.java | 6 +- .../org/openecomp/sdc/ci/tests/config/Config.java | 12 +- .../execute/TODO/ImportCapabilityTypeCITest.java | 12 +- .../org/openecomp/sdc/ci/tests/utils/DbUtils.java | 90 +- .../main/java/org/openecomp/sdc/post/Install.java | 32 +- .../src/main/resources/ci/conf/attsdc.yaml | 4 +- .../main/resources/ci/conf/janusgraph.properties | 11 + .../src/main/resources/ci/conf/log4j.properties | 2 +- .../src/main/resources/ci/conf/titan.properties | 11 - test-apis-ci/src/main/resources/log4j.properties | 2 +- .../config/test-apis-ci/configuration.yaml | 14 +- ui-ci/pom.xml | 25 - .../files/default/conf/log4j.properties | 2 +- .../recipes/sanityUiTests_2_setup_configuration.rb | 8 +- .../templates/default/BE-janusgraph.properties.erb | 25 + .../templates/default/BE-titan.properties.erb | 25 - .../templates/default/sdc-sanity.yaml.erb | 2 +- ui-ci/src/main/resources/ci/conf/attsdc.yaml | 4 +- ui-ci/src/main/resources/ci/conf/log4j.properties | 2 +- 546 files changed, 34214 insertions(+), 33628 deletions(-) create mode 100644 asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/janusgraph.properties.erb delete mode 100644 asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/titan.properties.erb create mode 100644 asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/JanusGraphInitializer.java delete mode 100644 asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/TitanGraphInitializer.java create mode 100644 asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/TitanToJanusGraphMigration.groovy create mode 100644 asdctool/src/main/java/org/openecomp/sdc/asdctool/servlets/ExportImportJanusGraphServlet.java delete mode 100644 asdctool/src/main/java/org/openecomp/sdc/asdctool/servlets/ExportImportTitanServlet.java create mode 100644 asdctool/src/main/resources/config/janusgraph-migration.properties create mode 100644 asdctool/src/main/resources/config/janusgraph.properties delete mode 100644 asdctool/src/main/resources/config/titan-migration.properties delete mode 100644 asdctool/src/main/resources/config/titan.properties create mode 100644 asdctool/src/main/resources/scripts/janusGraphSchemaCreation.sh delete mode 100644 asdctool/src/main/resources/scripts/titanSchemaCreation.sh create mode 100644 asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/JanusGraphInitializerTest.java delete mode 100644 asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/TitanGraphInitializerTest.java create mode 100644 asdctool/src/test/java/org/openecomp/sdc/asdctool/servlets/ExportImportJanusGraphServletTest.java delete mode 100644 asdctool/src/test/java/org/openecomp/sdc/asdctool/servlets/ExportImportTitanServletTest.java create mode 100644 catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-janusgraph.properties.erb delete mode 100644 catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-titan.properties.erb create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/JanusGraphCommitHandler.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/JanusGraphRollbackHandler.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java create mode 100644 catalog-be/src/main/resources/config/janusgraph.properties delete mode 100644 catalog-be/src/main/resources/config/titan.properties create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryJanusGraphClient.java delete mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/JanusGraphTestSetup.java delete mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/DAOJanusGraphStrategy.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/DAOTitanStrategy.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/JanusGraphClientStrategy.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/TitanClientStrategy.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/JanusGraphSpringConfig.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/TitanSpringConfig.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/heal/HealJanusGraphDao.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/heal/HealTitanGraphDao.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/HealingJanusGraphGenericDao.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphClient.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphGenericDao.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphOperationStatus.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphUtils.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/QueryType.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/transactions/SimpleJanusGraphTransactionManager.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/HealingJanusGraphDao.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/HealingTitanDao.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/JanusGraphDao.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/heal/AbstractJanusGraphVertexHeal.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/heal/AbstractTitanVertexHeal.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/HealingTitanGenericDao.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/QueryType.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanOperationStatus.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanUtils.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/transactions/SimpleTitanTransactionManager.java create mode 100644 catalog-dao/src/test/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphUtilsTest.java create mode 100644 catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/JanusGraphDaoMockTest.java create mode 100644 catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/JanusGraphDaoTest.java delete mode 100644 catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoMockTest.java delete mode 100644 catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoTest.java delete mode 100644 catalog-dao/src/test/java/org/openecomp/sdc/be/dao/titan/TitanUtilsTest.java create mode 100644 catalog-dao/src/test/java/org/openecomp/sdc/be/resources/JanusGraphGenericDaoTest.java delete mode 100644 catalog-dao/src/test/java/org/openecomp/sdc/be/resources/TitanGenericDaoTest.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeType.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/TopologyTemplate.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElementTypeEnum.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/enums/JsonConstantKeysEnum.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperations.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/BaseOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ByToscaNameDerivedNodeTypeResolver.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CapabilitiesOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CategoryOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ForwardingPathOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InstancesOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InterfaceOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeFilterOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/RequirementOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaDataOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementLifecycleOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperation.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityRequirementNameResolver.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/IdMapper.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElement.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnum.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnum.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArchiveOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ByToscaNameDerivedNodeTypeResolver.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CapabilitiesOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CategoryOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ForwardingPathOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InstancesOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeFilterOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/RequirementOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaDataOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementLifecycleOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/UpgradeOperation.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/CapabilityRequirementNameResolver.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapper.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeTypeTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/TopologyTemplateTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElementTypeEnumTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/enums/JsonConstantKeysEnumTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperationsTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CapabilitiesOperationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InterfaceOperationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperationGraphTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperationIntegrationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperationCapabilityIntegrationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperationCatalogTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperationTestImpl.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacadePoliciesTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacadeTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperationTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityTestUtils.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/GraphTestUtils.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/IdMapperTest.java create mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverterTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeTypeTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplateTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnumTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnumTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArchiveOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/CapabilitiesOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationGraphTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationIntegrationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationCapabilityIntegrationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationCatalogTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadePoliciesTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadeTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/UpgradeOperationTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/CapabilityTestUtils.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapperTest.java delete mode 100644 catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverterTest.java create mode 100644 test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/templates/default/BE-janusgraph.properties.erb delete mode 100644 test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/templates/default/BE-titan.properties.erb create mode 100644 test-apis-ci/src/main/resources/ci/conf/janusgraph.properties delete mode 100644 test-apis-ci/src/main/resources/ci/conf/titan.properties create mode 100644 ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/templates/default/BE-janusgraph.properties.erb delete mode 100644 ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/templates/default/BE-titan.properties.erb diff --git a/asdctool/pom.xml b/asdctool/pom.xml index 2bb4059975..d7ac069d45 100644 --- a/asdctool/pom.xml +++ b/asdctool/pom.xml @@ -222,11 +222,10 @@ - - com.thinkaurelius.titan - titan-core - ${titan.version} + org.janusgraph + janusgraph-core + ${janusgraph.version} compile @@ -241,6 +240,10 @@ commons-collections commons-collections + + groovy + org.codehaus.groovy + @@ -252,9 +255,9 @@ - org.onap.sdc.sdc-titan-cassandra - sdc-titan-cassandra - ${sdc.titan.version} + org.janusgraph + janusgraph-cassandra + ${janusgraph.version} compile @@ -264,27 +267,6 @@ - - org.apache.tinkerpop - tinkergraph-gremlin - 3.0.1-incubating - compile - - - - org.apache.tinkerpop - gremlin-groovy - 3.0.1-incubating - compile - - - groovy - org.codehaus.groovy - - - - - commons-logging commons-logging diff --git a/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/recipes/03-schemaCreation.rb b/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/recipes/03-schemaCreation.rb index fbfcb2ecea..4de50f6492 100644 --- a/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/recipes/03-schemaCreation.rb +++ b/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/recipes/03-schemaCreation.rb @@ -12,17 +12,17 @@ bash "install tar" do end -template "titan.properties" do +template "janusgraph.properties" do sensitive true - path "/tmp/sdctool/config/titan.properties" - source "titan.properties.erb" + path "/tmp/sdctool/config/janusgraph.properties" + source "janusgraph.properties.erb" mode "0755" variables({ :DC_NAME => node['cassandra']['datacenter_name'], :cassandra_ip => node['Nodes']['CS'].first, :cassandra_pwd => node['cassandra'][:cassandra_password], :cassandra_usr => node['cassandra'][:cassandra_user], - :titan_connection_timeout => node['cassandra']['titan_connection_timeout'], + :janusgraph_connection_timeout => node['cassandra']['janusgraph_connection_timeout'], :replication_factor => node['cassandra']['replication_factor'] }) end @@ -40,7 +40,7 @@ template "/tmp/sdctool/config/configuration.yaml" do :cassandra_port => node['cassandra']['cassandra_port'], :rep_factor => node['cassandra']['replication_factor'], :DC_NAME => node['cassandra']['datacenter_name'], - :titan_Path => "/tmp/sdctool/config/", + :janusgraph_Path => "/tmp/sdctool/config/", :socket_connect_timeout => node['cassandra']['socket_connect_timeout'], :socket_read_timeout => node['cassandra']['socket_read_timeout'], :cassandra_pwd => node['cassandra'][:cassandra_password], @@ -66,9 +66,9 @@ bash "excuting-schema-creation" do EOH end -bash "excuting-titanSchemaCreation.sh" do +bash "excuting-janusGraphSchemaCreation.sh" do code <<-EOH - chmod +x /tmp/sdctool/scripts/titanSchemaCreation.sh - /tmp/sdctool/scripts/titanSchemaCreation.sh /tmp/sdctool/config + chmod +x /tmp/sdctool/scripts/janusGraphSchemaCreation.sh + /tmp/sdctool/scripts/janusGraphSchemaCreation.sh /tmp/sdctool/config EOH end diff --git a/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb b/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb index 0a658bb8d9..ab27886a47 100644 --- a/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb +++ b/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb @@ -29,14 +29,14 @@ released: 2012-11-30 toscaConformanceLevel: 9.0 minToscaConformanceLevel: 3.0 -titanCfgFile: <%= @titan_Path %>/titan.properties -titanInMemoryGraph: false -titanLockTimeout: 1800 -# The interval to try and reconnect to titan DB when it is down during ASDC startup: -titanReconnectIntervalInSeconds: 3 - -# The read timeout towards Titan DB when health check is invoked: -titanHealthCheckReadTimeout: 1 +janusGraphCfgFile: <%= @janusgraph_Path %>/janusgraph.properties +janusGraphInMemoryGraph: false +janusGraphLockTimeout: 1800 +# The interval to try and reconnect to JanusGraph DB when it is down during ASDC startup: +janusGraphReconnectIntervalInSeconds: 3 + +# The read timeout towards JanusGraph DB when health check is invoked: +janusGraphHealthCheckReadTimeout: 1 # The interval to try and reconnect to Elasticsearch when it is down during ASDC startup: diff --git a/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/janusgraph.properties.erb b/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/janusgraph.properties.erb new file mode 100644 index 0000000000..60c24d7613 --- /dev/null +++ b/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/janusgraph.properties.erb @@ -0,0 +1,29 @@ +storage.backend=cassandra +storage.hostname=<%= @cassandra_ip %> +storage.port=9160 +storage.username=<%= @cassandra_usr %> +storage.password=<%= @cassandra_pwd %> +storage.connection-timeout=<%= @janusgraph_connection_timeout %> +storage.cassandra.keyspace=sdctitan + + +storage.cassandra.ssl.enabled=false +storage.cassandra.ssl.truststore.location=/var/lib/jetty/config/.truststore +storage.cassandra.ssl.truststore.password=Aa123456 + +storage.cassandra.read-consistency-level=LOCAL_QUORUM +storage.cassandra.write-consistency-level=LOCAL_QUORUM +storage.cassandra.replication-strategy-class=org.apache.cassandra.locator.NetworkTopologyStrategy +storage.cassandra.replication-strategy-options=<%= @DC_NAME %>,<%= @replication_factor %> +storage.cassandra.astyanax.local-datacenter=<%= @DC_NAME %> + +cache.db-cache = false +cache.db-cache-clean-wait = 20 +cache.db-cache-time = 180000 +cache.db-cache-size = 0.5 + +cache.tx-cache-size = 1000000 + +storage.lock.retries=5 +storage.lock.wait-time=500 + diff --git a/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/titan.properties.erb b/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/titan.properties.erb deleted file mode 100644 index 20a97be9de..0000000000 --- a/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/titan.properties.erb +++ /dev/null @@ -1,29 +0,0 @@ -storage.backend=cassandra -storage.hostname=<%= @cassandra_ip %> -storage.port=9160 -storage.username=<%= @cassandra_usr %> -storage.password=<%= @cassandra_pwd %> -storage.connection-timeout=<%= @titan_connection_timeout %> -storage.cassandra.keyspace=sdctitan - - -storage.cassandra.ssl.enabled=false -storage.cassandra.ssl.truststore.location=/var/lib/jetty/config/.truststore -storage.cassandra.ssl.truststore.password=Aa123456 - -storage.cassandra.read-consistency-level=LOCAL_QUORUM -storage.cassandra.write-consistency-level=LOCAL_QUORUM -storage.cassandra.replication-strategy-class=org.apache.cassandra.locator.NetworkTopologyStrategy -storage.cassandra.replication-strategy-options=<%= @DC_NAME %>,<%= @replication_factor %> -storage.cassandra.astyanax.local-datacenter=<%= @DC_NAME %> - -cache.db-cache = false -cache.db-cache-clean-wait = 20 -cache.db-cache-time = 180000 -cache.db-cache-size = 0.5 - -cache.tx-cache-size = 1000000 - -storage.lock.retries=5 -storage.lock.wait-time=500 - diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/Utils.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/Utils.java index 5c7d78e3f2..44bfc536b6 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/Utils.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/Utils.java @@ -20,8 +20,8 @@ package org.openecomp.sdc.asdctool; -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; +import org.janusgraph.core.JanusGraphFactory; +import org.janusgraph.core.JanusGraph; import org.apache.commons.configuration.Configuration; import org.apache.tinkerpop.gremlin.structure.Element; import org.apache.tinkerpop.gremlin.structure.Property; @@ -60,12 +60,12 @@ public class Utils { return responseBuilder.build(); } - public static TitanGraph openGraph(Configuration conf) { + public static JanusGraph openGraph(Configuration conf) { - TitanGraph graph = null; + JanusGraph graph = null; try { - graph = TitanFactory.open(conf); + graph = JanusGraphFactory.open(conf); } catch (Exception e) { log.error("Failed to start open graph", e); diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/GetConsumersConfiguration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/GetConsumersConfiguration.java index e411b53c08..53d299e163 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/GetConsumersConfiguration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/GetConsumersConfiguration.java @@ -1,20 +1,20 @@ package org.openecomp.sdc.asdctool.configuration; -import org.openecomp.sdc.be.dao.config.TitanSpringConfig; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.config.JanusGraphSpringConfig; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.model.operations.impl.ConsumerOperation; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration -@Import({TitanSpringConfig.class}) +@Import({JanusGraphSpringConfig.class}) public class GetConsumersConfiguration { @Bean("consumer-operation") - public ConsumerOperation consumerOperation(TitanGenericDao titanGenericDao) { - return new ConsumerOperation(titanGenericDao); + public ConsumerOperation consumerOperation(JanusGraphGenericDao janusGraphGenericDao) { + return new ConsumerOperation(janusGraphGenericDao); } } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/VrfObjectFixConfiguration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/VrfObjectFixConfiguration.java index 0dd078d863..5a82c697c7 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/VrfObjectFixConfiguration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/VrfObjectFixConfiguration.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.asdctool.configuration; import org.openecomp.sdc.asdctool.impl.VrfObjectFixHandler; -import org.openecomp.sdc.be.dao.DAOTitanStrategy; -import org.openecomp.sdc.be.dao.TitanClientStrategy; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.DAOJanusGraphStrategy; +import org.openecomp.sdc.be.dao.JanusGraphClientStrategy; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -13,24 +13,26 @@ import org.springframework.context.annotation.Primary; @Configuration public class VrfObjectFixConfiguration { - @Bean(name = "titan-dao") - public TitanDao titanDao(@Qualifier("titan-client") TitanGraphClient titanClient){ - return new TitanDao(titanClient); + @Bean(name = "janusgraph-dao") + public JanusGraphDao janusGraphDao(@Qualifier("janusgraph-client") JanusGraphClient janusGraphClient){ + return new JanusGraphDao(janusGraphClient); } - @Bean(name = "titan-client") + @Bean(name = "janusgraph-client") @Primary - public TitanGraphClient titanClient(@Qualifier("dao-client-strategy") TitanClientStrategy titanClientStrategy) { - return new TitanGraphClient(titanClientStrategy); + public JanusGraphClient janusGraphClient(@Qualifier("dao-client-strategy") + JanusGraphClientStrategy janusGraphClientStrategy) { + return new JanusGraphClient(janusGraphClientStrategy); } @Bean(name ="dao-client-strategy") - public TitanClientStrategy titanClientStrategy() { - return new DAOTitanStrategy(); + public JanusGraphClientStrategy janusGraphClientStrategy() { + return new DAOJanusGraphStrategy(); } @Bean - public VrfObjectFixHandler vrfObjectFixHandler(@Qualifier("titan-dao") TitanDao titanDao){ - return new VrfObjectFixHandler(titanDao); + public VrfObjectFixHandler vrfObjectFixHandler(@Qualifier("janusgraph-dao") + JanusGraphDao janusGraphDao){ + return new VrfObjectFixHandler(janusGraphDao); } } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ArtifactUuidFix.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ArtifactUuidFix.java index 03f3e41bd9..cd19c1cbf0 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ArtifactUuidFix.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ArtifactUuidFix.java @@ -8,12 +8,12 @@ import org.openecomp.sdc.asdctool.impl.validator.utils.VfModuleArtifactPayloadEx import org.openecomp.sdc.be.components.distribution.engine.VfModuleArtifactPayload; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; @@ -25,10 +25,10 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; @@ -71,7 +71,7 @@ public class ArtifactUuidFix { private static final String UTF8 = "utf-8"; @Autowired - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Autowired private ToscaOperationFacade toscaOperationFacade; @@ -140,7 +140,7 @@ public class ArtifactUuidFix { hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); log.info("Try to fetch resources with properties {} and not {}", hasProps, hasNotProps); - Either, TitanOperationStatus> servicesByCriteria = titanDao + Either, JanusGraphOperationStatus> servicesByCriteria = janusGraphDao .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, hasNotProps, JsonParseFlagEnum.ParseAll); if (servicesByCriteria.isRight()) { log.info("Failed to fetch resources {}", servicesByCriteria.right().value()); @@ -182,14 +182,14 @@ public class ArtifactUuidFix { writeModuleResultToFile(writer, resource, null); writer.flush(); } - titanDao.commit(); + janusGraphDao.commit(); } } catch (Exception e) { log.info(FAILED_TO_FETCH_VF_RESOURCES, e); return false; } finally { - titanDao.commit(); + janusGraphDao.commit(); } return true; } @@ -228,7 +228,7 @@ public class ArtifactUuidFix { writer.flush(); } - titanDao.commit(); + janusGraphDao.commit(); } } } @@ -237,7 +237,7 @@ public class ArtifactUuidFix { log.info("Failed to fetch services ", e); return false; } finally { - titanDao.commit(); + janusGraphDao.commit(); } return true; } @@ -259,7 +259,7 @@ public class ArtifactUuidFix { hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); log.info("Try to fetch services with properties {} and not {}", hasProps, hasNotProps); - Either, TitanOperationStatus> servicesByCriteria = titanDao + Either, JanusGraphOperationStatus> servicesByCriteria = janusGraphDao .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, hasNotProps, JsonParseFlagEnum.ParseAll); if (servicesByCriteria.isRight()) { log.info("Failed to fetch services {}", servicesByCriteria.right().value()); @@ -290,14 +290,14 @@ public class ArtifactUuidFix { } - titanDao.commit(); + janusGraphDao.commit(); } log.info("output file with list of services : {}", fileName); } catch (Exception e) { log.info("Failed to fetch services ", e); return false; } finally { - titanDao.commit(); + janusGraphDao.commit(); } return true; } @@ -608,7 +608,7 @@ public class ArtifactUuidFix { res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, arifacts); } - titanDao.commit(); + janusGraphDao.commit(); } else { failedList.add(component); } @@ -639,7 +639,7 @@ public class ArtifactUuidFix { res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, arifacts); } - titanDao.commit(); + janusGraphDao.commit(); } else { failedList.add(component); } @@ -660,7 +660,7 @@ public class ArtifactUuidFix { } catch (IOException e) { log.error(e.getMessage()); } finally { - titanDao.commit(); + janusGraphDao.commit(); } log.info(" Fix finished with res {} ***** ", res); return res; @@ -688,7 +688,7 @@ public class ArtifactUuidFix { Map arifacts = topologyTemplate.getToscaArtifacts(); res = fixDataOnGraph(c.getUniqueId(), VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, arifacts); - titanDao.commit(); + janusGraphDao.commit(); } else { failedList.add(c); } @@ -737,9 +737,9 @@ public class ArtifactUuidFix { } } finally { if (res) - titanDao.commit(); + janusGraphDao.commit(); else - titanDao.rollback(); + janusGraphDao.rollback(); } log.debug("Migration1707ArtifactUuidFix generateToscaPerComponent finished component name {} id {} res {}", c.getName(), c.getUniqueId(), res); @@ -751,7 +751,7 @@ public class ArtifactUuidFix { log.debug("amount groups to update: VertexTypeEnum {} EdgeLabelEnum {} data size {}", vertexTypeEnum.getName(), edgeLabelEnum, groups.size()); boolean res = true; - Either getResponse = titanDao.getVertexById(componentId, + Either getResponse = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); if (getResponse.isRight()) { log.debug("Couldn't fetch component unique id {}, error: {}", componentId, getResponse.right().value()); @@ -762,9 +762,9 @@ public class ArtifactUuidFix { GraphVertex componentVertex = getResponse.left().value(); GraphVertex toscaDataVertex = null; - Either groupVertexEither = titanDao.getChildVertex(componentVertex, + Either groupVertexEither = janusGraphDao.getChildVertex(componentVertex, edgeLabelEnum, JsonParseFlagEnum.ParseJson); - if (groupVertexEither.isRight() && groupVertexEither.right().value() == TitanOperationStatus.NOT_FOUND) { + if (groupVertexEither.isRight() && groupVertexEither.right().value() == JanusGraphOperationStatus.NOT_FOUND) { log.debug("no child {} vertex for component unique id {}, error: {}", edgeLabelEnum, componentId, groupVertexEither.right().value()); return true; @@ -777,11 +777,11 @@ public class ArtifactUuidFix { if (res) { toscaDataVertex = groupVertexEither.left().value(); toscaDataVertex.setJson(groups); - Either updatevertexEither = titanDao.updateVertex(toscaDataVertex); + Either updatevertexEither = janusGraphDao.updateVertex(toscaDataVertex); if (updatevertexEither.isRight()) { log.debug("failed to update vertex for component unique id {}, error: {}", componentId, updatevertexEither.right().value()); - titanDao.rollback(); + janusGraphDao.rollback(); return false; } } @@ -1081,7 +1081,8 @@ public class ArtifactUuidFix { Map> result = new HashMap<>(); try { - Either, TitanOperationStatus> resultsEither = titanDao.getByCriteria(type, hasProps); + Either, JanusGraphOperationStatus> resultsEither = janusGraphDao + .getByCriteria(type, hasProps); if (resultsEither.isRight()) { log.error("getVerticesToValidate failed {} ",resultsEither.right().value()); return result; @@ -1107,7 +1108,7 @@ public class ArtifactUuidFix { } else { compList.add(toscaElement.left().value()); } - titanDao.commit(); + janusGraphDao.commit(); }); @@ -1115,7 +1116,7 @@ public class ArtifactUuidFix { log.info(FAILED_TO_FETCH_VF_RESOURCES, e); } finally { - titanDao.commit(); + janusGraphDao.commit(); } return result; @@ -1161,7 +1162,7 @@ public class ArtifactUuidFix { } else { compListfull.add(toscaElement.left().value()); } - this.titanDao.commit(); + this.janusGraphDao.commit(); } compToFix.put(entry.getKey(), compListfull); @@ -1174,7 +1175,7 @@ public class ArtifactUuidFix { log.info(FAILED_TO_FETCH_VF_RESOURCES, e); return false; } finally { - titanDao.commit(); + janusGraphDao.commit(); } return result; } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphJsonValidator.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphJsonValidator.java index b404404bc6..57a7c251aa 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphJsonValidator.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphJsonValidator.java @@ -33,13 +33,13 @@ import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** - * simple util class to verify that the titan export json graph is not corrupted + * simple util class to verify that the janusgraph export json graph is not corrupted */ public class GraphJsonValidator { private static Logger log = Logger.getLogger(GraphJsonValidator.class.getName()); - public boolean verifyTitanJson(String filePath) throws IOException { + public boolean verifyJanusGraphJson(String filePath) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); List invalidRows = new ArrayList<>(); AtomicInteger atomicInteger = new AtomicInteger(1); diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphMLConverter.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphMLConverter.java index d43b3b8fcd..ee33c82da4 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphMLConverter.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/GraphMLConverter.java @@ -21,11 +21,11 @@ package org.openecomp.sdc.asdctool.impl; import com.google.gson.Gson; -import com.thinkaurelius.titan.core.TitanEdge; -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanGraphQuery; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphEdge; +import org.janusgraph.core.JanusGraphFactory; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphQuery; +import org.janusgraph.core.JanusGraphVertex; import org.apache.commons.configuration.BaseConfiguration; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.*; @@ -79,11 +79,11 @@ public class GraphMLConverter { public boolean importGraph(String[] args) { - TitanGraph graph = null; + JanusGraph graph = null; try { - String titanFileLocation = args[1]; + String janusGraphFileLocation = args[1]; String inputFile = args[2]; - graph = openGraph(titanFileLocation); + graph = openGraph(janusGraphFileLocation); List> propertiesCriteriaToDelete = new ArrayList<>(); ImmutablePair immutablePair1 = new ImmutablePair<>("healthcheckis", "GOOD"); @@ -113,11 +113,11 @@ public class GraphMLConverter { public boolean exportGraph(String[] args) { - TitanGraph graph = null; + JanusGraph graph = null; try { - String titanFileLocation = args[1]; + String janusGraphFileLocation = args[1]; String outputDirectory = args[2]; - graph = openGraph(titanFileLocation); + graph = openGraph(janusGraphFileLocation); String result = exportJsonGraph(graph, outputDirectory); @@ -140,12 +140,12 @@ public class GraphMLConverter { public String exportGraphMl(String[] args) { - TitanGraph graph = null; + JanusGraph graph = null; String result = null; try { - String titanFileLocation = args[1]; + String janusGraphFileLocation = args[1]; String outputDirectory = args[2]; - graph = openGraph(titanFileLocation); + graph = openGraph(janusGraphFileLocation); result = exportGraphMl(graph, outputDirectory); @@ -164,11 +164,11 @@ public class GraphMLConverter { public boolean findErrorInJsonGraph(String[] args) { - TitanGraph graph = null; + JanusGraph graph = null; try { - String titanFileLocation = args[1]; + String janusGraphFileLocation = args[1]; String outputDirectory = args[2]; - graph = openGraph(titanFileLocation); + graph = openGraph(janusGraphFileLocation); String result = findErrorInJsonGraph(graph, outputDirectory); @@ -189,13 +189,13 @@ public class GraphMLConverter { return true; } - public TitanGraph openGraph(String titanFileLocation) { + public JanusGraph openGraph(String janusGraphFileLocation) { - return TitanFactory.open(titanFileLocation); + return JanusGraphFactory.open(janusGraphFileLocation); } - public String exportJsonGraph(TitanGraph graph, String outputDirectory) { + public String exportJsonGraph(JanusGraph graph, String outputDirectory) { String result = null; @@ -231,7 +231,7 @@ public class GraphMLConverter { } - public String exportGraphMl(TitanGraph graph, String outputDirectory) { + public String exportGraphMl(JanusGraph graph, String outputDirectory) { String result = null; String outputFile = outputDirectory + File.separator + EXPORT_GRAPH + System.currentTimeMillis() + ".graphml"; try { @@ -253,7 +253,7 @@ public class GraphMLConverter { return builder.create(); } - public boolean importJsonGraph(TitanGraph graph, String graphJsonFile, + public boolean importJsonGraph(JanusGraph graph, String graphJsonFile, List> propertiesCriteriaToDelete) { boolean result = false; @@ -312,7 +312,7 @@ public class GraphMLConverter { } - public String findErrorInJsonGraph(TitanGraph graph, String outputDirectory) { + public String findErrorInJsonGraph(JanusGraph graph, String outputDirectory) { boolean runVertexScan = false; boolean runEdgeScan = false; @@ -331,8 +331,8 @@ public class GraphMLConverter { Vertex vertexTo = null; Edge edge = null; - Iterable edges = graph.query().edges(); - Iterator iterator = edges.iterator(); + Iterable edges = graph.query().edges(); + Iterator iterator = edges.iterator(); while (iterator.hasNext()) { try { @@ -344,12 +344,12 @@ public class GraphMLConverter { BaseConfiguration conf = new BaseConfiguration(); conf.setProperty(STORAGE_BACKEND, INMEMORY); - TitanGraph openGraph = Utils.openGraph(conf); + JanusGraph openGraph = Utils.openGraph(conf); - TitanVertex addVertexFrom = openGraph.addVertex(); + JanusGraphVertex addVertexFrom = openGraph.addVertex(); Utils.setProperties(addVertexFrom, Utils.getProperties(vertexFrom)); - TitanVertex addVertexTo = openGraph.addVertex(); + JanusGraphVertex addVertexTo = openGraph.addVertex(); Utils.setProperties(addVertexTo, Utils.getProperties(vertexTo)); Edge addEdge = addVertexFrom.addEdge(edge.label(), addVertexTo); @@ -394,9 +394,9 @@ public class GraphMLConverter { BaseConfiguration conf = new BaseConfiguration(); conf.setProperty(STORAGE_BACKEND, INMEMORY); - TitanGraph openGraph = Utils.openGraph(conf); + JanusGraph openGraph = Utils.openGraph(conf); - TitanVertex addVertexFrom = openGraph.addVertex(); + JanusGraphVertex addVertexFrom = openGraph.addVertex(); Utils.setProperties(addVertexFrom, Utils.getProperties(vertex)); log.info(FROM_VERTEX, Utils.getProperties(addVertexFrom)); @@ -426,7 +426,7 @@ public class GraphMLConverter { } - Iterable vertices2 = graph.query() + Iterable vertices2 = graph.query() .has(GraphPropertiesDictionary.HEALTH_CHECK.getProperty(), "GOOD").vertices(); ; @@ -458,17 +458,17 @@ public class GraphMLConverter { } - private void removeNodesByLabel(TitanGraph graph, String label) { - Iterable vertices = graph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), label) + private void removeNodesByLabel(JanusGraph graph, String label) { + Iterable vertices = graph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), label) .vertices(); - Iterator iterator = vertices.iterator(); + Iterator iterator = vertices.iterator(); while (iterator.hasNext()) { Vertex next2 = iterator.next(); next2.remove(); } } - public String exportUsers(TitanGraph graph, String outputDirectory) { + public String exportUsers(JanusGraph graph, String outputDirectory) { List> users = new ArrayList<>(); String result = null; @@ -478,11 +478,11 @@ public class GraphMLConverter { FileWriter fileWriter = null; try { - TitanGraphQuery graphQuery = graph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), + JanusGraphQuery graphQuery = graph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); @SuppressWarnings("unchecked") - Iterable vertices = graphQuery.vertices(); + Iterable vertices = graphQuery.vertices(); if (vertices != null) { for (Vertex v : vertices) { @@ -538,11 +538,11 @@ public class GraphMLConverter { public boolean exportUsers(String[] args) { - TitanGraph graph = null; + JanusGraph graph = null; try { - String titanFileLocation = args[1]; + String janusGraphFileLocation = args[1]; String outputDirectory = args[2]; - graph = openGraph(titanFileLocation); + graph = openGraph(janusGraphFileLocation); String result = exportUsers(graph, outputDirectory); diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/JanusGraphInitializer.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/JanusGraphInitializer.java new file mode 100644 index 0000000000..fbebe2cd27 --- /dev/null +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/JanusGraphInitializer.java @@ -0,0 +1,204 @@ +/*- + * ============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.asdctool.impl; + +import org.janusgraph.core.*; +import org.janusgraph.core.schema.ConsistencyModifier; +import org.janusgraph.core.schema.JanusGraphIndex; +import org.janusgraph.core.schema.JanusGraphManagement; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.utils.UserStatusEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.resources.data.UserData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class JanusGraphInitializer { + + private static Logger logger = LoggerFactory.getLogger(JanusGraphInitializer.class.getName()); + private static JanusGraph graph; + + public static boolean createGraph(String janusGraphCfgFile) { + logger.info("** createGraph with {}", janusGraphCfgFile); + try { + logger.info("createGraph : try to load file {}", janusGraphCfgFile); + graph = JanusGraphFactory.open(janusGraphCfgFile); + if (graph.isClosed()) { + return false; + } + + } catch (JanusGraphException e) { + logger.info("createGraph : failed to open JanusGraph graph with configuration file: {}", janusGraphCfgFile, e); + return false; + } + + createIndexesAndDefaults(); + + logger.info("** JanusGraph graph created "); + + return true; + } + + private static boolean isVertexExist(Map properties) { + JanusGraphQuery query = graph.query(); + + if (properties != null && !properties.isEmpty()) { + for (Map.Entry entry : properties.entrySet()) { + query = query.has(entry.getKey(), entry.getValue()); + } + } + Iterable vertecies = query.vertices(); + java.util.Iterator iterator = vertecies.iterator(); + if (iterator.hasNext()) { + return true; + } + return false; + } + + private static boolean isVertexNotExist(Map properties) { + return !isVertexExist(properties); + } + + private static void createDefaultAdminUser() { + createUser(getDefaultUserAdmin()); + graph.tx().commit(); + + } + + private static void createUser(UserData user) { + Map checkedProperties = new HashMap<>(); + checkedProperties.put(GraphPropertiesDictionary.USERID.getProperty(), user.getUserId()); + checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); + Map properties = null; + if (!isVertexExist(checkedProperties)) { + Vertex vertex = graph.addVertex(); + vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); + properties = user.toGraphMap(); + for (Map.Entry entry : properties.entrySet()) { + vertex.property(entry.getKey(), entry.getValue()); + } + } + } + + private static UserData getDefaultUserAdmin() { + UserData userData = new UserData(); + userData.setAction(ActionEnum.Create); + userData.setElementType(GraphElementTypeEnum.Node); + userData.setUserId("jh0003"); + userData.setEmail("admin@sdc.com"); + userData.setFirstName("Jimmy"); + userData.setLastName("Hendrix"); + userData.setRole("ADMIN"); + userData.setStatus(UserStatusEnum.ACTIVE.name()); + userData.setLastLoginTime(0L); + return userData; + } + + private static void createVertexIndixes() { + logger.info("** createVertexIndixes started"); + + JanusGraphManagement graphMgt = graph.openManagement(); + JanusGraphIndex index = null; + for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) { + PropertyKey propKey = null; + if (!graphMgt.containsPropertyKey(prop.getProperty())) { + Class clazz = prop.getClazz(); + if (!clazz.isAssignableFrom(ArrayList.class) && !clazz.isAssignableFrom(HashMap.class)) { + propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); + } + } else { + propKey = graphMgt.getPropertyKey(prop.getProperty()); + } + if (prop.isIndexed()) { + if (!graphMgt.containsGraphIndex(prop.getProperty())) { + if (prop.isUnique()) { + index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex(); + + graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures + // only + // one + // name + // per + // vertex + graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures + // name + // uniqueness + // in + // the + // graph + + } else { + graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex(); + } + } + } + } + graphMgt.commit(); + logger.info("** createVertexIndixes ended"); + + } + + private static void createEdgeIndixes() { + logger.info("** createEdgeIndixes started"); + JanusGraphManagement graphMgt = graph.openManagement(); + for (GraphEdgePropertiesDictionary prop : GraphEdgePropertiesDictionary.values()) { + if (!graphMgt.containsGraphIndex(prop.getProperty())) { + PropertyKey propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); + graphMgt.buildIndex(prop.getProperty(), Edge.class).addKey(propKey).buildCompositeIndex(); + + } + } + graphMgt.commit(); + logger.info("** createEdgeIndixes ended"); + } + + private static void createIndexesAndDefaults() { + createVertexIndixes(); + createEdgeIndixes(); + createDefaultAdminUser(); + createRootVertex(VertexTypeEnum.CATALOG_ROOT); + createRootVertex(VertexTypeEnum.ARCHIVE_ROOT); + } + + private static void createRootVertex(VertexTypeEnum vertexTypeEnum) { + Map checkedProperties = new HashMap<>(); + checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), vertexTypeEnum.getName()); + if (isVertexNotExist(checkedProperties)) { + Vertex vertex = graph.addVertex(); + vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty(), IdBuilderUtils.generateUniqueId()); + vertex.property(GraphPropertyEnum.LABEL.getProperty(), vertexTypeEnum.getName()); + graph.tx().commit(); + } + } + +} diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ProductLogic.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ProductLogic.java index d8b8936dca..883f5e50f4 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ProductLogic.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ProductLogic.java @@ -20,9 +20,9 @@ package org.openecomp.sdc.asdctool.impl; -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphFactory; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -39,10 +39,10 @@ public class ProductLogic { private static Logger log = Logger.getLogger(ProductLogic.class.getName()); - public boolean deleteAllProducts(String titanFile, String beHost, String bePort, String adminUser) { + public boolean deleteAllProducts(String janusGraphFile, String beHost, String bePort, String adminUser) { log.debug("retrieving all products from graph"); RestUtils restUtils = null; - List productList = getAllProducts(titanFile); + List productList = getAllProducts(janusGraphFile); restUtils = new RestUtils(); if (productList != null) { for (String productUid : productList) { @@ -56,15 +56,15 @@ public class ProductLogic { } } - private List getAllProducts(String titanFile) { - TitanGraph graph = null; + private List getAllProducts(String janusGraphFile) { + JanusGraph graph = null; try { - graph = openGraph(titanFile); + graph = openGraph(janusGraphFile); List productsToDelete = new ArrayList(); Iterable vertices = graph.query() .has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Product.getName()).vertices(); if (vertices != null) { - Iterator iter = vertices.iterator(); + Iterator iter = vertices.iterator(); while (iter.hasNext()) { Vertex vertex = iter.next(); String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); @@ -88,9 +88,9 @@ public class ProductLogic { } } - private TitanGraph openGraph(String titanFileLocation) { + private JanusGraph openGraph(String janusGraphFileLocation) { - return TitanFactory.open(titanFileLocation); + return JanusGraphFactory.open(janusGraphFileLocation); } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/TitanGraphInitializer.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/TitanGraphInitializer.java deleted file mode 100644 index 8b89cc2706..0000000000 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/TitanGraphInitializer.java +++ /dev/null @@ -1,204 +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.asdctool.impl; - -import com.thinkaurelius.titan.core.*; -import com.thinkaurelius.titan.core.schema.ConsistencyModifier; -import com.thinkaurelius.titan.core.schema.TitanGraphIndex; -import com.thinkaurelius.titan.core.schema.TitanManagement; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum; -import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; -import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; -import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.utils.UserStatusEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.resources.data.UserData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -public class TitanGraphInitializer { - - private static Logger logger = LoggerFactory.getLogger(TitanGraphInitializer.class.getName()); - private static TitanGraph graph; - - public static boolean createGraph(String titanCfgFile) { - logger.info("** createGraph with {}", titanCfgFile); - try { - logger.info("createGraph : try to load file {}", titanCfgFile); - graph = TitanFactory.open(titanCfgFile); - if (graph.isClosed()) { - return false; - } - - } catch (TitanException e) { - logger.info("createGraph : failed to open Titan graph with configuration file: {}", titanCfgFile, e); - return false; - } - - createIndexesAndDefaults(); - - logger.info("** Titan graph created "); - - return true; - } - - private static boolean isVertexExist(Map properties) { - TitanGraphQuery query = graph.query(); - - if (properties != null && !properties.isEmpty()) { - for (Map.Entry entry : properties.entrySet()) { - query = query.has(entry.getKey(), entry.getValue()); - } - } - Iterable vertecies = query.vertices(); - java.util.Iterator iterator = vertecies.iterator(); - if (iterator.hasNext()) { - return true; - } - return false; - } - - private static boolean isVertexNotExist(Map properties) { - return !isVertexExist(properties); - } - - private static void createDefaultAdminUser() { - createUser(getDefaultUserAdmin()); - graph.tx().commit(); - - } - - private static void createUser(UserData user) { - Map checkedProperties = new HashMap<>(); - checkedProperties.put(GraphPropertiesDictionary.USERID.getProperty(), user.getUserId()); - checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); - Map properties = null; - if (!isVertexExist(checkedProperties)) { - Vertex vertex = graph.addVertex(); - vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); - properties = user.toGraphMap(); - for (Map.Entry entry : properties.entrySet()) { - vertex.property(entry.getKey(), entry.getValue()); - } - } - } - - private static UserData getDefaultUserAdmin() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("jh0003"); - userData.setEmail("admin@sdc.com"); - userData.setFirstName("Jimmy"); - userData.setLastName("Hendrix"); - userData.setRole("ADMIN"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - private static void createVertexIndixes() { - logger.info("** createVertexIndixes started"); - - TitanManagement graphMgt = graph.openManagement(); - TitanGraphIndex index = null; - for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) { - PropertyKey propKey = null; - if (!graphMgt.containsPropertyKey(prop.getProperty())) { - Class clazz = prop.getClazz(); - if (!clazz.isAssignableFrom(ArrayList.class) && !clazz.isAssignableFrom(HashMap.class)) { - propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); - } - } else { - propKey = graphMgt.getPropertyKey(prop.getProperty()); - } - if (prop.isIndexed()) { - if (!graphMgt.containsGraphIndex(prop.getProperty())) { - if (prop.isUnique()) { - index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex(); - - graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures - // only - // one - // name - // per - // vertex - graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures - // name - // uniqueness - // in - // the - // graph - - } else { - graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex(); - } - } - } - } - graphMgt.commit(); - logger.info("** createVertexIndixes ended"); - - } - - private static void createEdgeIndixes() { - logger.info("** createEdgeIndixes started"); - TitanManagement graphMgt = graph.openManagement(); - for (GraphEdgePropertiesDictionary prop : GraphEdgePropertiesDictionary.values()) { - if (!graphMgt.containsGraphIndex(prop.getProperty())) { - PropertyKey propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); - graphMgt.buildIndex(prop.getProperty(), Edge.class).addKey(propKey).buildCompositeIndex(); - - } - } - graphMgt.commit(); - logger.info("** createEdgeIndixes ended"); - } - - private static void createIndexesAndDefaults() { - createVertexIndixes(); - createEdgeIndixes(); - createDefaultAdminUser(); - createRootVertex(VertexTypeEnum.CATALOG_ROOT); - createRootVertex(VertexTypeEnum.ARCHIVE_ROOT); - } - - private static void createRootVertex(VertexTypeEnum vertexTypeEnum) { - Map checkedProperties = new HashMap<>(); - checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), vertexTypeEnum.getName()); - if (isVertexNotExist(checkedProperties)) { - Vertex vertex = graph.addVertex(); - vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty(), IdBuilderUtils.generateUniqueId()); - vertex.property(GraphPropertyEnum.LABEL.getProperty(), vertexTypeEnum.getName()); - graph.tx().commit(); - } - } - -} diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/TitanToJanusGraphMigration.groovy b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/TitanToJanusGraphMigration.groovy new file mode 100644 index 0000000000..9c69a781c1 --- /dev/null +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/TitanToJanusGraphMigration.groovy @@ -0,0 +1,66 @@ +/* + * Before starting the migration, please make sure to create a backup of sdctitan keyspace in cassandra + * + * Usage Instructions : + * 1. Download JanusGraph gremlin in-built package from below URL; + * https://github.com/JanusGraph/janusgraph/releases/download/v0.3.1/janusgraph-0.3.1-hadoop2.zip + * 2. Unzip it and navigate to bin folder. + * 3. Run below command. + * Command : ./gremlin.sh -l -e + * Example : ./gremlin.sh -l ERROR -e /data/scripts/TitanToJanusGraphMigration.groovy /data/scripts/titan.properties + * + * Note: Please make sure that the above provided property file have the below field present; + * graph.allow-upgrade=true +*/ + +// Check for open database connections; should be only one +def Object checkAndCloseMultipleInstances(Object mgmt, Object graph, long sleepTime){ + if(mgmt.getOpenInstances().size() > 1) { + for (String instanceId in mgmt.getOpenInstances()) + if(!instanceId.contains("current")) + mgmt.forceCloseInstance(instanceId); + mgmt.commit(); + sleep(sleepTime); + mgmt = graph.openManagement(); + } + return mgmt; +} + +// Update the ID Store +def updateGraphIDStore(Object mgmt, long sleepTime){ + mgmt.set('ids.store-name', 'titan_ids'); + mgmt.commit(); + sleep(sleepTime); +} + +// Verify the ID Store +def verifyUpdatedGraphIDStore(String propertyPath){ + graph = JanusGraphFactory.open(propertyPath); + mgmt = graph.openManagement(); + if(!mgmt.get('ids.store-name').equals("titan_ids")) + throw new GroovyRuntimeException("FAILURE -> Error in setting up the ID Store to titan_ids; please contact system administrator... "); + else + println("SUCCESS -> Titan ID Store has also been set correctly... "); +} + +try { + graph = JanusGraphFactory.open(args[0]); + mgmt = graph.openManagement(); + + // Check if titan graph is upgraded to Janus Graph compatibility + if(mgmt.get('graph.titan-version').equals("1.0.0")) + throw new GroovyRuntimeException("FAILURE -> Titan graph is not upgraded to Janus. please make sure graph.allow-upgrade property is set to true in properties file and re-run the script."); + println("SUCCESS -> Titan Graph data is upgraded to Janus compatible Graph... "); + + // Update the ID Store if required + if(mgmt.get('ids.store-name').equals("janusgraph_ids")){ + mgmt = checkAndCloseMultipleInstances(mgmt, graph,2000l); + updateGraphIDStore(mgmt, 2000l); + verifyUpdatedGraphIDStore(args[0]); + } + println("SUCCESS -> Titan to Janus Graph upgrade process is now complete... "); + +} catch(Exception ex){ + println("FAILURE -> Titan to Janus Graph migration process has failed; please check the exception trace for more details."); + throw ex; +} diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/UpdatePropertyOnVertex.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/UpdatePropertyOnVertex.java index 774af480ee..9911fb73f3 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/UpdatePropertyOnVertex.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/UpdatePropertyOnVertex.java @@ -20,9 +20,9 @@ package org.openecomp.sdc.asdctool.impl; -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanGraphQuery; +import org.janusgraph.core.JanusGraphFactory; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphQuery; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.openecomp.sdc.asdctool.Utils; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; @@ -38,21 +38,21 @@ public class UpdatePropertyOnVertex { private static Logger log = Logger.getLogger(UpdatePropertyOnVertex.class.getName()); - public Integer updatePropertyOnServiceAtLeastCertified(String titanFile, Map keyValueToSet, + public Integer updatePropertyOnServiceAtLeastCertified(String janusGraphFile, Map keyValueToSet, List> orCriteria) { - TitanGraph graph = null; + JanusGraph graph = null; Integer numberOfUpdatedVertexes = 0; try { - graph = openGraph(titanFile); + graph = openGraph(janusGraphFile); if (orCriteria != null && false == orCriteria.isEmpty()) { for (Map criteria : orCriteria) { - TitanGraphQuery query = graph.query(); + JanusGraphQuery query = graph.query(); if (criteria != null && !criteria.isEmpty()) { for (Map.Entry entry : criteria.entrySet()) { @@ -112,10 +112,10 @@ public class UpdatePropertyOnVertex { } - private Integer updateVertexes(Map keyValueToSet, TitanGraph graph, Map criteria) { + private Integer updateVertexes(Map keyValueToSet, JanusGraph graph, Map criteria) { Integer numberOfUpdatedVertexesPerService = 0; - TitanGraphQuery updateQuery = graph.query(); + JanusGraphQuery updateQuery = graph.query(); if (criteria != null && !criteria.isEmpty()) { for (Map.Entry entry : criteria.entrySet()) { @@ -159,9 +159,9 @@ public class UpdatePropertyOnVertex { return numberOfUpdatedVertexesPerService; } - public TitanGraph openGraph(String titanFileLocation) { + public JanusGraph openGraph(String janusGraphFileLocation) { - TitanGraph graph = TitanFactory.open(titanFileLocation); + JanusGraph graph = JanusGraphFactory.open(janusGraphFileLocation); return graph; diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/VrfObjectFixHandler.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/VrfObjectFixHandler.java index 8eec51071f..1c7afef1c3 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/VrfObjectFixHandler.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/VrfObjectFixHandler.java @@ -6,18 +6,18 @@ 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.asdctool.migration.tasks.handlers.XlsOutputHandler; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.common.log.wrappers.Logger; @@ -42,10 +42,10 @@ public class VrfObjectFixHandler { private XlsOutputHandler outputHandler; private final String sheetName = this.getClass().getSimpleName() + "Report"; - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; - public VrfObjectFixHandler(TitanDao titanDao) { - this.titanDao = titanDao; + public VrfObjectFixHandler(JanusGraphDao janusGraphDao) { + this.janusGraphDao = janusGraphDao; } public boolean handle(String mode, String outputPath) { @@ -65,10 +65,10 @@ public class VrfObjectFixHandler { try{ Map>> corruptedData = fetchCorruptedData(); corruptedData.forEach(this::fixCorruptedVfrObjectAndRelatedInstances); - titanDao.commit(); + janusGraphDao.commit(); writeOutput(corruptedData); } catch (Exception e){ - titanDao.rollback(); + janusGraphDao.rollback(); log.debug("#fixCorruptedData - Failed to detect corrupted data. The exception occurred: ", e); return false; } @@ -93,7 +93,7 @@ public class VrfObjectFixHandler { private void fixCorruptedVfrObject(GraphVertex vfrObjectV) { vfrObjectV.getMetadataProperties().put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, VALID_TOSCA_NAME); - titanDao.updateVertex(vfrObjectV).left().on(this::rightOnUpdate); + janusGraphDao.updateVertex(vfrObjectV).left().on(this::rightOnUpdate); } private Map>> fetchCorruptedData(){ @@ -106,7 +106,7 @@ public class VrfObjectFixHandler { private List getCorruptedVrfObjects() { Map props = new EnumMap<>(GraphPropertyEnum.class); props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, "org.openecomp.resource.configuration.VRFObject"); - return titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, props).left().on(this::rightOnGet); + return janusGraphDao.getByCriteria(VertexTypeEnum.NODE_TYPE, props).left().on(this::rightOnGet); } private void fillCorruptedData(GraphVertex vrfObjectV, Map>> findToUpdate) { @@ -115,7 +115,8 @@ public class VrfObjectFixHandler { Iterator instanceEdges = vrfObjectV.getVertex().edges(Direction.IN, EdgeLabelEnum.INSTANCE_OF.name()); while(instanceEdges.hasNext()){ Edge edge = instanceEdges.next(); - putCorruptedInstances(corruptedInstances, edge, (List) titanDao.getProperty(edge, EdgePropertyEnum.INSTANCES)); + putCorruptedInstances(corruptedInstances, edge, (List) janusGraphDao + .getProperty(edge, EdgePropertyEnum.INSTANCES)); } } @@ -139,7 +140,7 @@ public class VrfObjectFixHandler { String jsonMetadataStr = JsonParserUtils.toJson(jsonObj); container.property(GraphPropertyEnum.JSON.getProperty(), jsonMetadataStr); } catch (IOException e) { - throw new StorageException("Failed to fix the corrupted instances of the container", e, TitanOperationStatus.GENERAL_ERROR); + throw new StorageException("Failed to fix the corrupted instances of the container", e, JanusGraphOperationStatus.GENERAL_ERROR); } } @@ -159,7 +160,7 @@ public class VrfObjectFixHandler { private Map getJsonMap(Vertex container) { String json = (String)container.property(GraphPropertyEnum.JSON.getProperty()).value(); - Map properties = titanDao.getVertexProperties(container); + Map properties = janusGraphDao.getVertexProperties(container); VertexTypeEnum label = VertexTypeEnum.getByName((String) (properties.get(GraphPropertyEnum.LABEL))); return JsonParserUtils.toMap(json, label != null ? label.getClassOfJson() : null); } @@ -175,13 +176,13 @@ public class VrfObjectFixHandler { } } - private List rightOnGet(TitanOperationStatus status) { - if(status == TitanOperationStatus.NOT_FOUND){ + private List rightOnGet(JanusGraphOperationStatus status) { + if(status == JanusGraphOperationStatus.NOT_FOUND){ return emptyList(); } throw new StorageException(status); } - private GraphVertex rightOnUpdate(TitanOperationStatus status) { + private GraphVertex rightOnUpdate(JanusGraphOperationStatus status) { throw new StorageException(status); } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/internal/tool/CsarGenerator.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/internal/tool/CsarGenerator.java index 7007c6dd5e..40680af56f 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/internal/tool/CsarGenerator.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/internal/tool/CsarGenerator.java @@ -42,33 +42,27 @@ import java.util.stream.Collectors; import org.openecomp.sdc.asdctool.utils.ConsoleWriter; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.be.tosca.CsarUtils; -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.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.GeneralUtility; -import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; - @org.springframework.stereotype.Component("csarGenerator") public class CsarGenerator extends CommonInternalTool { public CsarGenerator() { @@ -76,7 +70,7 @@ public class CsarGenerator extends CommonInternalTool { } @Autowired - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Autowired private CsarUtils csarUtils; @Autowired @@ -90,14 +84,15 @@ public class CsarGenerator extends CommonInternalTool { private static Logger log = Logger.getLogger(CsarGenerator.class.getName()); public void generateCsar(String uuid, Scanner scanner) { - TitanOperationStatus status = TitanOperationStatus.OK; + JanusGraphOperationStatus status = JanusGraphOperationStatus.OK; Map props = new EnumMap<>(GraphPropertyEnum.class); props.put(GraphPropertyEnum.UUID, uuid); props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); props.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - List byCriterria = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props).either(l -> l, r -> null); + List byCriterria = janusGraphDao + .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props).either(l -> l, r -> null); if (byCriterria != null && !byCriterria.isEmpty()) { if (byCriterria.size() > 1) { ConsoleWriter.dataLine("Warning ! More that 1 certified service with uuid", uuid); @@ -116,15 +111,15 @@ public class CsarGenerator extends CommonInternalTool { } else { ConsoleWriter.dataLine("No certified service with UUID", uuid); } - if (status == TitanOperationStatus.OK) { - titanDao.commit(); + if (status == JanusGraphOperationStatus.OK) { + janusGraphDao.commit(); } else { - titanDao.rollback(); + janusGraphDao.rollback(); } } - private TitanOperationStatus handleService(GraphVertex metadataV, String uuid) { - TitanOperationStatus status = TitanOperationStatus.OK; + private JanusGraphOperationStatus handleService(GraphVertex metadataV, String uuid) { + JanusGraphOperationStatus status = JanusGraphOperationStatus.OK; org.openecomp.sdc.be.model.Component component = toscaOperationFacade.getToscaFullElement(metadataV.getUniqueId()).either(l -> l, r -> null); if (component != null) { @@ -134,11 +129,12 @@ public class CsarGenerator extends CommonInternalTool { supplier = () -> generateCsarPayload(component); generateArtifact(component, ArtifactTypeEnum.TOSCA_CSAR, supplier); - GraphVertex toscaArtifactV = titanDao.getChildVertex(metadataV, EdgeLabelEnum.TOSCA_ARTIFACTS, JsonParseFlagEnum.ParseJson).either(l->l, r->null); + GraphVertex toscaArtifactV = janusGraphDao + .getChildVertex(metadataV, EdgeLabelEnum.TOSCA_ARTIFACTS, JsonParseFlagEnum.ParseJson).either(l->l, r->null); if ( toscaArtifactV != null ){ Map copy = component.getToscaArtifacts().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); toscaArtifactV.setJson(copy); - titanDao.updateVertex(toscaArtifactV); + janusGraphDao.updateVertex(toscaArtifactV); } } else { @@ -147,8 +143,8 @@ public class CsarGenerator extends CommonInternalTool { return status; } - private TitanOperationStatus generateArtifact(Component component, ArtifactTypeEnum artifactType, Supplier supplier){ - TitanOperationStatus status = TitanOperationStatus.GENERAL_ERROR; + private JanusGraphOperationStatus generateArtifact(Component component, ArtifactTypeEnum artifactType, Supplier supplier){ + JanusGraphOperationStatus status = JanusGraphOperationStatus.GENERAL_ERROR; ArtifactDefinition csarArtifact = null; Optional op = component.getToscaArtifacts().values().stream().filter(p -> p.getArtifactType().equals(artifactType.getType())).findAny(); if (op.isPresent()) { @@ -166,12 +162,12 @@ public class CsarGenerator extends CommonInternalTool { return toscaExportHandler.exportComponent(component).either(l -> l.getMainYaml().getBytes(), r -> null); } - private TitanOperationStatus savePayload(org.openecomp.sdc.be.model.Component component, ArtifactDefinition csarArtifact, Supplier supplier) { + private JanusGraphOperationStatus savePayload(org.openecomp.sdc.be.model.Component component, ArtifactDefinition csarArtifact, Supplier supplier) { byte[] payload = supplier.get(); if ( payload == null ) { ConsoleWriter.dataLine("create artifact failed ", csarArtifact.getArtifactLabel()); - return TitanOperationStatus.GENERAL_ERROR; + return JanusGraphOperationStatus.GENERAL_ERROR; } ConsoleWriter.dataLine("createartifact success ", csarArtifact.getArtifactLabel()); csarArtifact.setPayload(payload); @@ -190,7 +186,7 @@ public class CsarGenerator extends CommonInternalTool { ConsoleWriter.dataLine("Artifact generated and saved into Cassandra ", csarArtifact.getArtifactLabel()); report(component, csarArtifact); - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } private void report(org.openecomp.sdc.be.model.Component component, ArtifactDefinition csarArtifact) { diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/internal/tool/DeleteComponentHandler.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/internal/tool/DeleteComponentHandler.java index e7f42c9614..76fcec8186 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/internal/tool/DeleteComponentHandler.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/internal/tool/DeleteComponentHandler.java @@ -29,21 +29,21 @@ */ package org.openecomp.sdc.asdctool.impl.internal.tool; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; 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.asdctool.utils.ConsoleWriter; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTypeOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementOperation; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -56,7 +56,7 @@ import java.util.Scanner; @Component("deleteComponentHandler") public class DeleteComponentHandler extends CommonInternalTool{ @Autowired - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Autowired private NodeTypeOperation nodeTypeOperation; @Autowired @@ -70,23 +70,23 @@ public class DeleteComponentHandler extends CommonInternalTool{ super("delete"); } public void deleteComponent(String id, Scanner scanner) { - TitanOperationStatus status = TitanOperationStatus.OK; - GraphVertex metadataVertex = titanDao.getVertexById(id).either(l -> l, r -> null); + JanusGraphOperationStatus status = JanusGraphOperationStatus.OK; + GraphVertex metadataVertex = janusGraphDao.getVertexById(id).either(l -> l, r -> null); if (metadataVertex != null) { status = handleComponent(scanner, metadataVertex); } else { ConsoleWriter.dataLine("No vertex for id", id); } - if (status == TitanOperationStatus.OK) { - titanDao.commit(); + if (status == JanusGraphOperationStatus.OK) { + janusGraphDao.commit(); } else { - titanDao.rollback(); + janusGraphDao.rollback(); } } - private TitanOperationStatus handleComponent(Scanner scanner, GraphVertex metadataVertex) { + private JanusGraphOperationStatus handleComponent(Scanner scanner, GraphVertex metadataVertex) { Map metadataProperties = metadataVertex.getMetadataProperties(); - TitanOperationStatus status = TitanOperationStatus.OK; + JanusGraphOperationStatus status = JanusGraphOperationStatus.OK; printComponentInfo(metadataProperties); Iterator edges = metadataVertex.getVertex().edges(Direction.OUT, EdgeLabelEnum.VERSION.name()); @@ -107,12 +107,12 @@ public class DeleteComponentHandler extends CommonInternalTool{ return status; } - private TitanOperationStatus handleComponent(GraphVertex metadataVertex) { + private JanusGraphOperationStatus handleComponent(GraphVertex metadataVertex) { ToscaElementOperation toscaElementOperation = getOperationByLabel(metadataVertex); Iterator edges = metadataVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name()); if (edges != null && edges.hasNext()) { - TitanOperationStatus status = updatePreviousVersion(metadataVertex, edges); - if ( status != TitanOperationStatus.OK ){ + JanusGraphOperationStatus status = updatePreviousVersion(metadataVertex, edges); + if ( status != JanusGraphOperationStatus.OK ){ return status; } } @@ -121,28 +121,28 @@ public class DeleteComponentHandler extends CommonInternalTool{ .map(l -> { ConsoleWriter.dataLine("\nDeleted"); report(metadataVertex); - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; }) .right() .map(r-> { ConsoleWriter.dataLine("\nFailed to delete. see log file"); return r; }); - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } - private TitanOperationStatus updatePreviousVersion(GraphVertex metadataVertex, Iterator edges) { + private JanusGraphOperationStatus updatePreviousVersion(GraphVertex metadataVertex, Iterator edges) { Edge edge = edges.next(); - TitanVertex prevVersionVertex = (TitanVertex) edge.outVertex(); + JanusGraphVertex prevVersionVertex = (JanusGraphVertex) edge.outVertex(); // check if previous version is deleted - Boolean isDeleted = (Boolean) titanDao.getProperty(prevVersionVertex, GraphPropertyEnum.IS_DELETED.getProperty()); + Boolean isDeleted = (Boolean) janusGraphDao.getProperty(prevVersionVertex, GraphPropertyEnum.IS_DELETED.getProperty()); if (isDeleted != null && isDeleted) { ConsoleWriter.dataLine("\nPrevoius version is marked as deleted. Component cannot be deleted"); - return TitanOperationStatus.GENERAL_ERROR; + return JanusGraphOperationStatus.GENERAL_ERROR; } // update highest property for previous version - TitanOperationStatus status = updateStateOfPreviuosVersion(prevVersionVertex); - if ( TitanOperationStatus.OK != status ){ + JanusGraphOperationStatus status = updateStateOfPreviuosVersion(prevVersionVertex); + if ( JanusGraphOperationStatus.OK != status ){ return status; } @@ -150,51 +150,54 @@ public class DeleteComponentHandler extends CommonInternalTool{ return connectToCatalogAndArchive(metadataVertex, prevVersionVertex); } - private TitanOperationStatus updateStateOfPreviuosVersion(TitanVertex prevVersionVertex) { - String prevId = (String) titanDao.getProperty(prevVersionVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()); - Either prevGraphVertex = titanDao.getVertexById(prevId); + private JanusGraphOperationStatus updateStateOfPreviuosVersion(JanusGraphVertex prevVersionVertex) { + String prevId = (String) janusGraphDao.getProperty(prevVersionVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()); + Either prevGraphVertex = janusGraphDao.getVertexById(prevId); GraphVertex prevVertex = prevGraphVertex.left().value(); prevVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - titanDao.updateVertex(prevVertex); + janusGraphDao.updateVertex(prevVertex); Iterator edgesIter = prevVersionVertex.edges(Direction.IN, EdgeLabelEnum.LAST_STATE.name()); if ( edgesIter.hasNext() ) { Edge lastStateEdge = edgesIter.next(); Vertex lastModifier = lastStateEdge.outVertex(); - TitanOperationStatus replaceRes = titanDao.replaceEdgeLabel(lastModifier, prevVersionVertex, lastStateEdge, EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE); - if (replaceRes != TitanOperationStatus.OK) { + JanusGraphOperationStatus + replaceRes = janusGraphDao + .replaceEdgeLabel(lastModifier, prevVersionVertex, lastStateEdge, EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE); + if (replaceRes != JanusGraphOperationStatus.OK) { log.info("Failed to replace label from {} to {}. status = {}", EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE, replaceRes); ConsoleWriter.dataLine("\nFailed to replace LAST_STATE edge . Failed to delete"); - return TitanOperationStatus.GENERAL_ERROR; + return JanusGraphOperationStatus.GENERAL_ERROR; } } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } - private TitanOperationStatus connectToCatalogAndArchive(GraphVertex metadataVertex, TitanVertex prevVersionVertex) { + private JanusGraphOperationStatus connectToCatalogAndArchive(GraphVertex metadataVertex, JanusGraphVertex prevVersionVertex) { - TitanOperationStatus status = connectByLabel(metadataVertex, prevVersionVertex, EdgeLabelEnum.CATALOG_ELEMENT, VertexTypeEnum.CATALOG_ROOT); - if ( status == TitanOperationStatus.OK ){ + JanusGraphOperationStatus + status = connectByLabel(metadataVertex, prevVersionVertex, EdgeLabelEnum.CATALOG_ELEMENT, VertexTypeEnum.CATALOG_ROOT); + if ( status == JanusGraphOperationStatus.OK ){ status = connectByLabel(metadataVertex, prevVersionVertex, EdgeLabelEnum.ARCHIVE_ELEMENT, VertexTypeEnum.ARCHIVE_ROOT); } return status; } - private TitanOperationStatus connectByLabel(GraphVertex metadataVertex, TitanVertex prevVersionVertex, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexlabel) { + private JanusGraphOperationStatus connectByLabel(GraphVertex metadataVertex, JanusGraphVertex prevVersionVertex, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexlabel) { Iterator edgesToCatalog = metadataVertex.getVertex().edges(Direction.IN, edgeLabel.name()); if ( edgesToCatalog != null && edgesToCatalog.hasNext() ){ //exist edge move to prev version - Either catalog = titanDao.getVertexByLabel(vertexlabel); + Either catalog = janusGraphDao.getVertexByLabel(vertexlabel); if (catalog.isRight()) { log.debug("Failed to fetch {} vertex, error {}", vertexlabel, catalog.right().value()); return catalog.right().value(); } GraphVertex catalogV = catalog.left().value(); Edge edge = edgesToCatalog.next(); - return titanDao.createEdge(catalogV.getVertex(), prevVersionVertex, edgeLabel, edge ); + return janusGraphDao.createEdge(catalogV.getVertex(), prevVersionVertex, edgeLabel, edge ); } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } private boolean isReferenceExist(GraphVertex metadataVertex) { 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 eb2574405f..02b37b7d21 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 @@ -8,14 +8,14 @@ import org.openecomp.sdc.asdctool.impl.validator.tasks.artifacts.ServiceArtifact import org.openecomp.sdc.asdctool.impl.validator.tasks.artifacts.VfArtifactValidationTask; import org.openecomp.sdc.asdctool.impl.validator.tasks.moduleJson.ModuleJsonTask; import org.openecomp.sdc.asdctool.impl.validator.utils.ReportManager; -import org.openecomp.sdc.be.dao.DAOTitanStrategy; -import org.openecomp.sdc.be.dao.TitanClientStrategy; +import org.openecomp.sdc.be.dao.DAOJanusGraphStrategy; +import org.openecomp.sdc.be.dao.JanusGraphClientStrategy; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraClient; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.model.DerivedNodeTypeResolver; -import org.openecomp.sdc.be.model.jsontitan.operations.*; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.*; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -81,14 +81,15 @@ public class ValidationToolConfiguration { return new CassandraClient(); } - @Bean(name = "dao-titan-strategy") - public TitanClientStrategy daoStrategy() { - return new DAOTitanStrategy(); + @Bean(name = "dao-janusgraph-strategy") + public JanusGraphClientStrategy daoStrategy() { + return new DAOJanusGraphStrategy(); } - @Bean(name = "migration-titan-client", initMethod = "createGraph") - public TitanGraphClient titanMigrationClient(@Qualifier("dao-titan-strategy") TitanClientStrategy titanClientStrategy) { - return new TitanGraphClient(titanClientStrategy); + @Bean(name = "migration-janusgraph-client", initMethod = "createGraph") + public JanusGraphClient janusGraphMigrationClient(@Qualifier("dao-janusgraph-strategy") + JanusGraphClientStrategy janusGraphClientStrategy) { + return new JanusGraphClient(janusGraphClientStrategy); } @Bean(name = "tosca-operation-facade") @@ -116,9 +117,9 @@ public class ValidationToolConfiguration { return new ByToscaNameDerivedNodeTypeResolver(); } - @Bean(name = "titan-dao") - public TitanDao titanDao(@Qualifier("migration-titan-client") TitanGraphClient titanGraphClient) { - return new TitanDao(titanGraphClient); + @Bean(name = "janusgraph-dao") + public JanusGraphDao janusGraphDao(@Qualifier("migration-janusgraph-client") JanusGraphClient janusGraphClient) { + return new JanusGraphDao(janusGraphClient); } @Bean(name = "category-operation") diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/ArtifactValidatorExecuter.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/ArtifactValidatorExecuter.java index 34696b33eb..57053eb032 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/ArtifactValidatorExecuter.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/ArtifactValidatorExecuter.java @@ -2,15 +2,15 @@ package org.openecomp.sdc.asdctool.impl.validator.executers; import fj.data.Either; import org.openecomp.sdc.asdctool.impl.validator.config.ValidationConfigManager; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; @@ -22,7 +22,7 @@ import java.util.stream.Collectors; public class ArtifactValidatorExecuter{ @Autowired - protected TitanDao titanDao; + protected JanusGraphDao janusGraphDao; @Autowired private ToscaOperationFacade toscaOperationFacade; @@ -42,7 +42,8 @@ public class ArtifactValidatorExecuter{ public Map> getVerticesToValidate(VertexTypeEnum type, Map hasProps){ Map> result = new HashMap<>(); - Either, TitanOperationStatus> resultsEither = titanDao.getByCriteria(type, hasProps); + Either, JanusGraphOperationStatus> resultsEither = janusGraphDao + .getByCriteria(type, hasProps); if (resultsEither.isRight()) { log.error("getVerticesToValidate failed "+ resultsEither.right().value()); return result; @@ -101,7 +102,7 @@ public class ArtifactValidatorExecuter{ log.error("Failed to fetch vf resources ", e); return false; } finally { - titanDao.commit(); + janusGraphDao.commit(); } return result; } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/TopologyTemplateValidatorExecuter.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/TopologyTemplateValidatorExecuter.java index a10d3193b2..79bf510b55 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/TopologyTemplateValidatorExecuter.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/TopologyTemplateValidatorExecuter.java @@ -5,9 +5,9 @@ import org.openecomp.sdc.asdctool.impl.validator.tasks.TopologyTemplateValidatio import org.openecomp.sdc.asdctool.impl.validator.utils.ReportManager; import org.openecomp.sdc.asdctool.impl.validator.utils.VertexResult; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; @@ -24,7 +24,7 @@ public class TopologyTemplateValidatorExecuter { private static Logger log = Logger.getLogger(VfValidatorExecuter.class.getName()); @Autowired - protected TitanDao titanDao; + protected JanusGraphDao janusGraphDao; protected String name; @@ -43,7 +43,8 @@ public class TopologyTemplateValidatorExecuter { props.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF); } - Either, TitanOperationStatus> results = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props); + Either, JanusGraphOperationStatus> results = janusGraphDao + .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props); if (results.isRight()) { log.error("getVerticesToValidate failed "+ results.right().value()); return new ArrayList<>(); diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/ArtifactValidationUtils.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/ArtifactValidationUtils.java index faccd647c2..433ea9ef0a 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/ArtifactValidationUtils.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/ArtifactValidationUtils.java @@ -8,9 +8,9 @@ import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.springframework.beans.factory.annotation.Autowired; diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/moduleJson/ModuleJsonTask.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/moduleJson/ModuleJsonTask.java index 272b546a5d..dd1f54f337 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/moduleJson/ModuleJsonTask.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/moduleJson/ModuleJsonTask.java @@ -11,9 +11,9 @@ import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.springframework.beans.factory.annotation.Autowired; diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/DataSchemaMenu.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/DataSchemaMenu.java index fe117d1a1a..d2d5e77f2b 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/DataSchemaMenu.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/DataSchemaMenu.java @@ -22,7 +22,7 @@ package org.openecomp.sdc.asdctool.main; -import org.openecomp.sdc.asdctool.impl.TitanGraphInitializer; +import org.openecomp.sdc.asdctool.impl.JanusGraphInitializer; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaBuilder; import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils; @@ -62,14 +62,14 @@ public class DataSchemaMenu { System.exit(2); } break; - case "create-titan-structures": - log.debug("Start create titan keyspace"); - String titanCfg = 2 == args.length ? configurationManager.getConfiguration().getTitanCfgFile() : args[2]; - if (TitanGraphInitializer.createGraph(titanCfg)) { - log.debug("create titan keyspace successfull"); + case "create-janusgraph-structures": + log.debug("Start create janusgraph keyspace"); + String janusGraphCfg = 2 == args.length ? configurationManager.getConfiguration().getJanusGraphCfgFile() : args[2]; + if (JanusGraphInitializer.createGraph(janusGraphCfg)) { + log.debug("create janusgraph keyspace successfull"); System.exit(0); } else { - log.debug("create titan keyspace failed"); + log.debug("create janusgraph keyspace failed"); System.exit(2); } break; @@ -96,6 +96,6 @@ public class DataSchemaMenu { private static void DataSchemeUsage() { System.out.println("Usage: create-cassandra-structures "); - System.out.println("Usage: create-titan-structures "); + System.out.println("Usage: create-janusgraph-structures "); } } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ExportImportMenu.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ExportImportMenu.java index 36d2f66d58..844ae1ec6e 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ExportImportMenu.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ExportImportMenu.java @@ -36,7 +36,7 @@ public class ExportImportMenu { } private static void importUsage() { - System.out.println("Usage: import "); + System.out.println("Usage: import "); } private static void validateJsonUsage() { @@ -44,7 +44,7 @@ public class ExportImportMenu { } private static void exportUsage() { - System.out.println("Usage: export "); + System.out.println("Usage: export "); } private static void dataReportUsage() { @@ -52,7 +52,7 @@ public class ExportImportMenu { } private static void exportUsersUsage() { - System.out.println("Usage: exportusers "); + System.out.println("Usage: exportusers "); } public static void main(String[] args) throws Exception { @@ -116,7 +116,7 @@ public class ExportImportMenu { case "validate-json": String jsonFilePath = validateAndGetJsonFilePath(args); GraphJsonValidator graphJsonValidator = new GraphJsonValidator(); - if (graphJsonValidator.verifyTitanJson(jsonFilePath)) { + if (graphJsonValidator.verifyJanusGraphJson(jsonFilePath)) { System.exit(2); } break; diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/RemoveUtils.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/RemoveUtils.java index 4bc21b38ca..236f819063 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/RemoveUtils.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/RemoveUtils.java @@ -52,7 +52,7 @@ public class RemoveUtils { } private static void removeUsage() { - System.out.println("Usage: remove-products "); + System.out.println("Usage: remove-products "); } private static boolean verifyParamsLength(String[] args, int i) { diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/UpdateIsVnfMenu.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/UpdateIsVnfMenu.java index ff548ff71a..fc65a2d2d8 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/UpdateIsVnfMenu.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/UpdateIsVnfMenu.java @@ -41,7 +41,7 @@ public class UpdateIsVnfMenu { private static void updateIsVnfTrueUsage() { System.out.println( - "Usage: updateIsVnfTrue "); + "Usage: updateIsVnfTrue "); } public static void main(String[] args) { diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710.java index bff30683ca..c4be03d899 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710.java @@ -21,17 +21,17 @@ import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLog import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.*; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; 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.CsarOperation; @@ -74,7 +74,7 @@ public class UpgradeMigration1710 implements PostMigration { private boolean isNodeTypesSupportOnly = true; @Autowired - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Autowired private ToscaOperationFacade toscaOperationFacade; @@ -263,10 +263,10 @@ public class UpgradeMigration1710 implements PostMigration { private void cleanup(MigrationResult.MigrationStatus status) { if (status == MigrationResult.MigrationStatus.COMPLETED ) { log.info("Upgrade migration 1710 has been successfully finished. "); - titanDao.commit(); + janusGraphDao.commit(); } else { log.info("Upgrade migration 1710 was failed. "); - titanDao.rollback(); + janusGraphDao.rollback(); } outputHandler.writeOutputAndCloseFile(); if (!isNodeTypesSupportOnly && isLockSucceeded) { @@ -299,11 +299,11 @@ public class UpgradeMigration1710 implements PostMigration { finally { if (result) { log.info("Service upgrade finished successfully: uniqueId {} ", currUid); - titanDao.commit(); + janusGraphDao.commit(); } else { log.error("Failed to upgrade service with uniqueId {} ", currUid); - titanDao.rollback(); + janusGraphDao.rollback(); } markCheckedOutServiceAsDeletedIfUpgradeFailed(currUid, result); } @@ -314,7 +314,7 @@ public class UpgradeMigration1710 implements PostMigration { } private void upgradeServices() { - Either, TitanOperationStatus> getServicesRes = getAllLatestCertifiedComponentUids(VertexTypeEnum.TOPOLOGY_TEMPLATE, ComponentTypeEnum.SERVICE); + Either, JanusGraphOperationStatus> getServicesRes = getAllLatestCertifiedComponentUids(VertexTypeEnum.TOPOLOGY_TEMPLATE, ComponentTypeEnum.SERVICE); if (getServicesRes.isRight()) { log.error("Failed to retrieve the latest certified service versions"); return; @@ -341,7 +341,7 @@ public class UpgradeMigration1710 implements PostMigration { return upgradeService(getServiceRes.left().value()); } if(!latestGenericTypes.containsKey(derivedFromGenericType)){ - Either, TitanOperationStatus> getDerivedRes = findDerivedResources(derivedFromGenericType); + Either, JanusGraphOperationStatus> getDerivedRes = findDerivedResources(derivedFromGenericType); if(getDerivedRes.isRight()){ log.error(FAILED_TO_UPGRADE_COMPONENT, getServiceRes.left().value().getComponentType().getValue(), getServiceRes.left().value().getName(), getServiceRes.left().value().getInvariantUUID(), getServiceRes.left().value().getVersion(), "findDerivedResources", getDerivedRes.right().value()); outputHandler.addRecord( getServiceRes.left().value().getComponentType().name(),getServiceRes.left().value().getName(), getServiceRes.left().value().getInvariantUUID(), getServiceRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), getDerivedRes.right().value()); @@ -531,7 +531,7 @@ public class UpgradeMigration1710 implements PostMigration { Optional propertyInvariantUuid = instanceProperties.stream().filter(p->p.getName().equals(SERVICE_INVARIANT_UUID_RPOPERTY)).findFirst(); if(propertyUuid.isPresent() && propertyInvariantUuid.isPresent()){ String serviceInvariantUUID = propertyInvariantUuid.get().getValue(); - Either, TitanOperationStatus> getLatestOriginServiceRes = getLatestCertifiedService(serviceInvariantUUID); + Either, JanusGraphOperationStatus> getLatestOriginServiceRes = getLatestCertifiedService(serviceInvariantUUID); if (getLatestOriginServiceRes.isRight()) { return instance; } @@ -565,9 +565,9 @@ public class UpgradeMigration1710 implements PostMigration { } private Either upgradeServiceProxyInstance(org.openecomp.sdc.be.model.Component component, ComponentInstance instance, ComponentInstance newComponentInstance) { - Either, TitanOperationStatus> getLatestOriginServiceRes = getLatestCertifiedService(instance.getSourceModelInvariant()); + Either, JanusGraphOperationStatus> getLatestOriginServiceRes = getLatestCertifiedService(instance.getSourceModelInvariant()); if (getLatestOriginServiceRes.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(getLatestOriginServiceRes.right().value()), instance.getOriginType().getComponentType()))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getLatestOriginServiceRes.right().value()), instance.getOriginType().getComponentType()))); } ModelConverter.getVertexType(instance.getOriginType().name()); Either getOriginRes = toscaOperationFacade.getLatestByName(instance.getComponentName()); @@ -580,7 +580,7 @@ public class UpgradeMigration1710 implements PostMigration { return changeAssetVersion(component, instance, newComponentInstance); } - private Either, TitanOperationStatus> getLatestCertifiedService(String invariantUUID) { + private Either, JanusGraphOperationStatus> getLatestCertifiedService(String invariantUUID) { Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); @@ -589,7 +589,8 @@ public class UpgradeMigration1710 implements PostMigration { propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, invariantUUID); Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - return titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata); + return janusGraphDao + .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata); } private Either changeAssetVersion(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance instance, ComponentInstance newComponentInstance) { @@ -599,7 +600,7 @@ public class UpgradeMigration1710 implements PostMigration { private boolean upgradeNodeTypes() { log.info("Starting upgrade node types upon upgrade migration 1710 process. "); if (nodeTypes != null && !nodeTypes.isEmpty()) { - Either, TitanOperationStatus> getRes = getAllLatestCertifiedComponentUids(VertexTypeEnum.NODE_TYPE, ComponentTypeEnum.RESOURCE); + Either, JanusGraphOperationStatus> getRes = getAllLatestCertifiedComponentUids(VertexTypeEnum.NODE_TYPE, ComponentTypeEnum.RESOURCE); if (getRes.isRight()) { return false; } @@ -633,7 +634,7 @@ public class UpgradeMigration1710 implements PostMigration { private boolean upgradeVFs() { log.info("Starting upgrade VFs upon upgrade migration 1710 process. "); - Either, TitanOperationStatus> getVfsRes = getAllLatestCertifiedComponentUids(VertexTypeEnum.TOPOLOGY_TEMPLATE, ComponentTypeEnum.RESOURCE); + Either, JanusGraphOperationStatus> getVfsRes = getAllLatestCertifiedComponentUids(VertexTypeEnum.TOPOLOGY_TEMPLATE, ComponentTypeEnum.RESOURCE); if (getVfsRes.isRight()) { log.info(UPGRADE_VFS_FAILED); return false; @@ -665,11 +666,11 @@ public class UpgradeMigration1710 implements PostMigration { finally { if (result) { log.info("Resource upgrade finished successfully: uniqueId {} ", currUid); - titanDao.commit(); + janusGraphDao.commit(); } else { log.error("Failed to upgrade resource with uniqueId {} ", currUid); - titanDao.rollback(); + janusGraphDao.rollback(); } markCheckedOutResourceAsDeletedIfUpgradeFailed(currUid, result); } @@ -804,7 +805,7 @@ public class UpgradeMigration1710 implements PostMigration { if (StringUtils.isNotEmpty(derivedFromGenericType) && !latestGenericTypes.containsKey(derivedFromGenericType)) { log.info("Starting upgrade vf with name {}, invariantUUID {}, version {}, latest derived from generic type {}, latest derived from generic version {}. ", component.getName(), component.getInvariantUUID(), component.getVersion(), derivedFromGenericType, derivedFromGenericVersion); log.info("Starting to fetch latest generic node type {}. ", derivedFromGenericType); - Either, TitanOperationStatus> getDerivedRes = findDerivedResources(derivedFromGenericType); + Either, JanusGraphOperationStatus> getDerivedRes = findDerivedResources(derivedFromGenericType); if (getDerivedRes.isRight()) { outputHandler.addRecord(component.getComponentType().name(), component.getName(), component.getInvariantUUID(), component.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), getDerivedRes.right().value()); log.info("Failed to upgrade component with name {}, invariantUUID {}, version {} and latest generic. Status is {}. ", component.getName(), component.getInvariantUUID(), component.getVersion(), derivedFromGenericType); @@ -835,9 +836,10 @@ public class UpgradeMigration1710 implements PostMigration { StorageOperationStatus result = StorageOperationStatus.OK; log.info("Starting upgrade node type with name {}, invariantUUID {}, version{}. ", nodeTypeV.getMetadataProperty(GraphPropertyEnum.NAME), nodeTypeV.getMetadataProperty(GraphPropertyEnum.INVARIANT_UUID), nodeTypeV.getMetadataProperty(GraphPropertyEnum.VERSION)); log.info("Starting to find derived to for node type with name {}, invariantUUID {}, version{}. ", nodeTypeV.getMetadataProperty(GraphPropertyEnum.NAME), nodeTypeV.getMetadataProperty(GraphPropertyEnum.INVARIANT_UUID), nodeTypeV.getMetadataProperty(GraphPropertyEnum.VERSION)); - Either, TitanOperationStatus> parentResourceRes = titanDao.getParentVertecies(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.ParseMetadata); - if (parentResourceRes.isRight() && parentResourceRes.right().value() != TitanOperationStatus.NOT_FOUND) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(parentResourceRes.right().value()); + Either, JanusGraphOperationStatus> parentResourceRes = janusGraphDao + .getParentVertecies(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.ParseMetadata); + if (parentResourceRes.isRight() && parentResourceRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentResourceRes.right().value()); } List derivedResourcesUid = getAllDerivedGraphVertices(allCertifiedUids, parentResourceRes); @@ -871,13 +873,13 @@ public class UpgradeMigration1710 implements PostMigration { } if (performFullCertification(checkouRes.left().value()).isLeft()) { upgradedNodeTypesMap.put(nodeType.getToscaResourceName(), checkouRes.left().value()); - titanDao.commit(); + janusGraphDao.commit(); return true; } return false; } - private List getAllDerivedGraphVertices(List allCertifiedUids, Either, TitanOperationStatus> parentResources) { + private List getAllDerivedGraphVertices(List allCertifiedUids, Either, JanusGraphOperationStatus> parentResources) { List derivedResourcesUid = new ArrayList<>(); if (parentResources.isLeft()) { @@ -916,14 +918,15 @@ public class UpgradeMigration1710 implements PostMigration { return changeStateEither; } - private Either, TitanOperationStatus> findDerivedResources(String parentResource) { + private Either, JanusGraphOperationStatus> findDerivedResources(String parentResource) { Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, parentResource); propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - return titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, JsonParseFlagEnum.ParseMetadata); + return janusGraphDao + .getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, JsonParseFlagEnum.ParseMetadata); } private boolean latestVersionExists(GraphVertex latestDerivedFrom, String currentVersion) { @@ -940,14 +943,14 @@ public class UpgradeMigration1710 implements PostMigration { return Double.parseDouble(latestVersion) > Double.parseDouble(currentVersion); } - private Either, TitanOperationStatus> getAllLatestCertifiedComponentUids(VertexTypeEnum vertexType, ComponentTypeEnum componentType) { + private Either, JanusGraphOperationStatus> getAllLatestCertifiedComponentUids(VertexTypeEnum vertexType, ComponentTypeEnum componentType) { log.info("Starting to fetch all latest certified not checked out components with type {} upon upgrade migration 1710 process", componentType); - Either, TitanOperationStatus> result = null; + Either, JanusGraphOperationStatus> result = null; Map latestCertifiedMap = new HashMap<>(); Map latestNotCertifiedMap = new HashMap<>(); - Either, TitanOperationStatus> getComponentsRes = getAllLatestComponents(vertexType, componentType); - if (getComponentsRes.isRight() && getComponentsRes.right().value() != TitanOperationStatus.NOT_FOUND) { + Either, JanusGraphOperationStatus> getComponentsRes = getAllLatestComponents(vertexType, componentType); + if (getComponentsRes.isRight() && getComponentsRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) { log.error("Failed to fetch all latest certified not checked out components with type {}. Status is {}. ", componentType, getComponentsRes.right().value()); result = Either.right(getComponentsRes.right().value()); } @@ -968,7 +971,7 @@ public class UpgradeMigration1710 implements PostMigration { return result; } - private Either, TitanOperationStatus> getAllLatestComponents(VertexTypeEnum vertexType, ComponentTypeEnum componentType) { + private Either, JanusGraphOperationStatus> getAllLatestComponents(VertexTypeEnum vertexType, ComponentTypeEnum componentType) { Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); @@ -979,7 +982,8 @@ public class UpgradeMigration1710 implements PostMigration { if (vertexType == VertexTypeEnum.TOPOLOGY_TEMPLATE && componentType == ComponentTypeEnum.RESOURCE) { propertiesNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name()); } - return titanDao.getByCriteria(vertexType, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata); + return janusGraphDao + .getByCriteria(vertexType, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata); } private Either, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) { @@ -990,11 +994,12 @@ public class UpgradeMigration1710 implements PostMigration { propertiesToMatch.put(property, nodeName); propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - Either, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata); + Either, JanusGraphOperationStatus> highestResources = janusGraphDao + .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata); if (highestResources.isRight()) { - TitanOperationStatus status = highestResources.right().value(); + JanusGraphOperationStatus status = highestResources.right().value(); log.debug("Failed to fetch resource with name {}. Status is {} ", nodeName, status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } List resources = highestResources.left().value(); List result = new ArrayList<>(); diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1802/SdcCatalogMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1802/SdcCatalogMigration.java index d520eee1b8..a47c63d451 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1802/SdcCatalogMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1802/SdcCatalogMigration.java @@ -6,17 +6,17 @@ import org.apache.tinkerpop.gremlin.structure.Direction; import org.openecomp.sdc.asdctool.migration.core.DBVersion; import org.openecomp.sdc.asdctool.migration.core.task.Migration; import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementOperation; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; @@ -32,11 +32,11 @@ public class SdcCatalogMigration implements Migration { private static final List EXCLUDE_TYPES = Arrays.asList(ResourceTypeEnum.VFCMT, ResourceTypeEnum.Configuration); private ToscaElementOperation toscaElementOperation; - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; - public SdcCatalogMigration(TopologyTemplateOperation toscaElementOperation, TitanDao titanDao) { + public SdcCatalogMigration(TopologyTemplateOperation toscaElementOperation, JanusGraphDao janusGraphDao) { this.toscaElementOperation = toscaElementOperation; - this.titanDao = titanDao; + this.janusGraphDao = janusGraphDao; } @Override @@ -51,45 +51,46 @@ public class SdcCatalogMigration implements Migration { @Override public MigrationResult migrate() { - TitanOperationStatus status = null; + JanusGraphOperationStatus status = null; try { status = getOrCreateCatalogRoot() .either(this::associateCatalogRootToCatalogElements, err -> {LOGGER.error("failed to create catalog root. err: {}", err); return err;}); - return status == TitanOperationStatus.OK ? MigrationResult.success() : MigrationResult.error("failed to create and associate catalog root. error: " + status); + return status == JanusGraphOperationStatus.OK ? MigrationResult.success() : MigrationResult.error("failed to create and associate catalog root. error: " + status); } finally { commitOrRollBack(status); } } - private void commitOrRollBack(TitanOperationStatus status) { - if (status == TitanOperationStatus.OK) { - titanDao.commit(); + private void commitOrRollBack(JanusGraphOperationStatus status) { + if (status == JanusGraphOperationStatus.OK) { + janusGraphDao.commit(); } else { - titanDao.rollback(); + janusGraphDao.rollback(); } } - private Either getOrCreateCatalogRoot() { + private Either getOrCreateCatalogRoot() { LOGGER.info("creating or getting catalog root vertex"); - return titanDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT) + return janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT) .right() .bind(this::createRootCatalogVertexOrError); } - private Either createRootCatalogVertexOrError(TitanOperationStatus titanOperationStatus) { - return titanOperationStatus == TitanOperationStatus.NOT_FOUND ? createRootCatalogVertex() : Either.right(titanOperationStatus); + private Either createRootCatalogVertexOrError(JanusGraphOperationStatus janusGraphOperationStatus) { + return janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND ? createRootCatalogVertex() : Either.right( + janusGraphOperationStatus); } - private Either createRootCatalogVertex() { + private Either createRootCatalogVertex() { LOGGER.info("Creating root catalog vertex"); GraphVertex catalogRootVertex = new GraphVertex(VertexTypeEnum.CATALOG_ROOT); catalogRootVertex.setUniqueId(IdBuilderUtils.generateUniqueId()); - return titanDao.createVertex(catalogRootVertex); + return janusGraphDao.createVertex(catalogRootVertex); } - private Either, TitanOperationStatus> getAllCatalogVertices() { + private Either, JanusGraphOperationStatus> getAllCatalogVertices() { LOGGER.info("fetching all catalog resources"); return toscaElementOperation.getListOfHighestComponents(ComponentTypeEnum.RESOURCE, EXCLUDE_TYPES, JsonParseFlagEnum.ParseMetadata) .right() @@ -98,12 +99,12 @@ public class SdcCatalogMigration implements Migration { .bind(this::getAllCatalogVertices); } - private Either, TitanOperationStatus> errOrEmptyListIfNotFound(TitanOperationStatus err) { - return TitanOperationStatus.NOT_FOUND.equals(err) ? Either.left(new ArrayList<>()) : Either.right(err); + private Either, JanusGraphOperationStatus> errOrEmptyListIfNotFound(JanusGraphOperationStatus err) { + return JanusGraphOperationStatus.NOT_FOUND.equals(err) ? Either.left(new ArrayList<>()) : Either.right(err); } @SuppressWarnings("unchecked") - private Either, TitanOperationStatus> getAllCatalogVertices(List allResourceCatalogVertices) { + private Either, JanusGraphOperationStatus> getAllCatalogVertices(List allResourceCatalogVertices) { LOGGER.info("number of resources: {}", allResourceCatalogVertices.size()); LOGGER.info("fetching all catalog services"); return toscaElementOperation.getListOfHighestComponents(ComponentTypeEnum.SERVICE, EXCLUDE_TYPES, JsonParseFlagEnum.ParseMetadata) @@ -113,20 +114,22 @@ public class SdcCatalogMigration implements Migration { .map(allServiceVertices -> ListUtils.union(allServiceVertices, allResourceCatalogVertices)); } - private TitanOperationStatus associateCatalogRootToCatalogElements(GraphVertex root) { + private JanusGraphOperationStatus associateCatalogRootToCatalogElements(GraphVertex root) { return getAllCatalogVertices() .either(catalogVertices -> associateCatalogRootToCatalogElements(root, catalogVertices), err -> err); } - private TitanOperationStatus associateCatalogRootToCatalogElements(GraphVertex root, List catalogElements) { + private JanusGraphOperationStatus associateCatalogRootToCatalogElements(GraphVertex root, List catalogElements) { LOGGER.info("number of catalog elements: {}", catalogElements.size()); LOGGER.info("connect all catalog elements to root edge"); List nonConnectedElements = catalogElements.stream().filter(this::edgeNotAlreadyExists).collect(Collectors.toList()); int numOfCreatedEdges = 0; for (GraphVertex catalogElement : nonConnectedElements) { - TitanOperationStatus edgeCreationStatus = titanDao.createEdge(root, catalogElement, EdgeLabelEnum.CATALOG_ELEMENT, null); - if (edgeCreationStatus != TitanOperationStatus.OK) { + JanusGraphOperationStatus + edgeCreationStatus = janusGraphDao + .createEdge(root, catalogElement, EdgeLabelEnum.CATALOG_ELEMENT, null); + if (edgeCreationStatus != JanusGraphOperationStatus.OK) { LOGGER.error("failed to create edge from catalog element to vertex {}", catalogElement.getUniqueId()); return edgeCreationStatus; } @@ -134,7 +137,7 @@ public class SdcCatalogMigration implements Migration { numOfCreatedEdges++; } LOGGER.info("number edges created: {}", numOfCreatedEdges); - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } private boolean edgeNotAlreadyExists(GraphVertex catalogElement) { diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ForwardPathMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ForwardPathMigration.java index 9634025867..812c07e6b0 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ForwardPathMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ForwardPathMigration.java @@ -17,7 +17,7 @@ package org.openecomp.sdc.asdctool.migration.tasks.mig1806; import com.google.common.collect.ImmutableSet; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import java.math.BigInteger; import java.util.ArrayList; @@ -38,22 +38,20 @@ import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.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.UserAdminOperation; @@ -61,14 +59,14 @@ import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation; @org.springframework.stereotype.Component public class ForwardPathMigration implements Migration { - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; private UserAdminOperation userAdminOperation; private ToscaOperationFacade toscaOperationFacade; private User user = null; - public ForwardPathMigration(TitanDao titanDao, + public ForwardPathMigration(JanusGraphDao janusGraphDao, UserAdminOperation userAdminOperation, ToscaOperationFacade toscaOperationFacade) { - this.titanDao = titanDao; + this.janusGraphDao = janusGraphDao; this.userAdminOperation = userAdminOperation; this.toscaOperationFacade = toscaOperationFacade; } @@ -110,7 +108,7 @@ public class ForwardPathMigration implements Migration { hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); Map hasNotProps = new HashMap<>(); hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); - status = titanDao + status = janusGraphDao .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, hasNotProps, JsonParseFlagEnum.ParseAll) .either(this::cleanServices, this::handleError); return status; @@ -138,10 +136,11 @@ public class ForwardPathMigration implements Migration { } - private StorageOperationStatus handleError(TitanOperationStatus err) { - titanDao.rollback(); + private StorageOperationStatus handleError(JanusGraphOperationStatus err) { + janusGraphDao.rollback(); return DaoStatusConverter - .convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND == err ? TitanOperationStatus.OK : err); + .convertJanusGraphStatusToStorageStatus( + JanusGraphOperationStatus.NOT_FOUND == err ? JanusGraphOperationStatus.OK : err); } private StorageOperationStatus fixDataOnGraph(Component component) { @@ -149,10 +148,10 @@ public class ForwardPathMigration implements Migration { return StorageOperationStatus.OK; } Service service = (Service) component; - Either getResponse = titanDao.getVertexById(service.getUniqueId(), + Either getResponse = janusGraphDao.getVertexById(service.getUniqueId(), JsonParseFlagEnum.NoParse); if (getResponse.isRight()) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResponse.right().value()); } Set ciNames = new HashSet<>(); @@ -163,13 +162,13 @@ public class ForwardPathMigration implements Migration { GraphVertex componentVertex = getResponse.left().value(); GraphVertex toscaDataVertex; - Either groupVertexEither = titanDao.getChildVertex(componentVertex, + Either groupVertexEither = janusGraphDao.getChildVertex(componentVertex, EdgeLabelEnum.FORWARDING_PATH, JsonParseFlagEnum.ParseJson); - if (groupVertexEither.isRight() && groupVertexEither.right().value() == TitanOperationStatus.NOT_FOUND) { + if (groupVertexEither.isRight() && groupVertexEither.right().value() == JanusGraphOperationStatus.NOT_FOUND) { return StorageOperationStatus.OK; } if (groupVertexEither.isRight()) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(groupVertexEither.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(groupVertexEither.right().value()); } toscaDataVertex = groupVertexEither.left().value(); Map forwardingPaths = new HashMap<>( @@ -186,42 +185,44 @@ public class ForwardPathMigration implements Migration { } } if (toBeDeletedFP.isEmpty()) { - titanDao.rollback(); + janusGraphDao.rollback(); return StorageOperationStatus.OK; } toBeDeletedFP.stream().forEach(fpKey -> forwardingPaths.remove(fpKey)); toscaDataVertex.setJson(forwardingPaths); - Either updatevertexEither = updateOrCopyOnUpdate( + Either updatevertexEither = updateOrCopyOnUpdate( toscaDataVertex, componentVertex); if (updatevertexEither.isRight()) { - titanDao.rollback(); - return DaoStatusConverter.convertTitanStatusToStorageStatus(updatevertexEither.right().value()); + janusGraphDao.rollback(); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updatevertexEither.right().value()); } - titanDao.commit(); + janusGraphDao.commit(); return StorageOperationStatus.OK; } - private Either cloneDataVertex(GraphVertex dataVertex, GraphVertex toscaElementVertex, Edge edgeToRemove) { + private Either cloneDataVertex(GraphVertex dataVertex, GraphVertex toscaElementVertex, Edge edgeToRemove) { EdgeLabelEnum label = EdgeLabelEnum.FORWARDING_PATH; GraphVertex newDataVertex = new GraphVertex(dataVertex.getLabel()); String id = IdBuilderUtils.generateChildId(toscaElementVertex.getUniqueId(), dataVertex.getLabel()); newDataVertex.cloneData(dataVertex); newDataVertex.setUniqueId(id); - Either createVertex = titanDao.createVertex(newDataVertex); + Either createVertex = janusGraphDao.createVertex(newDataVertex); if (createVertex.isRight()) { return createVertex; } newDataVertex = createVertex.left().value(); - TitanOperationStatus createEdge = titanDao.createEdge(toscaElementVertex, newDataVertex, label, titanDao.getEdgeProperties(edgeToRemove)); - if (createEdge != TitanOperationStatus.OK) { + JanusGraphOperationStatus + createEdge = janusGraphDao + .createEdge(toscaElementVertex, newDataVertex, label, janusGraphDao.getEdgeProperties(edgeToRemove)); + if (createEdge != JanusGraphOperationStatus.OK) { return Either.right(createEdge); } edgeToRemove.remove(); return Either.left(newDataVertex); } - private Either updateOrCopyOnUpdate(GraphVertex dataVertex, GraphVertex toscaElementVertex ) { + private Either updateOrCopyOnUpdate(GraphVertex dataVertex, GraphVertex toscaElementVertex ) { EdgeLabelEnum label = EdgeLabelEnum.FORWARDING_PATH; Iterator edges = dataVertex.getVertex().edges(Direction.IN, label.name()); int edgeCount = 0; @@ -230,21 +231,22 @@ public class ForwardPathMigration implements Migration { Edge edge = edges.next(); ++edgeCount; Vertex outVertex = edge.outVertex(); - String outId = (String) titanDao.getProperty((TitanVertex) outVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()); + String outId = (String) janusGraphDao + .getProperty((JanusGraphVertex) outVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()); if (toscaElementVertex.getUniqueId().equals(outId)) { edgeToRemove = edge; } } if (edgeToRemove == null) { - return Either.right(TitanOperationStatus.GENERAL_ERROR); + return Either.right(JanusGraphOperationStatus.GENERAL_ERROR); } switch (edgeCount) { case 0: // error - return Either.right(TitanOperationStatus.GENERAL_ERROR); + return Either.right(JanusGraphOperationStatus.GENERAL_ERROR); case 1: // update - return titanDao.updateVertex(dataVertex); + return janusGraphDao.updateVertex(dataVertex); default: // copy on update return cloneDataVertex(dataVertex, toscaElementVertex, edgeToRemove); diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ResourceLifecycleMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ResourceLifecycleMigration.java index 7d741624c2..02b45dc332 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ResourceLifecycleMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ResourceLifecycleMigration.java @@ -8,11 +8,11 @@ import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; @@ -33,7 +33,7 @@ import java.util.Map; @Component public class ResourceLifecycleMigration implements Migration { - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; private LifecycleBusinessLogic lifecycleBusinessLogic; private UserAdminOperation userAdminOperation; @@ -41,8 +41,8 @@ public class ResourceLifecycleMigration implements Migration { private static final Logger log = Logger.getLogger(ResourceLifecycleMigration.class); - public ResourceLifecycleMigration(TitanDao titanDao, LifecycleBusinessLogic lifecycleBusinessLogic, UserAdminOperation userAdminOperation) { - this.titanDao = titanDao; + public ResourceLifecycleMigration(JanusGraphDao janusGraphDao, LifecycleBusinessLogic lifecycleBusinessLogic, UserAdminOperation userAdminOperation) { + this.janusGraphDao = janusGraphDao; this.lifecycleBusinessLogic = lifecycleBusinessLogic; this.userAdminOperation = userAdminOperation; } @@ -82,7 +82,7 @@ public class ResourceLifecycleMigration implements Migration { if (StorageOperationStatus.OK == status) { status = findResourcesAndChangeStatus(VertexTypeEnum.TOPOLOGY_TEMPLATE); } - titanDao.commit(); + janusGraphDao.commit(); return status; } @@ -97,12 +97,12 @@ public class ResourceLifecycleMigration implements Migration { hasNot.put(GraphPropertyEnum.IS_DELETED, true); log.info("findResourcesAndChangeStatus for type {} and state {}", type ,LifecycleStateEnum.READY_FOR_CERTIFICATION); - status = titanDao.getByCriteria(type, props, hasNot, JsonParseFlagEnum.ParseAll).either(this::changeState, this::handleError); + status = janusGraphDao.getByCriteria(type, props, hasNot, JsonParseFlagEnum.ParseAll).either(this::changeState, this::handleError); log.info("status {} for type {} and state {}", status, type ,LifecycleStateEnum.READY_FOR_CERTIFICATION); log.info("findResourcesAndChangeStatus for type {} and state {}", type ,LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); - status = titanDao.getByCriteria(type, props, hasNot, JsonParseFlagEnum.ParseAll).either(this::changeState, this::handleError); + status = janusGraphDao.getByCriteria(type, props, hasNot, JsonParseFlagEnum.ParseAll).either(this::changeState, this::handleError); log.info("status {} for type {} and state {}", status, type ,LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); @@ -130,9 +130,10 @@ public class ResourceLifecycleMigration implements Migration { return changeComponentState.isLeft() ? StorageOperationStatus.OK : StorageOperationStatus.GENERAL_ERROR; } - private StorageOperationStatus handleError(TitanOperationStatus err) { - log.debug("receive titan error {}", err); - return DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND == err ? TitanOperationStatus.OK : err); + private StorageOperationStatus handleError(JanusGraphOperationStatus err) { + log.debug("receive janusgraph error {}", err); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + JanusGraphOperationStatus.NOT_FOUND == err ? JanusGraphOperationStatus.OK : err); } } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SDCInstancesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SDCInstancesMigration.java index 4786839250..f85b6ade88 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SDCInstancesMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SDCInstancesMigration.java @@ -4,12 +4,12 @@ import fj.data.Either; import org.openecomp.sdc.asdctool.migration.core.DBVersion; import org.openecomp.sdc.asdctool.migration.core.task.Migration; import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; @@ -17,8 +17,8 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.common.log.wrappers.Logger; @@ -31,7 +31,7 @@ import java.util.Map.Entry; @Component public class SDCInstancesMigration implements Migration { - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; private NodeTemplateOperation nodeTemplateOperation; private static final Logger log = Logger.getLogger(SDCInstancesMigration.class); @@ -41,8 +41,8 @@ public class SDCInstancesMigration implements Migration { private static final List UUID_PROPS_NAMES = Arrays.asList("providing_service_uuid", "providing_service_uuid"); - public SDCInstancesMigration(TitanDao titanDao, NodeTemplateOperation nodeTemplateOperation) { - this.titanDao = titanDao; + public SDCInstancesMigration(JanusGraphDao janusGraphDao, NodeTemplateOperation nodeTemplateOperation) { + this.janusGraphDao = janusGraphDao; this.nodeTemplateOperation = nodeTemplateOperation; } @@ -69,13 +69,15 @@ public class SDCInstancesMigration implements Migration { hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC); - status = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, null, hasNotProps, JsonParseFlagEnum.ParseAll) + status = janusGraphDao + .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, null, hasNotProps, JsonParseFlagEnum.ParseAll) .either(this::connectAll, this::handleError); return status; } - private StorageOperationStatus handleError(TitanOperationStatus err) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND == err ? TitanOperationStatus.OK : err); + private StorageOperationStatus handleError(JanusGraphOperationStatus err) { + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + JanusGraphOperationStatus.NOT_FOUND == err ? JanusGraphOperationStatus.OK : err); } private StorageOperationStatus connectAll(List containersV) { @@ -96,7 +98,8 @@ public class SDCInstancesMigration implements Migration { ComponentTypeEnum componentType = containerV.getType(); Map instanceProperties = null; if (componentType == ComponentTypeEnum.RESOURCE) { - Either subcategoryV = titanDao.getChildVertex(containerV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); + Either subcategoryV = janusGraphDao + .getChildVertex(containerV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); if (subcategoryV.isRight()) { log.debug("Failed to fetch category vertex for resource {} error {} ", containerV.getUniqueId(), subcategoryV.right().value()); return StorageOperationStatus.GENERAL_ERROR; @@ -122,9 +125,9 @@ public class SDCInstancesMigration implements Migration { } finally { if (status == StorageOperationStatus.OK) { - titanDao.commit(); + janusGraphDao.commit(); } else { - titanDao.rollback(); + janusGraphDao.rollback(); } } } @@ -133,10 +136,11 @@ public class SDCInstancesMigration implements Migration { private Either, StorageOperationStatus> getInstProperties(GraphVertex containerV) { Map instanceProperties; - Either instProps = titanDao.getChildVertex(containerV, EdgeLabelEnum.INST_PROPERTIES, JsonParseFlagEnum.ParseAll); + Either instProps = janusGraphDao + .getChildVertex(containerV, EdgeLabelEnum.INST_PROPERTIES, JsonParseFlagEnum.ParseAll); if (instProps.isRight()) { - if (instProps.right().value() == TitanOperationStatus.NOT_FOUND) { + if (instProps.right().value() == JanusGraphOperationStatus.NOT_FOUND) { instanceProperties = new HashMap<>(); } else { log.debug("Failed to fetch instance properties vertex for resource {} error {} ", containerV.getUniqueId(), instProps.right().value()); diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SdcArchiveMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SdcArchiveMigration.java index bdab2cee2b..e8977227df 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SdcArchiveMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SdcArchiveMigration.java @@ -4,11 +4,11 @@ import fj.data.Either; import org.openecomp.sdc.asdctool.migration.core.DBVersion; import org.openecomp.sdc.asdctool.migration.core.task.Migration; import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; @@ -19,10 +19,10 @@ import java.math.BigInteger; public class SdcArchiveMigration implements Migration { private static final Logger logger = Logger.getLogger(SdcArchiveMigration.class); - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; - public SdcArchiveMigration(TitanDao titanDao) { - this.titanDao = titanDao; + public SdcArchiveMigration(JanusGraphDao janusGraphDao) { + this.janusGraphDao = janusGraphDao; } @Override @@ -37,30 +37,30 @@ public class SdcArchiveMigration implements Migration { @Override public MigrationResult migrate() { - TitanOperationStatus status = null; + JanusGraphOperationStatus status = null; try { status = getOrCreateArchiveRoot(); - return status == TitanOperationStatus.OK ? MigrationResult.success() : MigrationResult.error("failed to create archive root node. error: " + status); + return status == JanusGraphOperationStatus.OK ? MigrationResult.success() : MigrationResult.error("failed to create archive root node. error: " + status); } finally { commitOrRollBack(status); } } - private void commitOrRollBack(TitanOperationStatus status) { - if (status == TitanOperationStatus.OK) { - titanDao.commit(); + private void commitOrRollBack(JanusGraphOperationStatus status) { + if (status == JanusGraphOperationStatus.OK) { + janusGraphDao.commit(); } else { - titanDao.rollback(); + janusGraphDao.rollback(); } } - private TitanOperationStatus getOrCreateArchiveRoot() { + private JanusGraphOperationStatus getOrCreateArchiveRoot() { logger.info("creating or getting catalog archive vertex"); - return titanDao.getVertexByLabel(VertexTypeEnum.ARCHIVE_ROOT) - .either(v -> TitanOperationStatus.OK, s -> this.createRootArchiveVertex()); + return janusGraphDao.getVertexByLabel(VertexTypeEnum.ARCHIVE_ROOT) + .either(v -> JanusGraphOperationStatus.OK, s -> this.createRootArchiveVertex()); } - private TitanOperationStatus createRootArchiveVertex() { + private JanusGraphOperationStatus createRootArchiveVertex() { GraphVertex archiveRootVertex = new GraphVertex(VertexTypeEnum.ARCHIVE_ROOT); archiveRootVertex.setUniqueId(IdBuilderUtils.generateUniqueId()); archiveRootVertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.ARCHIVE_ROOT); @@ -68,9 +68,9 @@ public class SdcArchiveMigration implements Migration { logger.info("Creating root archive vertex {}", archiveRootVertex.getUniqueId()); - final Either vertexE = titanDao.createVertex(archiveRootVertex); + final Either vertexE = janusGraphDao.createVertex(archiveRootVertex); - return vertexE.isLeft() ? TitanOperationStatus.OK : vertexE.right().value(); + return vertexE.isLeft() ? JanusGraphOperationStatus.OK : vertexE.right().value(); } } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1902/InterfaceOperationMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1902/InterfaceOperationMigration.java index afbd3b411a..35e795095e 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1902/InterfaceOperationMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1902/InterfaceOperationMigration.java @@ -28,17 +28,17 @@ import org.openecomp.sdc.asdctool.migration.core.task.Migration; import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; 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.UserAdminOperation; @@ -51,7 +51,7 @@ public class InterfaceOperationMigration implements Migration { private static final Logger LOGGER = Logger.getLogger(InterfaceOperationMigration.class); @Autowired - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Autowired private UserAdminOperation userAdminOperation; @Autowired @@ -86,7 +86,8 @@ public class InterfaceOperationMigration implements Migration { private StorageOperationStatus getAndUpdateAllComponents(){ Map hasNotProps = new EnumMap<>(GraphPropertyEnum.class); hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); - return titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, null, hasNotProps, JsonParseFlagEnum.ParseAll) + return janusGraphDao + .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, null, hasNotProps, JsonParseFlagEnum.ParseAll) .either(this::updateComponentVertices, this::handleError); } @@ -101,16 +102,17 @@ public class InterfaceOperationMigration implements Migration { return status; } - private StorageOperationStatus handleError(TitanOperationStatus err) { - titanDao.rollback(); - return DaoStatusConverter.convertTitanStatusToStorageStatus( - TitanOperationStatus.NOT_FOUND == err ? TitanOperationStatus.OK : err); + private StorageOperationStatus handleError(JanusGraphOperationStatus err) { + janusGraphDao.rollback(); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + JanusGraphOperationStatus.NOT_FOUND == err ? JanusGraphOperationStatus.OK : err); } private StorageOperationStatus updateDataOnGraph(GraphVertex componentVertex) { try { - Either interfaceVertexEither = - titanDao.getChildVertex(componentVertex, EdgeLabelEnum.INTERFACE, JsonParseFlagEnum.ParseJson); + Either interfaceVertexEither = + janusGraphDao + .getChildVertex(componentVertex, EdgeLabelEnum.INTERFACE, JsonParseFlagEnum.ParseJson); if (interfaceVertexEither.isLeft()) { GraphVertex interfaceVertex = interfaceVertexEither.left().value(); Map interfaceDefinitions = (Map) interfaceVertex.getJson(); @@ -121,9 +123,10 @@ public class InterfaceOperationMigration implements Migration { } } interfaceVertex.setJson(interfaceDefinitions); - Either updateInterfaceVertexEither = titanDao.updateVertex(interfaceVertex); + Either updateInterfaceVertexEither = janusGraphDao + .updateVertex(interfaceVertex); if(updateInterfaceVertexEither.isRight()){ - return DaoStatusConverter.convertTitanStatusToStorageStatus(updateInterfaceVertexEither.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateInterfaceVertexEither.right().value()); } } @@ -134,8 +137,8 @@ public class InterfaceOperationMigration implements Migration { } } - Either instInterfaceVertexEither = - titanDao.getChildVertex(componentVertex, EdgeLabelEnum.INST_INTERFACES, JsonParseFlagEnum.ParseJson); + Either instInterfaceVertexEither = + janusGraphDao.getChildVertex(componentVertex, EdgeLabelEnum.INST_INTERFACES, JsonParseFlagEnum.ParseJson); if (instInterfaceVertexEither.isLeft()) { GraphVertex instInterfaceVertex = instInterfaceVertexEither.left().value(); Map instInterfaceDefinitions = (Map) instInterfaceVertex.getJson(); @@ -148,17 +151,18 @@ public class InterfaceOperationMigration implements Migration { } } instInterfaceVertex.setJson(instInterfaceDefinitions); - Either updateInstInterfaceVertexEither = titanDao.updateVertex(instInterfaceVertex); + Either updateInstInterfaceVertexEither = janusGraphDao + .updateVertex(instInterfaceVertex); if(updateInstInterfaceVertexEither.isRight()){ - return DaoStatusConverter.convertTitanStatusToStorageStatus(updateInstInterfaceVertexEither.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateInstInterfaceVertexEither.right().value()); } } } - titanDao.commit(); + janusGraphDao.commit(); } catch (Exception e) { LOGGER.debug("Interface operation migration failed with error : ", e); - titanDao.rollback(); + janusGraphDao.rollback(); return StorageOperationStatus.GENERAL_ERROR; } diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/servlets/ExportImportJanusGraphServlet.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/servlets/ExportImportJanusGraphServlet.java new file mode 100644 index 0000000000..e7d39ffb3e --- /dev/null +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/servlets/ExportImportJanusGraphServlet.java @@ -0,0 +1,165 @@ +/*- + * ============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.asdctool.servlets; + +import org.janusgraph.core.JanusGraph; +import org.apache.commons.configuration.BaseConfiguration; +import org.apache.commons.configuration.Configuration; +import org.apache.tinkerpop.gremlin.structure.io.graphml.GraphMLWriter; +import org.glassfish.jersey.media.multipart.FormDataParam; +import org.openecomp.sdc.asdctool.Utils; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.*; +import java.util.Map.Entry; +import java.util.Properties; +//import com.tinkerpop.blueprints.util.io.graphml.GraphMLWriter; + +@Path("/janusgraph") +public class ExportImportJanusGraphServlet { + + private static Logger log = Logger.getLogger(ExportImportJanusGraphServlet.class.getName()); + + @GET + @Path("export") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_OCTET_STREAM) + public Response export(@FormDataParam("janusGraphProperties") File janusGraphPropertiesFile, + @FormDataParam("metadata") String exportGraphMetadata) { + + printJanusGraphConfigFile(janusGraphPropertiesFile); + printMetadata(exportGraphMetadata); + + Properties janusGraphProperties = convertFileToProperties(janusGraphPropertiesFile); + + if (janusGraphProperties == null) { + Response response = Utils.buildOkResponse(400, "cannot parse janusgraph properties file", null); + return response; + } + + Configuration conf = new BaseConfiguration(); + for (Entry entry : janusGraphProperties.entrySet()) { + String key = entry.getKey().toString(); + Object value = entry.getValue(); + conf.setProperty(key, value); + } + + conf.setProperty("storage.machine-id-appendix", System.currentTimeMillis() % 1000); + + try(JanusGraph openGraph = Utils.openGraph(conf)){ + + if (openGraph == null) { + Response buildErrorResponse = Utils.buildOkResponse(500, "failed to open graph", null); + return buildErrorResponse; + } + + // Open JanusGraph Graph + + Response buildOkResponse = Utils.buildOkResponse(200, "ok man", null); + + return buildOkResponse; + } + } + + private Properties convertFileToProperties(File janusGraphPropertiesFile) { + + Properties properties = new Properties(); + + try (FileReader fileReader = new FileReader(janusGraphPropertiesFile)){ + properties.load(fileReader); + } catch (Exception e) { + log.error("Failed to convert file to properties", e); + return null; + } + + return properties; + } + + private void printJanusGraphConfigFile(File janusGraphPropertiesFile) { + + if (log.isDebugEnabled()) { + StringBuilder builder = new StringBuilder(); + try (BufferedReader br = new BufferedReader(new FileReader(janusGraphPropertiesFile))) { + String line; + while ((line = br.readLine()) != null) { + builder.append(line + Utils.NEW_LINE); + } + + log.debug(builder.toString()); + + } catch (IOException e) { + log.error("Cannot print janusgraph properties file", e); + } + } + } + + private void printMetadata(String exportGraphMetadata) { + + log.debug(exportGraphMetadata); + + } + + public String exportGraph(JanusGraph graph, String outputDirectory) { + + String result = null; + + // GraphMLWriter graphMLWriter = new GraphMLWriter(graph); + GraphMLWriter graphMLWriter = GraphMLWriter.build().create(); + + String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".ml"; + + OutputStream out = null; + try { + out = new BufferedOutputStream(new ByteArrayOutputStream()); + + // graphMLWriter.outputGraph(out); + + graphMLWriter.writeGraph(out, graph); + + // graph.commit(); + graph.tx().commit(); + + result = outputFile; + + } catch (Exception e) { + log.info("export Graph failed - {}" , e); + // graph.rollback(); + graph.tx().rollback(); + } finally { + try { + if (out != null) { + out.close(); + } + } catch (IOException e) { + log.info("close FileOutputStream failed - {}" , e); + } + } + return result; + + } + +} diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/servlets/ExportImportTitanServlet.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/servlets/ExportImportTitanServlet.java deleted file mode 100644 index 31b1b1f07a..0000000000 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/servlets/ExportImportTitanServlet.java +++ /dev/null @@ -1,165 +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.asdctool.servlets; - -import com.thinkaurelius.titan.core.TitanGraph; -import org.apache.commons.configuration.BaseConfiguration; -import org.apache.commons.configuration.Configuration; -import org.apache.tinkerpop.gremlin.structure.io.graphml.GraphMLWriter; -import org.glassfish.jersey.media.multipart.FormDataParam; -import org.openecomp.sdc.asdctool.Utils; -import org.openecomp.sdc.common.log.wrappers.Logger; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.io.*; -import java.util.Map.Entry; -import java.util.Properties; -//import com.tinkerpop.blueprints.util.io.graphml.GraphMLWriter; - -@Path("/titan") -public class ExportImportTitanServlet { - - private static Logger log = Logger.getLogger(ExportImportTitanServlet.class.getName()); - - @GET - @Path("export") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_OCTET_STREAM) - public Response export(@FormDataParam("titanProperties") File titanPropertiesFile, - @FormDataParam("metadata") String exportGraphMetadata) { - - printTitanConfigFile(titanPropertiesFile); - printMetadata(exportGraphMetadata); - - Properties titanProperties = convertFileToProperties(titanPropertiesFile); - - if (titanProperties == null) { - Response response = Utils.buildOkResponse(400, "cannot parse titan properties file", null); - return response; - } - - Configuration conf = new BaseConfiguration(); - for (Entry entry : titanProperties.entrySet()) { - String key = entry.getKey().toString(); - Object value = entry.getValue(); - conf.setProperty(key, value); - } - - conf.setProperty("storage.machine-id-appendix", System.currentTimeMillis() % 1000); - - try(TitanGraph openGraph = Utils.openGraph(conf)){ - - if (openGraph == null) { - Response buildErrorResponse = Utils.buildOkResponse(500, "failed to open graph", null); - return buildErrorResponse; - } - - // Open Titan Graph - - Response buildOkResponse = Utils.buildOkResponse(200, "ok man", null); - - return buildOkResponse; - } - } - - private Properties convertFileToProperties(File titanPropertiesFile) { - - Properties properties = new Properties(); - - try (FileReader fileReader = new FileReader(titanPropertiesFile)){ - properties.load(fileReader); - } catch (Exception e) { - log.error("Failed to convert file to properties", e); - return null; - } - - return properties; - } - - private void printTitanConfigFile(File titanPropertiesFile) { - - if (log.isDebugEnabled()) { - StringBuilder builder = new StringBuilder(); - try (BufferedReader br = new BufferedReader(new FileReader(titanPropertiesFile))) { - String line; - while ((line = br.readLine()) != null) { - builder.append(line + Utils.NEW_LINE); - } - - log.debug(builder.toString()); - - } catch (IOException e) { - log.error("Cannot print titan properties file", e); - } - } - } - - private void printMetadata(String exportGraphMetadata) { - - log.debug(exportGraphMetadata); - - } - - public String exportGraph(TitanGraph graph, String outputDirectory) { - - String result = null; - - // GraphMLWriter graphMLWriter = new GraphMLWriter(graph); - GraphMLWriter graphMLWriter = GraphMLWriter.build().create(); - - String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".ml"; - - OutputStream out = null; - try { - out = new BufferedOutputStream(new ByteArrayOutputStream()); - - // graphMLWriter.outputGraph(out); - - graphMLWriter.writeGraph(out, graph); - - // graph.commit(); - graph.tx().commit(); - - result = outputFile; - - } catch (Exception e) { - log.info("export Graph failed - {}" , e); - // graph.rollback(); - graph.tx().rollback(); - } finally { - try { - if (out != null) { - out.close(); - } - } catch (IOException e) { - log.info("close FileOutputStream failed - {}" , e); - } - } - return result; - - } - -} diff --git a/asdctool/src/main/resources/config/configuration.yaml b/asdctool/src/main/resources/config/configuration.yaml index bdc6a43e12..b1b51fd458 100644 --- a/asdctool/src/main/resources/config/configuration.yaml +++ b/asdctool/src/main/resources/config/configuration.yaml @@ -42,16 +42,16 @@ supportAllottedResourcesAndProxy: false deleteLockTimeoutInSeconds: 60 maxDeleteComponents: 10 -titanCfgFile: src\main\resources\config\titan.properties -titanMigrationKeySpaceCfgFile: src\main\resources\config\titan-migration.properties -titanInMemoryGraph: false -titanLockTimeout: 1800 +janusGraphCfgFile: src\main\resources\config\janusgraph.properties +janusGraphMigrationKeySpaceCfgFile: src\main\resources\config\janusgraph-migration.properties +janusGraphInMemoryGraph: false +janusGraphLockTimeout: 1800 -# The interval to try and reconnect to titan DB when it is down during ASDC startup: -titanReconnectIntervalInSeconds: 3 +# The interval to try and reconnect to JanusGraph DB when it is down during ASDC startup: +janusGraphReconnectIntervalInSeconds: 3 -# The read timeout towards Titan DB when health check is invoked: -titanHealthCheckReadTimeout: 1 +# The read timeout towards JanusGraph DB when health check is invoked: +janusGraphHealthCheckReadTimeout: 1 # The interval to try and reconnect to Elasticsearch when it is down during ASDC startup: esReconnectIntervalInSeconds: 3 diff --git a/asdctool/src/main/resources/config/janusgraph-migration.properties b/asdctool/src/main/resources/config/janusgraph-migration.properties new file mode 100644 index 0000000000..e982c2d085 --- /dev/null +++ b/asdctool/src/main/resources/config/janusgraph-migration.properties @@ -0,0 +1,4 @@ +storage.backend=cassandra +storage.hostname=localhost +storage.port=9160 +storage.cassandra.keyspace=sdctitan diff --git a/asdctool/src/main/resources/config/janusgraph.properties b/asdctool/src/main/resources/config/janusgraph.properties new file mode 100644 index 0000000000..5f22a08837 --- /dev/null +++ b/asdctool/src/main/resources/config/janusgraph.properties @@ -0,0 +1,28 @@ +storage.backend=cassandrathrift +storage.hostname=192.168.33.10 +storage.port=9160 +storage.username=asdc_user +storage.password=Aa1234%^! +storage.connection-timeout=10000 +storage.cassandra.keyspace=sdctitan + +storage.cassandra.ssl.enabled=true +storage.cassandra.ssl.truststore.location=C:\\gitWork\\vagrant-sdc-all-in-one\\mytmp.trust +storage.cassandra.ssl.truststore.password=Aa123456 + +storage.cassandra.read-consistency-level=LOCAL_QUORUM +storage.cassandra.write-consistency-level=LOCAL_QUORUM +storage.cassandra.replication-strategy-class=org.apache.cassandra.locator.NetworkTopologyStrategy +storage.cassandra.replication-strategy-options=DC-sdc-iltlv633,1 +storage.cassandra.astyanax.local-datacenter=DC-sdc-iltlv633 + + +cache.db-cache = false +cache.db-cache-clean-wait = 20 +cache.db-cache-time = 180000 +cache.db-cache-size = 0.5 + +cache.tx-cache-size = 1000000 + +storage.lock.retries=5 +storage.lock.wait-time=500 diff --git a/asdctool/src/main/resources/config/titan-migration.properties b/asdctool/src/main/resources/config/titan-migration.properties deleted file mode 100644 index e982c2d085..0000000000 --- a/asdctool/src/main/resources/config/titan-migration.properties +++ /dev/null @@ -1,4 +0,0 @@ -storage.backend=cassandra -storage.hostname=localhost -storage.port=9160 -storage.cassandra.keyspace=sdctitan diff --git a/asdctool/src/main/resources/config/titan.properties b/asdctool/src/main/resources/config/titan.properties deleted file mode 100644 index 5f22a08837..0000000000 --- a/asdctool/src/main/resources/config/titan.properties +++ /dev/null @@ -1,28 +0,0 @@ -storage.backend=cassandrathrift -storage.hostname=192.168.33.10 -storage.port=9160 -storage.username=asdc_user -storage.password=Aa1234%^! -storage.connection-timeout=10000 -storage.cassandra.keyspace=sdctitan - -storage.cassandra.ssl.enabled=true -storage.cassandra.ssl.truststore.location=C:\\gitWork\\vagrant-sdc-all-in-one\\mytmp.trust -storage.cassandra.ssl.truststore.password=Aa123456 - -storage.cassandra.read-consistency-level=LOCAL_QUORUM -storage.cassandra.write-consistency-level=LOCAL_QUORUM -storage.cassandra.replication-strategy-class=org.apache.cassandra.locator.NetworkTopologyStrategy -storage.cassandra.replication-strategy-options=DC-sdc-iltlv633,1 -storage.cassandra.astyanax.local-datacenter=DC-sdc-iltlv633 - - -cache.db-cache = false -cache.db-cache-clean-wait = 20 -cache.db-cache-time = 180000 -cache.db-cache-size = 0.5 - -cache.tx-cache-size = 1000000 - -storage.lock.retries=5 -storage.lock.wait-time=500 diff --git a/asdctool/src/main/resources/scripts/deleteAllProducts.sh b/asdctool/src/main/resources/scripts/deleteAllProducts.sh index 38e468d5f7..474b6c8980 100644 --- a/asdctool/src/main/resources/scripts/deleteAllProducts.sh +++ b/asdctool/src/main/resources/scripts/deleteAllProducts.sh @@ -1,8 +1,8 @@ #!/bin/bash -############################## -# delete all products from titan -############################## +##################################### +# delete all products from JanusGraph +##################################### CURRENT_DIR=`pwd` BASEDIR=$(dirname $0) diff --git a/asdctool/src/main/resources/scripts/exportUsers.sh b/asdctool/src/main/resources/scripts/exportUsers.sh index d701c57f92..fec7d5abe4 100644 --- a/asdctool/src/main/resources/scripts/exportUsers.sh +++ b/asdctool/src/main/resources/scripts/exportUsers.sh @@ -1,8 +1,8 @@ #!/bin/bash -############################## -# export all users from titan -############################## +################################## +# export all users from JanusGraph +################################## CURRENT_DIR=`pwd` BASEDIR=$(dirname $0) diff --git a/asdctool/src/main/resources/scripts/janusGraphSchemaCreation.sh b/asdctool/src/main/resources/scripts/janusGraphSchemaCreation.sh new file mode 100644 index 0000000000..d4b7871f30 --- /dev/null +++ b/asdctool/src/main/resources/scripts/janusGraphSchemaCreation.sh @@ -0,0 +1,33 @@ +#!/bin/bash + +############################## +# JanusGraph Schema Creation +############################## + +CURRENT_DIR=`pwd` +BASEDIR=$(dirname $0) + +if [ ${BASEDIR:0:1} = "/" ] +then + FULL_PATH=$BASEDIR +else + FULL_PATH=$CURRENT_DIR/$BASEDIR +fi + +source ${FULL_PATH}/baseOperation.sh + +mainClass="org.openecomp.sdc.asdctool.main.DataSchemaMenu" + +command="java $JVM_LOG_FILE -cp $JARS $mainClass create-janusgraph-structures $@" +echo $command + +$command +result=$? + +echo "***********************************" +echo "***** $result *********************" +echo "***********************************" + +exit $result + + diff --git a/asdctool/src/main/resources/scripts/titanSchemaCreation.sh b/asdctool/src/main/resources/scripts/titanSchemaCreation.sh deleted file mode 100644 index 8a2488b3e2..0000000000 --- a/asdctool/src/main/resources/scripts/titanSchemaCreation.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/bash - -############################## -# Titan Schema Creation -############################## - -CURRENT_DIR=`pwd` -BASEDIR=$(dirname $0) - -if [ ${BASEDIR:0:1} = "/" ] -then - FULL_PATH=$BASEDIR -else - FULL_PATH=$CURRENT_DIR/$BASEDIR -fi - -source ${FULL_PATH}/baseOperation.sh - -mainClass="org.openecomp.sdc.asdctool.main.DataSchemaMenu" - -command="java $JVM_LOG_FILE -cp $JARS $mainClass create-titan-structures $@" -echo $command - -$command -result=$? - -echo "***********************************" -echo "***** $result *********************" -echo "***********************************" - -exit $result - - diff --git a/asdctool/src/main/resources/scripts/updateIsVnf.sh b/asdctool/src/main/resources/scripts/updateIsVnf.sh index 62bfb9cd66..bf45fa88b5 100644 --- a/asdctool/src/main/resources/scripts/updateIsVnf.sh +++ b/asdctool/src/main/resources/scripts/updateIsVnf.sh @@ -3,7 +3,7 @@ ######################################################################## # # Example: -# ./updateIsVnf.sh ../config/titan.properties Bservice,Myservice +# ./updateIsVnf.sh ../config/janusgraph.properties Bservice,Myservice # ######################################################################## diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/UtilsTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/UtilsTest.java index 8a9b1357ea..cefda717aa 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/UtilsTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/UtilsTest.java @@ -1,6 +1,6 @@ package org.openecomp.sdc.asdctool; -import com.thinkaurelius.titan.core.TitanGraph; +import org.janusgraph.core.JanusGraph; import org.apache.commons.configuration.Configuration; import org.apache.tinkerpop.gremlin.structure.Element; import org.junit.Assert; @@ -34,7 +34,7 @@ public class UtilsTest { @Test public void testOpenGraph() throws Exception { Configuration conf = null; - TitanGraph result; + JanusGraph result; // default test with null result = Utils.openGraph(conf); diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/configuration/GetConsumersConfigurationTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/configuration/GetConsumersConfigurationTest.java index 5495d11827..7c661ae808 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/configuration/GetConsumersConfigurationTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/configuration/GetConsumersConfigurationTest.java @@ -1,7 +1,7 @@ package org.openecomp.sdc.asdctool.configuration; import org.junit.Test; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.model.operations.impl.ConsumerOperation; public class GetConsumersConfigurationTest { @@ -13,11 +13,11 @@ public class GetConsumersConfigurationTest { @Test public void testConsumerOperation() throws Exception { GetConsumersConfiguration testSubject; - TitanGenericDao titanGenericDao = null; + JanusGraphGenericDao janusGraphGenericDao = null; ConsumerOperation result; // default test testSubject = createTestSubject(); - result = testSubject.consumerOperation(titanGenericDao); + result = testSubject.consumerOperation(janusGraphGenericDao); } } \ No newline at end of file diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/ArtifactUuidFixTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/ArtifactUuidFixTest.java index 891946d26c..858538250d 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/ArtifactUuidFixTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/ArtifactUuidFixTest.java @@ -1,8 +1,7 @@ package org.openecomp.sdc.asdctool.impl; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; @@ -12,14 +11,14 @@ import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; @@ -40,10 +39,10 @@ public class ArtifactUuidFixTest { private ArtifactUuidFix test; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock - private TitanVertex vertex; + private JanusGraphVertex vertex; @Mock ToscaOperationFacade toscaOperationFacade; @@ -70,25 +69,26 @@ public class ArtifactUuidFixTest { graphVertex.setUniqueId(uniqueId); graphVertex.setMetadataProperties(hasProps1); list.add(graphVertex); - when(titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, hasProps1)).thenReturn(Either.left(list)); + when(janusGraphDao.getByCriteria(VertexTypeEnum.NODE_TYPE, hasProps1)).thenReturn(Either.left(list)); Map hasProps2 = new HashMap<>(); hasProps2.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); hasProps2.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF); hasProps2.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - when(titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps2)).thenReturn(Either.left(list)); + when(janusGraphDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps2)).thenReturn(Either.left(list)); Map hasProps3 = new HashMap<>(); hasProps3.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); hasProps3.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - when(titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps3)).thenReturn(Either.left(list)); + when(janusGraphDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps3)).thenReturn(Either.left(list)); Map hasProps = new HashMap<>(); hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF.name()); Map hasNotProps = new HashMap<>(); hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); - when(titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, hasNotProps, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(list)); + when(janusGraphDao + .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, hasNotProps, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(list)); Resource resource = new Resource(); resource.setName(uniqueId); Map deployArtifact = new HashMap<>(); @@ -155,7 +155,8 @@ public class ArtifactUuidFixTest { componentInstances.add(componentInstance); service.setComponentInstances(componentInstances); - when(titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, hasNotProps, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(list)); + when(janusGraphDao + .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, hasNotProps, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(list)); when(toscaOperationFacade.getToscaElement(ArgumentMatchers.eq(graphVertex.getUniqueId()),any(ComponentParametersView.class))) .thenReturn(Either.left(service)); byte[] payload = "value".getBytes(); @@ -188,7 +189,8 @@ public class ArtifactUuidFixTest { hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); Map hasNotProps = new HashMap<>(); hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); - when(titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, hasNotProps, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(list)); + when(janusGraphDao + .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, hasNotProps, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(list)); result = test.doFix(fixComponent, runMode); assertEquals(false,result); } diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/GraphJsonValidatorTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/GraphJsonValidatorTest.java index 06beb8d409..87d95ed997 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/GraphJsonValidatorTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/GraphJsonValidatorTest.java @@ -14,33 +14,33 @@ public class GraphJsonValidatorTest { } @Test - public void testVerifyTitanJson() throws Exception { + public void testVerifyJanusGraphJson() throws Exception { GraphJsonValidator testSubject; boolean result; // default test testSubject = createTestSubject(); - result = testSubject.verifyTitanJson("src/test/resources/graph.json"); + result = testSubject.verifyJanusGraphJson("src/test/resources/graph.json"); assertTrue(result); } @Test - public void testVerifyTitanJsonErrorFile() throws Exception { + public void testVerifyJanusGraphJsonErrorFile() throws Exception { GraphJsonValidator testSubject; boolean result; // default test testSubject = createTestSubject(); - result = testSubject.verifyTitanJson("src/test/resources/graphError.json"); + result = testSubject.verifyJanusGraphJson("src/test/resources/graphError.json"); assertFalse(result); } @Test(expected=NoSuchFileException.class) - public void testVerifyTitanJsonNoFile() throws Exception { + public void testVerifyJanusGraphJsonNoFile() throws Exception { GraphJsonValidator testSubject; // default test testSubject = createTestSubject(); - testSubject.verifyTitanJson("stam"); + testSubject.verifyJanusGraphJson("stam"); } } diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/GraphMLConverterTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/GraphMLConverterTest.java index 5ade4faef8..111f66d540 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/GraphMLConverterTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/GraphMLConverterTest.java @@ -1,6 +1,6 @@ package org.openecomp.sdc.asdctool.impl; -import com.thinkaurelius.titan.core.TitanGraph; +import org.janusgraph.core.JanusGraph; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Element; import org.junit.Test; @@ -61,18 +61,18 @@ public class GraphMLConverterTest { @Test(expected=IllegalArgumentException.class) public void testOpenGraph() throws Exception { GraphMLConverter testSubject; - String titanFileLocation = ""; - TitanGraph result; + String janusGraphFileLocation = ""; + JanusGraph result; // default test testSubject = createTestSubject(); - result = testSubject.openGraph("src/main/resources/config/titan.properties"); + result = testSubject.openGraph("src/main/resources/config/janusgraph.properties"); } @Test(expected=NullPointerException.class) public void testExportJsonGraph() throws Exception { GraphMLConverter testSubject; - TitanGraph graph = null; + JanusGraph graph = null; String outputDirectory = ""; String result; @@ -84,7 +84,7 @@ public class GraphMLConverterTest { @Test(expected=NullPointerException.class) public void testExportGraphMl_1() throws Exception { GraphMLConverter testSubject; - TitanGraph graph = null; + JanusGraph graph = null; String outputDirectory = ""; String result; @@ -96,7 +96,7 @@ public class GraphMLConverterTest { @Test public void testImportJsonGraph() throws Exception { GraphMLConverter testSubject; - TitanGraph graph = null; + JanusGraph graph = null; String graphJsonFile = ""; List> propertiesCriteriaToDelete = null; boolean result; @@ -109,7 +109,7 @@ public class GraphMLConverterTest { @Test(expected=NullPointerException.class) public void testFindErrorInJsonGraph_1() throws Exception { GraphMLConverter testSubject; - TitanGraph graph = null; + JanusGraph graph = null; String outputDirectory = ""; String result; @@ -122,7 +122,7 @@ public class GraphMLConverterTest { @Test(expected=NullPointerException.class) public void testExportUsers() throws Exception { GraphMLConverter testSubject; - TitanGraph graph = null; + JanusGraph graph = null; String outputDirectory = ""; String result; diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/GraphMLDataAnalyzerTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/GraphMLDataAnalyzerTest.java index c6905a939d..c2605a6946 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/GraphMLDataAnalyzerTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/GraphMLDataAnalyzerTest.java @@ -11,7 +11,7 @@ public class GraphMLDataAnalyzerTest { @Test public void testAnalyzeGraphMLData() throws Exception { GraphMLDataAnalyzer testSubject; - String[] args = new String[] { "export", "src/main/resources/config/titan.properties", "./" }; + String[] args = new String[] { "export", "src/main/resources/config/janusgraph.properties", "./" }; String result; // default test diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/JanusGraphInitializerTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/JanusGraphInitializerTest.java new file mode 100644 index 0000000000..5be99c382a --- /dev/null +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/JanusGraphInitializerTest.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.asdctool.impl; + +import org.junit.Test; + +public class JanusGraphInitializerTest { + + @Test(expected=IllegalArgumentException.class) + public void testCreateGraph() throws Exception { + String janusGraphCfgFile = ""; + boolean result; + + // default test + result = JanusGraphInitializer.createGraph(""); + + } +} \ No newline at end of file diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/ProductLogicTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/ProductLogicTest.java index 982c85b060..09c8b08db6 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/ProductLogicTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/ProductLogicTest.java @@ -12,7 +12,7 @@ public class ProductLogicTest { @Test public void testDeleteAllProducts() throws Exception { ProductLogic testSubject; - String titanFile = ""; + String janusGraphFile = ""; String beHost = ""; String bePort = ""; String adminUser = ""; @@ -20,7 +20,7 @@ public class ProductLogicTest { // default test testSubject = createTestSubject(); - result = testSubject.deleteAllProducts(titanFile, beHost, bePort, adminUser); + result = testSubject.deleteAllProducts(janusGraphFile, beHost, bePort, adminUser); assertFalse(result); } } diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/TitanGraphInitializerTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/TitanGraphInitializerTest.java deleted file mode 100644 index 431c59f591..0000000000 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/TitanGraphInitializerTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.openecomp.sdc.asdctool.impl; - -import org.junit.Test; - -public class TitanGraphInitializerTest { - - @Test(expected=IllegalArgumentException.class) - public void testCreateGraph() throws Exception { - String titanCfgFile = ""; - boolean result; - - // default test - result = TitanGraphInitializer.createGraph(""); - - } -} \ No newline at end of file diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/UpdatePropertyOnVertexTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/UpdatePropertyOnVertexTest.java index 4db5c06262..4e52ad527e 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/UpdatePropertyOnVertexTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/UpdatePropertyOnVertexTest.java @@ -1,6 +1,6 @@ package org.openecomp.sdc.asdctool.impl; -import com.thinkaurelius.titan.core.TitanGraph; +import org.janusgraph.core.JanusGraph; import org.junit.Test; import java.util.List; @@ -15,8 +15,8 @@ public class UpdatePropertyOnVertexTest { @Test(expected=IllegalArgumentException.class) public void testOpenGraph() throws Exception { UpdatePropertyOnVertex testSubject; - String titanFileLocation = ""; - TitanGraph result; + String janusGraphFileLocation = ""; + JanusGraph result; // default test testSubject = createTestSubject(); @@ -26,13 +26,13 @@ public class UpdatePropertyOnVertexTest { @Test(expected=NullPointerException.class) public void testUpdatePropertyOnServiceAtLeastCertified() throws Exception { UpdatePropertyOnVertex testSubject; - String titanFile = ""; + String janusGraphFile = ""; Map keyValueToSet = null; List> orCriteria = null; Integer result; // default test testSubject = createTestSubject(); - result = testSubject.updatePropertyOnServiceAtLeastCertified(titanFile, keyValueToSet, orCriteria); + result = testSubject.updatePropertyOnServiceAtLeastCertified(janusGraphFile, keyValueToSet, orCriteria); } } \ No newline at end of file diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/VrfObjectFixHandlerTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/VrfObjectFixHandlerTest.java index c0ae55a607..b6ab4f5b55 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/VrfObjectFixHandlerTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/VrfObjectFixHandlerTest.java @@ -6,9 +6,9 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyMap; @@ -18,14 +18,14 @@ import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class VrfObjectFixHandlerTest { - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; private VrfObjectFixHandler vrfObjectFixHandler; @Before public void init(){ - titanDao = Mockito.mock(TitanDao.class); - vrfObjectFixHandler = new VrfObjectFixHandler(titanDao); + janusGraphDao = Mockito.mock(JanusGraphDao.class); + vrfObjectFixHandler = new VrfObjectFixHandler(janusGraphDao); } @Test @@ -35,25 +35,29 @@ public class VrfObjectFixHandlerTest { @Test public void handleDetectNotFoundTest(){ - when(titanDao.getByCriteria(eq(VertexTypeEnum.NODE_TYPE), anyMap())).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); + when(janusGraphDao.getByCriteria(eq(VertexTypeEnum.NODE_TYPE), anyMap())).thenReturn(Either.right( + JanusGraphOperationStatus.NOT_FOUND)); assertThat(vrfObjectFixHandler.handle("detect", null)).isTrue(); } @Test - public void handleDetectTitanNotConnectedTest(){ - when(titanDao.getByCriteria(eq(VertexTypeEnum.NODE_TYPE), anyMap())).thenReturn(Either.right(TitanOperationStatus.NOT_CONNECTED)); + public void handleDetectJanusGraphNotConnectedTest(){ + when(janusGraphDao.getByCriteria(eq(VertexTypeEnum.NODE_TYPE), anyMap())).thenReturn(Either.right( + JanusGraphOperationStatus.NOT_CONNECTED)); assertThat(vrfObjectFixHandler.handle("detect", null)).isFalse(); } @Test public void handleFixNotFoundTest(){ - when(titanDao.getByCriteria(eq(VertexTypeEnum.NODE_TYPE), anyMap())).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); + when(janusGraphDao.getByCriteria(eq(VertexTypeEnum.NODE_TYPE), anyMap())).thenReturn(Either.right( + JanusGraphOperationStatus.NOT_FOUND)); assertThat(vrfObjectFixHandler.handle("fix", null)).isTrue(); } @Test public void handleFixNotCreatedTest(){ - when(titanDao.getByCriteria(eq(VertexTypeEnum.NODE_TYPE), anyMap())).thenReturn(Either.right(TitanOperationStatus.NOT_CREATED)); + when(janusGraphDao.getByCriteria(eq(VertexTypeEnum.NODE_TYPE), anyMap())).thenReturn(Either.right( + JanusGraphOperationStatus.NOT_CREATED)); assertThat(vrfObjectFixHandler.handle("fix", null)).isFalse(); } diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/internal/tool/CsarGeneratorTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/internal/tool/CsarGeneratorTest.java index 4e80f8e119..109aa9d102 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/internal/tool/CsarGeneratorTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/internal/tool/CsarGeneratorTest.java @@ -37,7 +37,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; @@ -45,7 +45,7 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.*; @@ -58,7 +58,7 @@ public class CsarGeneratorTest { private CsarGenerator test; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private Component component; @@ -83,9 +83,10 @@ public class CsarGeneratorTest { props.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); graphVertex.setMetadataProperties(props); - when(titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props)).thenReturn(Either.left(list)); + when(janusGraphDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props)).thenReturn(Either.left(list)); when(toscaOperationFacade.getToscaFullElement(any(String.class))).thenReturn(Either.left(component)); - when(titanDao.getChildVertex(graphVertex, EdgeLabelEnum.TOSCA_ARTIFACTS, JsonParseFlagEnum.ParseJson)).thenReturn(Either.left(graphVertex)); + when(janusGraphDao + .getChildVertex(graphVertex, EdgeLabelEnum.TOSCA_ARTIFACTS, JsonParseFlagEnum.ParseJson)).thenReturn(Either.left(graphVertex)); test.generateCsar(uuid,scanner); } diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/internal/tool/DeleteComponentHandlerTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/internal/tool/DeleteComponentHandlerTest.java index 315f615fb4..b7e8eae560 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/internal/tool/DeleteComponentHandlerTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/internal/tool/DeleteComponentHandlerTest.java @@ -29,7 +29,7 @@ */ package org.openecomp.sdc.asdctool.impl.internal.tool; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import org.junit.Test; import org.junit.runner.RunWith; @@ -39,11 +39,11 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.HashMap; @@ -58,7 +58,7 @@ public class DeleteComponentHandlerTest { private DeleteComponentHandler test; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private TopologyTemplateOperation topologyTemplateOperation; @@ -74,7 +74,7 @@ public class DeleteComponentHandlerTest { Scanner scanner = new Scanner(in); String id = "start"; GraphVertex loc = new GraphVertex(); - TitanVertex vertex = Mockito.mock(TitanVertex.class); + JanusGraphVertex vertex = Mockito.mock(JanusGraphVertex.class); loc.setVertex(vertex); Map metadataProperties = new HashMap<>(); @@ -83,7 +83,7 @@ public class DeleteComponentHandlerTest { metadataProperties.put(GraphPropertyEnum.NAME, "user1"); loc.setMetadataProperties(metadataProperties); - when(titanDao.getVertexById(id)).thenReturn(Either.left(loc)); + when(janusGraphDao.getVertexById(id)).thenReturn(Either.left(loc)); when(topologyTemplateOperation.deleteToscaElement(ArgumentMatchers.any(GraphVertex.class))).thenReturn(Either.left(toscaElement)); test.deleteComponent(id,scanner); diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfigurationTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfigurationTest.java index 0d91f1a29e..cf064ee04d 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfigurationTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfigurationTest.java @@ -8,13 +8,13 @@ import org.openecomp.sdc.asdctool.impl.validator.tasks.artifacts.ArtifactValidat import org.openecomp.sdc.asdctool.impl.validator.tasks.artifacts.ServiceArtifactValidationTask; import org.openecomp.sdc.asdctool.impl.validator.tasks.artifacts.VfArtifactValidationTask; import org.openecomp.sdc.asdctool.impl.validator.tasks.moduleJson.ModuleJsonTask; -import org.openecomp.sdc.be.dao.TitanClientStrategy; +import org.openecomp.sdc.be.dao.JanusGraphClientStrategy; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraClient; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; import org.openecomp.sdc.be.model.DerivedNodeTypeResolver; -import org.openecomp.sdc.be.model.jsontitan.operations.*; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.*; public class ValidationToolConfigurationTest { @@ -125,7 +125,7 @@ public class ValidationToolConfigurationTest { @Test public void testDaoStrategy() { ValidationToolConfiguration testSubject; - TitanClientStrategy result; + JanusGraphClientStrategy result; // default test testSubject = createTestSubject(); @@ -174,14 +174,14 @@ public class ValidationToolConfigurationTest { } @Test - public void testTitanDao() { + public void testJanusGraphDao() { ValidationToolConfiguration testSubject; - TitanGraphClient titanGraphClient = null; - TitanDao result; + JanusGraphClient janusGraphClient = null; + JanusGraphDao result; // default test testSubject = createTestSubject(); - result = testSubject.titanDao(titanGraphClient); + result = testSubject.janusGraphDao(janusGraphClient); } @Test diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/validator/tasks/moduleJson/ModuleJsonTaskTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/validator/tasks/moduleJson/ModuleJsonTaskTest.java index 5799b6d03d..e4fb979620 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/validator/tasks/moduleJson/ModuleJsonTaskTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/impl/validator/tasks/moduleJson/ModuleJsonTaskTest.java @@ -15,8 +15,8 @@ import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation; import java.util.HashMap; import java.util.Map; diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710Test.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710Test.java index 8d46e61011..64e06ac5fb 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710Test.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710Test.java @@ -41,18 +41,18 @@ import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLog import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; 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.CsarOperation; @@ -95,7 +95,7 @@ public class UpgradeMigration1710Test { @Mock private LifecycleBusinessLogic lifecycleBusinessLogic; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private ComponentsUtils componentUtils; @Mock @@ -179,8 +179,8 @@ public class UpgradeMigration1710Test { public void nodeTypesUpgradeFailed() { migration.setNodeTypesSupportOnly(true); resolveUserAndDefineUpgradeLevel(); - when(titanDao.getByCriteria(any(), any(), any(), any())) - .thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); + when(janusGraphDao.getByCriteria(any(), any(), any(), any())) + .thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); assertEquals(MigrationResult.MigrationStatus.FAILED, migration.migrate().getMigrationStatus()); } @@ -189,8 +189,8 @@ public class UpgradeMigration1710Test { configurationManager.getConfiguration().setEnableAutoHealing(false); migration.init(); assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus()); - verify(titanDao, times(0)).commit(); - verify(titanDao, times(0)).rollback(); + verify(janusGraphDao, times(0)).commit(); + verify(janusGraphDao, times(0)).rollback(); } @Test @@ -213,8 +213,8 @@ public class UpgradeMigration1710Test { migration.setNodeTypesSupportOnly(true); upgradeAllScenario(false); assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus()); - verify(titanDao, times(2)).commit(); - verify(titanDao, times(0)).rollback(); + verify(janusGraphDao, times(2)).commit(); + verify(janusGraphDao, times(0)).rollback(); } @Test @@ -230,8 +230,8 @@ public class UpgradeMigration1710Test { resolveUserAndDefineUpgradeLevel(); upgradeRules(failOnVfUpgrade, exceptionOnVfUpgrade, upgradeServices, upgradeVFC, isFailed); assertEquals(MigrationResult.MigrationStatus.FAILED, migration.migrate().getMigrationStatus()); - verify(titanDao, times(1)).commit(); - verify(titanDao, times(2)).rollback(); + verify(janusGraphDao, times(1)).commit(); + verify(janusGraphDao, times(2)).rollback(); } @@ -247,8 +247,8 @@ public class UpgradeMigration1710Test { upgradeRules(failOnVfUpgrade, exceptionOnVfUpgrade, upgradeServices, upgradeVFC, isFailed); migration.init(); assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus()); - verify(titanDao, times(2)).commit(); - verify(titanDao, times(0)).rollback(); + verify(janusGraphDao, times(2)).commit(); + verify(janusGraphDao, times(0)).rollback(); } @Test @@ -262,8 +262,8 @@ public class UpgradeMigration1710Test { resolveUserAndDefineUpgradeLevel(); upgradeRules(failOnVfUpgrade, exceptionOnFvUpgrade, upgradeServices, upgradeVFC, isFailed); assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus()); - verify(titanDao, times(3)).commit(); - verify(titanDao, times(1)).rollback(); + verify(janusGraphDao, times(3)).commit(); + verify(janusGraphDao, times(1)).rollback(); } @@ -271,8 +271,8 @@ public class UpgradeMigration1710Test { public void upgradeAll() { upgradeAllScenario(true); assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus()); - verify(titanDao, times(4)).commit(); - verify(titanDao, times(0)).rollback(); + verify(janusGraphDao, times(4)).commit(); + verify(janusGraphDao, times(0)).rollback(); } @Test @@ -282,8 +282,8 @@ public class UpgradeMigration1710Test { .thenReturn(StorageOperationStatus.OK); upgradeAllScenario(true); assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus()); - verify(titanDao, times(4)).commit(); - verify(titanDao, times(0)).rollback(); + verify(janusGraphDao, times(4)).commit(); + verify(janusGraphDao, times(0)).rollback(); } @Test @@ -302,7 +302,7 @@ public class UpgradeMigration1710Test { @Test public void migrationFailedWhenUserNotResolved() { when(userAdminOperation.getUserData(anyString(), eq(false))).thenReturn(Either.right(ActionStatus.MISSING_INFORMATION)); - when(titanDao.rollback()).thenReturn(TitanOperationStatus.OK); + when(janusGraphDao.rollback()).thenReturn(JanusGraphOperationStatus.OK); assertEquals(MigrationResult.MigrationStatus.FAILED, migration.migrate().getMigrationStatus()); } @@ -523,13 +523,13 @@ public class UpgradeMigration1710Test { List components = Lists.newArrayList(); components.add(component); - when(titanDao.getByCriteria(any(), any(), any(), any())) + when(janusGraphDao.getByCriteria(any(), any(), any(), any())) .thenReturn(Either.left(components)); - when(titanDao.getParentVertecies(any(GraphVertex.class), any(EdgeLabelEnum.class), any(JsonParseFlagEnum.class))) + when(janusGraphDao.getParentVertecies(any(GraphVertex.class), any(EdgeLabelEnum.class), any(JsonParseFlagEnum.class))) //1th node to upgrade .thenReturn(Either.left(components)) //parent of the 1th node - stop recursion - .thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); + .thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); } private GraphVertex createComponent() { @@ -601,7 +601,7 @@ public class UpgradeMigration1710Test { components.add(component); when(toscaOperationFacade.getToscaElement(anyString())).thenReturn(Either.left(resource)); - when(titanDao.getByCriteria(any(), any(), any(), any())) + when(janusGraphDao.getByCriteria(any(), any(), any(), any())) .thenReturn(Either.left(components)); when(csarOperation.getCsarLatestVersion(anyString(), any())) .thenReturn(Either.left("2.0")); diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1802/SdcCatalogMigrationTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1802/SdcCatalogMigrationTest.java index 00b6d573af..47481f8f46 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1802/SdcCatalogMigrationTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1802/SdcCatalogMigrationTest.java @@ -3,14 +3,14 @@ package org.openecomp.sdc.asdctool.migration.tasks.mig1802; import org.junit.Test; import org.openecomp.sdc.asdctool.migration.core.DBVersion; import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanGraphClient; -import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation; public class SdcCatalogMigrationTest { private SdcCatalogMigration createTestSubject() { - return new SdcCatalogMigration(new TopologyTemplateOperation(), new TitanDao(new TitanGraphClient())); + return new SdcCatalogMigration(new TopologyTemplateOperation(), new JanusGraphDao(new JanusGraphClient())); } @Test diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ForwardPathMigrationTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ForwardPathMigrationTest.java index c10291b198..581ae09c26 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ForwardPathMigrationTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ForwardPathMigrationTest.java @@ -8,8 +8,8 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.openecomp.sdc.asdctool.migration.core.DBVersion; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation; public class ForwardPathMigrationTest { @@ -17,7 +17,7 @@ public class ForwardPathMigrationTest { ForwardPathMigration forwardPathMigration = null; @Mock - TitanDao titanDao; + JanusGraphDao janusGraphDao; @Mock UserAdminOperation userAdminOperation; @@ -27,7 +27,7 @@ public class ForwardPathMigrationTest { @Before public void setUp() throws Exception { - forwardPathMigration = new ForwardPathMigration(titanDao, userAdminOperation, toscaOperationFacade); + forwardPathMigration = new ForwardPathMigration(janusGraphDao, userAdminOperation, toscaOperationFacade); } @Test diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ResourceLifecycleMigrationTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ResourceLifecycleMigrationTest.java index b7f014039e..c3266f9ce2 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ResourceLifecycleMigrationTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ResourceLifecycleMigrationTest.java @@ -11,14 +11,14 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.asdctool.migration.core.DBVersion; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation; @RunWith(MockitoJUnitRunner.class) public class ResourceLifecycleMigrationTest { @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private LifecycleBusinessLogic lifecycleBusinessLogic; @Mock @@ -29,7 +29,7 @@ public class ResourceLifecycleMigrationTest { @Before public void setUp() throws Exception { resourceLifecycleMigration = - new ResourceLifecycleMigration(titanDao, lifecycleBusinessLogic, userAdminOperation); + new ResourceLifecycleMigration(janusGraphDao, lifecycleBusinessLogic, userAdminOperation); } @Test diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SDCInstancesMigrationTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SDCInstancesMigrationTest.java index d040d66496..2a55aaf1fa 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SDCInstancesMigrationTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SDCInstancesMigrationTest.java @@ -7,14 +7,14 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult; import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult.MigrationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import java.util.ArrayList; @@ -29,15 +29,16 @@ import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class SDCInstancesMigrationTest{ @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private NodeTemplateOperation nodeTemplateOperation; @Test public void testFailedMigration(){ - SDCInstancesMigration instancesMigration = new SDCInstancesMigration(titanDao, nodeTemplateOperation); - when(titanDao.getByCriteria(any(), any(), any(), any() )).thenReturn(Either.right(TitanOperationStatus.GENERAL_ERROR)); + SDCInstancesMigration instancesMigration = new SDCInstancesMigration(janusGraphDao, nodeTemplateOperation); + when(janusGraphDao.getByCriteria(any(), any(), any(), any() )).thenReturn(Either.right( + JanusGraphOperationStatus.GENERAL_ERROR)); MigrationResult migrate = instancesMigration.migrate(); MigrationStatus migrationStatus = migrate.getMigrationStatus(); @@ -45,7 +46,7 @@ public class SDCInstancesMigrationTest{ } @Test public void testSuccessMigration(){ - SDCInstancesMigration instancesMigration = new SDCInstancesMigration(titanDao, nodeTemplateOperation); + SDCInstancesMigration instancesMigration = new SDCInstancesMigration(janusGraphDao, nodeTemplateOperation); List list = new ArrayList<>(); GraphVertex vertexOrig = new GraphVertex(); Map jsonComposition = new HashMap<>(); @@ -59,7 +60,7 @@ public class SDCInstancesMigrationTest{ vertexOrig.setType(ComponentTypeEnum.SERVICE); list.add(vertexOrig); - when(titanDao.getByCriteria(any(), any(), any(), any() )).thenReturn(Either.left(list)); + when(janusGraphDao.getByCriteria(any(), any(), any(), any() )).thenReturn(Either.left(list)); when(nodeTemplateOperation.createInstanceEdge(vertexOrig, instance)).thenReturn(StorageOperationStatus.OK); MigrationResult migrate = instancesMigration.migrate(); diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SdcArchiveMigrationTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SdcArchiveMigrationTest.java index 0ea3b91083..1d3e7612ac 100644 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SdcArchiveMigrationTest.java +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/SdcArchiveMigrationTest.java @@ -10,18 +10,18 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.asdctool.migration.core.DBVersion; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; @RunWith(MockitoJUnitRunner.class) public class SdcArchiveMigrationTest { @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; SdcArchiveMigration sdcArchiveMigration = null; @Before public void setUp() throws Exception { - sdcArchiveMigration = new SdcArchiveMigration(titanDao); + sdcArchiveMigration = new SdcArchiveMigration(janusGraphDao); } @Test diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/servlets/ExportImportJanusGraphServletTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/servlets/ExportImportJanusGraphServletTest.java new file mode 100644 index 0000000000..93606e271d --- /dev/null +++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/servlets/ExportImportJanusGraphServletTest.java @@ -0,0 +1,38 @@ +package org.openecomp.sdc.asdctool.servlets; + +import org.janusgraph.core.JanusGraph; +import org.junit.Test; + +import javax.ws.rs.core.Response; +import java.io.File; + +public class ExportImportJanusGraphServletTest { + + private ExportImportJanusGraphServlet createTestSubject() { + return new ExportImportJanusGraphServlet(); + } + + @Test(expected=NullPointerException.class) + public void testExport() throws Exception { + ExportImportJanusGraphServlet testSubject; + File janusGraphPropertiesFile = null; + String exportGraphMetadata = ""; + Response result; + + // default test + testSubject = createTestSubject(); + result = testSubject.export(janusGraphPropertiesFile, exportGraphMetadata); + } + + @Test(expected=NullPointerException.class) + public void testExportGraph() throws Exception { + ExportImportJanusGraphServlet testSubject; + JanusGraph graph = null; + String outputDirectory = ""; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.exportGraph(graph, outputDirectory); + } +} \ No newline at end of file diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/servlets/ExportImportTitanServletTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/servlets/ExportImportTitanServletTest.java deleted file mode 100644 index 9f104632dd..0000000000 --- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/servlets/ExportImportTitanServletTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.openecomp.sdc.asdctool.servlets; - -import com.thinkaurelius.titan.core.TitanGraph; -import org.junit.Test; - -import javax.ws.rs.core.Response; -import java.io.File; - -public class ExportImportTitanServletTest { - - private ExportImportTitanServlet createTestSubject() { - return new ExportImportTitanServlet(); - } - - @Test(expected=NullPointerException.class) - public void testExport() throws Exception { - ExportImportTitanServlet testSubject; - File titanPropertiesFile = null; - String exportGraphMetadata = ""; - Response result; - - // default test - testSubject = createTestSubject(); - result = testSubject.export(titanPropertiesFile, exportGraphMetadata); - } - - @Test(expected=NullPointerException.class) - public void testExportGraph() throws Exception { - ExportImportTitanServlet testSubject; - TitanGraph graph = null; - String outputDirectory = ""; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.exportGraph(graph, outputDirectory); - } -} \ No newline at end of file diff --git a/build.gradle b/build.gradle index d15a3ca28c..4dcc3d27b6 100644 --- a/build.gradle +++ b/build.gradle @@ -292,7 +292,7 @@ def gitLatest(){ } def newEcoSystem(){ - //cleanTitan() + //cleanJanusGraph() backupDB() //and clean all //restoreDB() //restore latest createSchema() @@ -322,11 +322,11 @@ def createSchemaPostStep(){ def createSchema(){ createSchemaPreStep() //todo- create schema - //todo- create titan + //todo- create JanusGraph createSchemaPostStep() } -def cleanTitan(){ +def cleanJanusGraph(){ execSafe{ ssh.settings { knownHosts = allowAnyHosts @@ -339,9 +339,9 @@ def cleanTitan(){ } } } -task cleanTitan { +task cleanJanusGraph { doLast{ - cleanTitan() + cleanJanusGraph() } } diff --git a/catalog-be/pom.xml b/catalog-be/pom.xml index dcd4c586cb..dfa6eaa031 100644 --- a/catalog-be/pom.xml +++ b/catalog-be/pom.xml @@ -301,11 +301,10 @@ compile - - com.thinkaurelius.titan - titan-core - ${titan.version} + org.janusgraph + janusgraph-core + ${janusgraph.version} compile @@ -324,9 +323,9 @@ - org.onap.sdc.sdc-titan-cassandra - sdc-titan-cassandra - ${sdc.titan.version} + org.janusgraph + janusgraph-cassandra + ${janusgraph.version} compile @@ -346,7 +345,6 @@ ${lang3.version} compile - com.googlecode.json-simple @@ -407,25 +405,6 @@ 20131018 compile - - org.apache.tinkerpop - tinkergraph-gremlin - 3.0.1-incubating - compile - - - - org.apache.tinkerpop - gremlin-groovy - 3.0.1-incubating - compile - - - groovy - org.codehaus.groovy - - - diff --git a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb index 09c5cb3974..763db8f5a4 100644 --- a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb +++ b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb @@ -20,7 +20,7 @@ default['cassandra']['datacenter_name'] = "DC-" default['cassandra']['cluster_name'] = "SDC-CS-" default['cassandra']['socket_read_timeout'] = 20000 default['cassandra']['socket_connect_timeout'] = 20000 -default['cassandra']['titan_connection_timeout'] = 10000 +default['cassandra']['janusgraph_connection_timeout'] = 10000 #Elasticsearch default['elasticsearch']['cluster_name'] = "SDC-ES-" diff --git a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_2_setup_configuration.rb b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_2_setup_configuration.rb index 5d83cdbd43..20c144c056 100644 --- a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_2_setup_configuration.rb +++ b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_2_setup_configuration.rb @@ -2,18 +2,18 @@ replication_factor=node['cassandra']['replication_factor'] if node['Pair_EnvName'] == "" - titan_dcname_with_rep = node['cassandra']['datacenter_name'] + "," + replication_factor.to_s + janusgraph_dcname_with_rep = node['cassandra']['datacenter_name'] + "," + replication_factor.to_s conf_dcname_with_rep = node['cassandra']['datacenter_name'] + "','" + replication_factor.to_s else - titan_dcname_with_rep = node['cassandra']['datacenter_name'] + "," + replication_factor.to_s + "," + node['cassandra']['cluster_name'] + node['Pair_EnvName'] + "," + replication_factor.to_s + janusgraph_dcname_with_rep = node['cassandra']['datacenter_name'] + "," + replication_factor.to_s + "," + node['cassandra']['cluster_name'] + node['Pair_EnvName'] + "," + replication_factor.to_s conf_dcname_with_rep = node['cassandra']['datacenter_name'] + "','" + replication_factor.to_s + "','" + node['cassandra']['cluster_name'] + node['Pair_EnvName'] + "','" + replication_factor.to_s end -template "titan.properties" do - path "#{ENV['JETTY_BASE']}/config/catalog-be/titan.properties" - source "BE-titan.properties.erb" +template "janusgraph.properties" do + path "#{ENV['JETTY_BASE']}/config/catalog-be/janusgraph.properties" + source "BE-janusgraph.properties.erb" owner "jetty" group "jetty" mode "0755" @@ -23,8 +23,8 @@ template "titan.properties" do :cassandra_usr => node['cassandra'][:cassandra_user], :rep_factor => replication_factor, :DC_NAME => node['cassandra']['datacenter_name'], - :DC_NAME_WITH_REP => titan_dcname_with_rep, - :titan_connection_timeout => node['cassandra']['titan_connection_timeout'], + :DC_NAME_WITH_REP => janusgraph_dcname_with_rep, + :janusgraph_connection_timeout => node['cassandra']['janusgraph_connection_timeout'], :cassandra_truststore_password => node['cassandra'][:truststore_password], :cassandra_ssl_enabled => "#{ENV['cassandra_ssl_enabled']}" }) @@ -46,7 +46,7 @@ template "catalog-be-config" do :rep_factor => replication_factor, :DC_NAME => node['cassandra']['datacenter_name'], :REP_STRING => conf_dcname_with_rep, - :titan_Path => "/var/lib/jetty/config/catalog-be/", + :janusgraph_Path => "/var/lib/jetty/config/catalog-be/", :socket_connect_timeout => node['cassandra']['socket_connect_timeout'], :socket_read_timeout => node['cassandra']['socket_read_timeout'], :cassandra_pwd => node['cassandra'][:cassandra_password], diff --git a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb index 0ad9997c3f..6a49b19c5e 100644 --- a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb +++ b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb @@ -28,14 +28,14 @@ released: 2012-11-30 toscaConformanceLevel: 9.0 minToscaConformanceLevel: 3.0 -titanCfgFile: /var/lib/jetty/config/catalog-be/titan.properties -titanInMemoryGraph: false -titanLockTimeout: 1800 -# The interval to try and reconnect to titan DB when it is down during ASDC startup: -titanReconnectIntervalInSeconds: 3 - -# The read timeout towards Titan DB when health check is invoked: -titanHealthCheckReadTimeout: 1 +janusGraphCfgFile: /var/lib/jetty/config/catalog-be/janusgraph.properties +janusGraphInMemoryGraph: false +janusGraphLockTimeout: 1800 +# The interval to try and reconnect to JanusGraph DB when it is down during ASDC startup: +janusGraphReconnectIntervalInSeconds: 3 + +# The read timeout towards JanusGraph DB when health check is invoked: +janusGraphHealthCheckReadTimeout: 1 # The interval to try and reconnect to Elasticsearch when it is down during ASDC startup: diff --git a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-janusgraph.properties.erb b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-janusgraph.properties.erb new file mode 100644 index 0000000000..e091052709 --- /dev/null +++ b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-janusgraph.properties.erb @@ -0,0 +1,28 @@ +storage.backend=cassandra +storage.hostname=<%= @cassandra_ip %> +storage.port=9160 +storage.username=<%= @cassandra_usr %> +storage.password=<%= @cassandra_pwd %> +storage.connection-timeout=<%= @janusgraph_connection_timeout %> +storage.cassandra.keyspace=sdctitan + +storage.cassandra.ssl.enabled=<%= @cassandra_ssl_enabled %> +storage.cassandra.ssl.truststore.location=/var/lib/jetty/etc/truststore +storage.cassandra.ssl.truststore.password=<%= @cassandra_truststore_password %> + +storage.cassandra.read-consistency-level=LOCAL_QUORUM +storage.cassandra.write-consistency-level=LOCAL_QUORUM +storage.cassandra.replication-strategy-class=org.apache.cassandra.locator.NetworkTopologyStrategy +storage.cassandra.replication-strategy-options=<%= @DC_NAME_WITH_REP %> +storage.cassandra.astyanax.local-datacenter=<%= @DC_NAME %> + + +cache.db-cache = false +cache.db-cache-clean-wait = 20 +cache.db-cache-time = 180000 +cache.db-cache-size = 0.5 + +cache.tx-cache-size = 1000000 + +storage.lock.retries=5 +storage.lock.wait-time=500 diff --git a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-titan.properties.erb b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-titan.properties.erb deleted file mode 100644 index 1a259a1f98..0000000000 --- a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-titan.properties.erb +++ /dev/null @@ -1,28 +0,0 @@ -storage.backend=cassandra -storage.hostname=<%= @cassandra_ip %> -storage.port=9160 -storage.username=<%= @cassandra_usr %> -storage.password=<%= @cassandra_pwd %> -storage.connection-timeout=<%= @titan_connection_timeout %> -storage.cassandra.keyspace=sdctitan - -storage.cassandra.ssl.enabled=<%= @cassandra_ssl_enabled %> -storage.cassandra.ssl.truststore.location=/var/lib/jetty/etc/truststore -storage.cassandra.ssl.truststore.password=<%= @cassandra_truststore_password %> - -storage.cassandra.read-consistency-level=LOCAL_QUORUM -storage.cassandra.write-consistency-level=LOCAL_QUORUM -storage.cassandra.replication-strategy-class=org.apache.cassandra.locator.NetworkTopologyStrategy -storage.cassandra.replication-strategy-options=<%= @DC_NAME_WITH_REP %> -storage.cassandra.astyanax.local-datacenter=<%= @DC_NAME %> - - -cache.db-cache = false -cache.db-cache-clean-wait = 20 -cache.db-cache-time = 180000 -cache.db-cache-size = 0.5 - -cache.tx-cache-size = 1000000 - -storage.lock.retries=5 -storage.lock.wait-time=500 diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/YamlTemplateParsingHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/YamlTemplateParsingHandler.java index 04df614b9d..7b3d4fac25 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/YamlTemplateParsingHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/YamlTemplateParsingHandler.java @@ -35,7 +35,7 @@ import org.openecomp.sdc.be.components.impl.NodeFilterUploadCreator; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; 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.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; @@ -67,13 +67,13 @@ public class YamlTemplateParsingHandler { private Gson gson = new Gson(); - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; private GroupTypeBusinessLogic groupTypeBusinessLogic; private AnnotationBusinessLogic annotationBusinessLogic; - public YamlTemplateParsingHandler(TitanDao titanDao, + public YamlTemplateParsingHandler(JanusGraphDao janusGraphDao, GroupTypeBusinessLogic groupTypeBusinessLogic, AnnotationBusinessLogic annotationBusinessLogic) { - this.titanDao = titanDao; + this.janusGraphDao = janusGraphDao; this.groupTypeBusinessLogic = groupTypeBusinessLogic; this.annotationBusinessLogic = annotationBusinessLogic; } @@ -865,17 +865,17 @@ public class YamlTemplateParsingHandler { } private Map failIfNoNodeTemplates(String fileName) { - titanDao.rollback(); + janusGraphDao.rollback(); throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, fileName); } private Object failIfNotTopologyTemplate(String fileName) { - titanDao.rollback(); + janusGraphDao.rollback(); throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, fileName); } private void rollbackWithException(ActionStatus actionStatus, String... params) { - titanDao.rollback(); + janusGraphDao.rollback(); throw new ByActionStatusComponentException(actionStatus, params); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java index 0303b3f5e7..04c4d11679 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java @@ -27,7 +27,7 @@ import org.openecomp.sdc.be.config.ConfigurationManager; 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.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IArtifactOperation; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.common.api.ArtifactTypeEnum; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java index c0a89d6954..00efd80200 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java @@ -31,7 +31,7 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.impl.EsHealthCheckDao; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.switchover.detector.SwitchoverDetector; import org.openecomp.sdc.common.api.HealthCheckInfo; import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; @@ -78,7 +78,7 @@ public class HealthCheckBusinessLogic { private final ScheduledExecutorService healthCheckScheduler = newSingleThreadScheduledExecutor((Runnable r) -> new Thread(r, "BE-Health-Check-Task")); private HealthCheckScheduledTask healthCheckScheduledTask = null; @Resource - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; @Resource private EsHealthCheckDao esHealthCheckDao; @Resource @@ -130,8 +130,8 @@ public class HealthCheckBusinessLogic { // BE getBeHealthCheck(healthCheckInfos); - // Titan - getTitanHealthCheck(healthCheckInfos); + // JanusGraph + getJanusGraphHealthCheck(healthCheckInfos); // ES getEsHealthCheck(healthCheckInfos); @@ -195,25 +195,25 @@ public class HealthCheckBusinessLogic { } - public List getTitanHealthCheck(List healthCheckInfos) { - // Titan health check and version + public List getJanusGraphHealthCheck(List healthCheckInfos) { + // JanusGraph health check and version String description; - boolean isTitanUp; + boolean isJanusGraphUp; try { - isTitanUp = titanGenericDao.isGraphOpen(); + isJanusGraphUp = janusGraphGenericDao.isGraphOpen(); } catch (Exception e) { - description = "Titan error: "; - healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, DOWN, null, description)); + description = "JanusGraph error: "; + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_JANUSGRAPH, DOWN, null, description)); log.error(description, e); return healthCheckInfos; } - if (isTitanUp) { + if (isJanusGraphUp) { description = "OK"; - healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, UP, null, description)); + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_JANUSGRAPH, UP, null, description)); } else { - description = "Titan graph is down"; - healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, DOWN, null, description)); + description = "JanusGraph graph is down"; + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_JANUSGRAPH, DOWN, null, description)); } return healthCheckInfos; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java index 7f6565c88e..19e696c07a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java @@ -25,7 +25,7 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.graph.datatype.AdditionalInformationEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.WebAppContextWrapper; @@ -471,9 +471,9 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { try { - Either findIdRes = additionalInformationOperation.getAllAdditionalInformationParameters(nodeType, resourceId, false); + Either findIdRes = additionalInformationOperation.getAllAdditionalInformationParameters(nodeType, resourceId, false); if (findIdRes.isRight()) { - StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(findIdRes.right().value()); + StorageOperationStatus status = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(findIdRes.right().value()); ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus)); } else { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java index 3cf520d30e..c836e91b9b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java @@ -26,7 +26,7 @@ import fj.data.Either; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.validation.AccessValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -34,8 +34,8 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.catalog.CatalogComponent; -import org.openecomp.sdc.be.model.jsontitan.operations.ArchiveOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArchiveOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; @@ -49,14 +49,14 @@ public class ArchiveBusinessLogic { private static final Logger log = Logger.getLogger(ArchiveBusinessLogic.class.getName()); - private final TitanDao titanDao; + private final JanusGraphDao janusGraphDao; private final AccessValidations accessValidations; private final ArchiveOperation archiveOperation; private final ToscaOperationFacade toscaOperationFacade; private final ComponentsUtils componentUtils; - public ArchiveBusinessLogic(TitanDao titanDao, AccessValidations accessValidations, ArchiveOperation archiveOperation, ToscaOperationFacade tof, ComponentsUtils componentsUtils) { - this.titanDao = titanDao; + public ArchiveBusinessLogic(JanusGraphDao janusGraphDao, AccessValidations accessValidations, ArchiveOperation archiveOperation, ToscaOperationFacade tof, ComponentsUtils componentsUtils) { + this.janusGraphDao = janusGraphDao; this.accessValidations = accessValidations; this.archiveOperation = archiveOperation; this.toscaOperationFacade = tof; @@ -143,7 +143,7 @@ public class ArchiveBusinessLogic { throw e; } finally { - titanDao.commit(); + janusGraphDao.commit(); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java index f23057cad0..dcc6eee01a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java @@ -73,7 +73,7 @@ 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.heat.HeatParameterType; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation; import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; @@ -652,13 +652,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (resultOp == null || resultOp.isRight()) { log.debug(ROLLBACK); if (!inTransaction) { - titanDao.rollback(); + janusGraphDao.rollback(); } } else { log.debug(COMMIT); if (!inTransaction) { - titanDao.commit(); + janusGraphDao.commit(); } } if (shouldLock) { @@ -804,11 +804,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { // unlock resource if (resultOp == null || resultOp.isRight()) { log.debug(ROLLBACK); - titanDao.rollback(); + janusGraphDao.rollback(); } else { log.debug(COMMIT); - titanDao.commit(); + janusGraphDao.commit(); } componentType = component.getComponentType(); @@ -4072,7 +4072,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) { if (!inTransaction) { - titanDao.commit(); + janusGraphDao.commit(); } log.debug("Artifact Saved In ES {}", artifactData.getId()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); @@ -4083,7 +4083,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } else { if (!inTransaction) { - titanDao.rollback(); + janusGraphDao.rollback(); } log.info("Failed to save artifact {}.", artifactData.getId()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); @@ -4228,13 +4228,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (resultOp == null || resultOp.isRight()) { log.debug(ROLLBACK); if (!inTransaction) { - titanDao.rollback(); + janusGraphDao.rollback(); } } else { log.debug(COMMIT); if (!inTransaction) { - titanDao.commit(); + janusGraphDao.commit(); } } if (shouldLock) { 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 c77223ba59..8a4b761a5a 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 @@ -38,9 +38,9 @@ import org.openecomp.sdc.be.components.validation.UserValidations; 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.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; @@ -59,9 +59,9 @@ import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.User; 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.InterfaceOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; @@ -108,10 +108,10 @@ public abstract class BaseBusinessLogic { protected IGraphLockOperation graphLockOperation; @Autowired - protected TitanDao titanDao; + protected JanusGraphDao janusGraphDao; @Autowired - protected TitanGenericDao titanGenericDao; + protected JanusGraphGenericDao janusGraphGenericDao; @Autowired protected IElementOperation elementDao; @@ -283,9 +283,9 @@ public abstract class BaseBusinessLogic { NodeTypeEnum nodeType = componentType.getNodeType(); if (!inTransaction) { if (either == null || either.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); } else { - titanDao.commit(); + janusGraphDao.commit(); } } // unlock resource @@ -339,11 +339,11 @@ public abstract class BaseBusinessLogic { } Either updateInputPropertyObjectValue(T property) { - Either, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll(); if (allDataTypesEither.isRight()) { - TitanOperationStatus status = allDataTypesEither.right().value(); + JanusGraphOperationStatus status = allDataTypesEither.right().value(); BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)))); } Map allDataTypes = allDataTypesEither.left().value(); String propertyType = property.getType(); @@ -356,7 +356,8 @@ public abstract class BaseBusinessLogic { if (isValid.isRight()) { Boolean res = isValid.right().value(); if (Boolean.FALSE.equals(res)) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + JanusGraphOperationStatus.ILLEGAL_ARGUMENT)))); } } else { Object object = isValid.left().value(); @@ -429,15 +430,15 @@ public abstract class BaseBusinessLogic { } // For UT - public void setTitanGenericDao(TitanDao titanDao) { - this.titanDao = titanDao; + public void setJanusGraphGenericDao(JanusGraphDao janusGraphDao) { + this.janusGraphDao = janusGraphDao; } protected Either, ResponseFormat> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) { - Either, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); + Either, JanusGraphOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); if (allDataTypes.isRight()) { - TitanOperationStatus operationStatus = allDataTypes.right().value(); - if (operationStatus == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus operationStatus = allDataTypes.right().value(); + if (operationStatus == JanusGraphOperationStatus.NOT_FOUND) { BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", ErrorSeverity.ERROR); return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY)); } else { @@ -536,10 +537,10 @@ public abstract class BaseBusinessLogic { void commitOrRollback(Either result) { if (result == null || result.isRight()) { log.warn("operation failed. do rollback"); - titanDao.rollback(); + janusGraphDao.rollback(); } else { log.debug("operation success. do commit"); - titanDao.commit(); + janusGraphDao.commit(); } } @@ -587,7 +588,8 @@ public abstract class BaseBusinessLogic { if (isValid.isRight()) { Boolean res = isValid.right().value(); if (Boolean.FALSE.equals(res)) { - throw new StorageException(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + JanusGraphOperationStatus.ILLEGAL_ARGUMENT)); } } else { Object object = isValid.left().value(); @@ -599,7 +601,8 @@ public abstract class BaseBusinessLogic { log.trace("After validateAndUpdateRules. pair = {}", pair); if (Boolean.FALSE.equals(pair.getRight())) { BeEcompErrorManager.getInstance().logBeInvalidValueError(ADD_PROPERTY_VALUE, pair.getLeft(), property.getName(), propertyType); - throw new StorageException(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + JanusGraphOperationStatus.ILLEGAL_ARGUMENT)); } return newValue; } @@ -625,7 +628,7 @@ public abstract class BaseBusinessLogic { private void failOnIllegalArgument() { throw new ByActionStatusComponentException( componentsUtils.convertFromStorageResponse( - DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))); + DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))); } public Either validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map dataTypes) { @@ -712,7 +715,7 @@ public abstract class BaseBusinessLogic { } protected void rollbackWithException(ActionStatus actionStatus, String... params) { - titanDao.rollback(); + janusGraphDao.rollback(); throw new ByActionStatusComponentException(actionStatus, params); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java index f2fd37704d..425458f518 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java @@ -23,7 +23,7 @@ import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.components.validation.CapabilitiesValidation; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -33,8 +33,8 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.CapabilitiesOperation; -import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.CapabilitiesOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; @@ -94,7 +94,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { try { return createCapability(componentId, capabilityDefinitions, storedComponent); } catch (Exception e) { - titanDao.rollback(); + janusGraphDao.rollback(); LOGGER.error(EXCEPTION_OCCURRED_DURING_CAPABILITIES, "addOrUpdate", e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { @@ -151,7 +151,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { result = capabilitiesOperation.addCapabilities(componentId, capabilitiesToReturn); } if (result.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result .right().value(), storedComponent.getComponentType()), "")); } @@ -161,11 +161,11 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { StorageOperationStatus storageOperationStatus = capabilitiesOperation .createOrUpdateCapabilityProperties(componentId, propertiesMap); if (storageOperationStatus != StorageOperationStatus.OK) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(storageOperationStatus)); } } - titanDao.commit(); + janusGraphDao.commit(); return Either.left(capabilitiesToReturn); } @@ -242,7 +242,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { result = capabilitiesOperation.addCapabilities(componentId, capabilitiesToReturn); } if (result.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result .right().value(), storedComponent.getComponentType()), "")); } @@ -252,14 +252,14 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { StorageOperationStatus storageOperationStatus = capabilitiesOperation .createOrUpdateCapabilityProperties(componentId, propertiesMap); if (storageOperationStatus != StorageOperationStatus.OK) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(storageOperationStatus)); } } - titanDao.commit(); + janusGraphDao.commit(); return Either.left(capabilitiesToReturn); } catch (Exception e) { - titanDao.rollback(); + janusGraphDao.rollback(); LOGGER.error(EXCEPTION_OCCURRED_DURING_CAPABILITIES, "addOrUpdate", e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { @@ -292,13 +292,13 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { Either, StorageOperationStatus> deleteCapabilityEither = deleteCapability(storedComponent, storedComponentCapabilities, capabilityDefinitionToDelete); if (deleteCapabilityEither.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(deleteCapabilityEither.right().value())); } StorageOperationStatus deleteStorageOperationStatus = capabilitiesOperation .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete)); if (deleteStorageOperationStatus != StorageOperationStatus.OK) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(deleteStorageOperationStatus)); } capabilitiesToReturn.add(initiateNewCapability(storedComponent, capabilityDefinitionToUpdate)); @@ -334,13 +334,13 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { Either, StorageOperationStatus> deleteCapabilityEither = deleteCapability(storedComponent, storedComponentCapabilities, capabilityDefinitionToDelete); if (deleteCapabilityEither.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(deleteCapabilityEither.right().value())); } StorageOperationStatus deleteStorageOperationStatus = capabilitiesOperation .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete)); if (deleteStorageOperationStatus != StorageOperationStatus.OK) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(deleteStorageOperationStatus)); } } @@ -416,7 +416,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { return deleteCapability(capabilityIdToDelete, storedComponent); } catch (Exception e) { LOGGER.error(EXCEPTION_OCCURRED_DURING_CAPABILITIES, "delete", e); - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND)); } finally { if (lockResult.isLeft() && lockResult.left().value()) { @@ -441,14 +441,14 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { Either, StorageOperationStatus> result = deleteCapability(storedComponent, storedComponentCapabilities, capabilityDefinitionToDeleteEither.left().value()); if (result.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); LOGGER.error("Failed to delete capability from component {}. Response is {}", storedComponent.getName(), result.right().value()); return Either.right(componentsUtils.getResponseFormat( componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()))); } - titanDao.commit(); + janusGraphDao.commit(); return Either.left(capabilityDefinitionToDeleteEither.left().value()); } @@ -528,7 +528,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { if (lockResult.isRight()) { LOGGER.debug(FAILED_TO_LOCK_COMPONENT_RESPONSE_IS, component.getName(), lockResult.right().value().getFormattedMessage()); - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(lockResult.right().value()); } } @@ -584,7 +584,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { StorageOperationStatus deleteStorageOperationStatus = capabilitiesOperation .deleteCapabilityProperties(component, buildCapPropKey(storedCapability)); if (deleteStorageOperationStatus != StorageOperationStatus.OK) { - titanDao.rollback(); + janusGraphDao.rollback(); } } @@ -605,11 +605,11 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { } public Either, ResponseFormat> getAllCapabilityTypes() { - Either, TitanOperationStatus> capabilityTypeCacheAll = + Either, JanusGraphOperationStatus> capabilityTypeCacheAll = capabilityTypeOperation.getAllCapabilityTypes(); if (capabilityTypeCacheAll.isRight()) { - TitanOperationStatus operationStatus = capabilityTypeCacheAll.right().value(); - if (TitanOperationStatus.NOT_FOUND == operationStatus) { + JanusGraphOperationStatus operationStatus = capabilityTypeCacheAll.right().value(); + if (JanusGraphOperationStatus.NOT_FOUND == operationStatus) { BeEcompErrorManager.getInstance().logInternalDataError("FetchCapabilityTypes", "Capability types are not loaded", BeEcompErrorManager.ErrorSeverity.ERROR); return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY)); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java index bc5f77ba1b..c77877fac4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java @@ -68,20 +68,21 @@ public class CassandraHealthCheck { sdcKeyspaces.add(table.getTableDescription().getKeyspace()); } - String titanCfgFile = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanCfgFile(); + String janusGraphCfgFile = ConfigurationManager.getConfigurationManager() + .getConfiguration().getJanusGraphCfgFile(); Properties prop = new Properties(); - InputStream titanProp = null; + InputStream janusGraphProp = null; try { //load a properties file - titanProp = new FileInputStream(titanCfgFile); - prop.load(titanProp); - //Add titan keyspace - String titanKeyspace = prop.getProperty("storage.cassandra.keyspace"); - if (!GeneralUtility.isEmptyString(titanKeyspace)) { - sdcKeyspaces.add(titanKeyspace); + janusGraphProp = new FileInputStream(janusGraphCfgFile); + prop.load(janusGraphProp); + //Add janusgraph keyspace + String janusGraphKeyspace = prop.getProperty("storage.cassandra.keyspace"); + if (!GeneralUtility.isEmptyString(janusGraphKeyspace)) { + sdcKeyspaces.add(janusGraphKeyspace); } } catch (Exception e) { - log.error("Failed to open titen.properties file , url is : {}", titanCfgFile, e); + log.error("Failed to open titen.properties file , url is : {}", janusGraphCfgFile, e); } log.info("All sdc keyspaces are : {}", sdcKeyspaces); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java index d2f845cc00..1de92e2e15 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java @@ -237,17 +237,17 @@ public class CommonImportManager { typeOperations.addType(newTypeDefinition); } else { if (typeOperations.isSameType(newTypeDefinition, existingDefinition)) { - propertyOperation.getTitanGenericDao().rollback(); + propertyOperation.getJanusGraphGenericDao().rollback(); createdElementTypes.add(new ImmutablePair<>(newTypeDefinition, null)); continue; } else { typeOperations.updateType(existingDefinition, newTypeDefinition); } } - propertyOperation.getTitanGenericDao().commit(); + propertyOperation.getJanusGraphGenericDao().commit(); createdElementTypes.add(new ImmutablePair<>(newTypeDefinition, true)); } catch (Exception e) { - propertyOperation.getTitanGenericDao().rollback(); + propertyOperation.getJanusGraphGenericDao().rollback(); createdElementTypes.add(new ImmutablePair<>(newTypeDefinition, false)); } @@ -287,10 +287,10 @@ public class CommonImportManager { } finally { if (eitherResult.isLeft()) { - propertyOperation.getTitanGenericDao().commit(); + propertyOperation.getJanusGraphGenericDao().commit(); } else { - propertyOperation.getTitanGenericDao().rollback(); + propertyOperation.getJanusGraphGenericDao().rollback(); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java index dcd0c7b7f0..18d8688036 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java @@ -561,7 +561,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return Either.left(result); } finally{ - titanDao.commit(); + janusGraphDao.commit(); } } @@ -596,7 +596,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())); } finally { - titanDao.commit(); + janusGraphDao.commit(); } return Either.right(responseFormat); } @@ -771,12 +771,12 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { if ( deleteMarkedElements.isRight()){ - titanDao.rollback(); + janusGraphDao.rollback(); ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType)); return Either.right(responseFormat); } log.trace("end deleteMarkedComponents"); - titanDao.commit(); + janusGraphDao.commit(); return Either.left(deleteMarkedElements.left().value()); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java index 71b125737e..eebbb0a2bf 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java @@ -37,7 +37,7 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datamodel.utils.PropertyValueConstraintValidationUtil; import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; @@ -76,10 +76,10 @@ import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeFilterOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ForwardingPathOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; @@ -1042,13 +1042,13 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (deleteServiceFilterEither.isRight()) { ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType); - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(status, componentInstanceId)); } resultOp = deleteServiceFiltersRelatedTobeDeletedComponentInstance((Service) containerComponent, componentInstance, ComponentTypeEnum.SERVICE, userId); if (resultOp.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return resultOp; } } @@ -1672,9 +1672,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { finally { if (result == null || result.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); } else { - titanDao.commit(); + janusGraphDao.commit(); } // unlock resource graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); @@ -1800,9 +1800,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } finally { if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); } else { - titanDao.commit(); + janusGraphDao.commit(); } // unlock resource graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); @@ -1926,11 +1926,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } private Either updatePropertyObjectValue(T property, boolean isInput) { - Either, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll(); if (allDataTypesEither.isRight()) { - TitanOperationStatus status = allDataTypesEither.right().value(); + JanusGraphOperationStatus status = allDataTypesEither.right().value(); BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)))); } Map allDataTypes = allDataTypesEither.left().value(); String innerType = null; @@ -1957,7 +1957,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (isValid.isRight()) { Boolean res = isValid.right().value(); if (!res) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)))); } } else { Object object = isValid.left().value(); @@ -1969,7 +1969,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { ImmutablePair pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true); if (pair.getRight() != null && pair.getRight() == false) { BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)))); } } return Either.left(newValue); @@ -2052,9 +2052,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } finally { if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); } else { - titanDao.commit(); + janusGraphDao.commit(); } // unlock resource graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); @@ -2147,9 +2147,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } finally { if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); } else { - titanDao.commit(); + janusGraphDao.commit(); } // unlock resource graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); @@ -2236,9 +2236,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } finally { if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); } else { - titanDao.commit(); + janusGraphDao.commit(); } // unlock resource graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); @@ -2292,9 +2292,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } finally { if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); } else { - titanDao.commit(); + janusGraphDao.commit(); } // unlock resource graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType()); @@ -2894,11 +2894,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); } - Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); + JanusGraphOperationStatus status = allDataTypes.right().value(); BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)))); } try { @@ -2920,9 +2920,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } finally { if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); } else { - titanDao.commit(); + janusGraphDao.commit(); } // unlock resource graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType()); @@ -2982,9 +2982,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } finally { if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); } else { - titanDao.commit(); + janusGraphDao.commit(); } // unlock resource graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType()); @@ -3028,7 +3028,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { // on failure of the create instance unlock the resource and rollback the transaction. if (null == actionResponse || actionResponse.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); } unlockComponent(actionResponse, origComponent); } @@ -3053,10 +3053,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } finally { if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); } else { - titanDao.commit(); + janusGraphDao.commit(); log.debug("Success trasaction commit"); } // unlock resource diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java index 3ddfe4bfc4..a1a6555630 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java @@ -3,7 +3,7 @@ package org.openecomp.sdc.be.components.impl; import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; @@ -22,10 +22,10 @@ public class DataTypesService { } public Either, ResponseFormat> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) { - Either, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); + Either, JanusGraphOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); if (allDataTypes.isRight()) { - TitanOperationStatus operationStatus = allDataTypes.right().value(); - if (operationStatus == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus operationStatus = allDataTypes.right().value(); + if (operationStatus == JanusGraphOperationStatus.NOT_FOUND) { BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", BeEcompErrorManager.ErrorSeverity.ERROR); return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY)); } else { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java index 746f4e9c27..91d7fa6034 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java @@ -32,10 +32,10 @@ import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; 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.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum; import org.openecomp.sdc.be.datamodel.utils.NodeTypeConvertUtils; import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; @@ -250,7 +250,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resources.right().value()))); } } finally { - titanDao.commit(); + janusGraphDao.commit(); } } @@ -999,7 +999,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { .bimap(this::groupByComponentType, err -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(err))); } finally { - titanDao.commit(); + janusGraphDao.commit(); } } @@ -1229,10 +1229,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } CategoryData categoryData = categoryResult.left().value(); - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(), + Either>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao + .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.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childrenNodes.right().value())); } return Either.left(childrenNodes.left().value()); } @@ -1248,7 +1249,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return collectComponents(neededType, categoryUid, categoryType, clazz, resourceType); } finally { if (!inTransaction) { - titanDao.commit(); + janusGraphDao.commit(); } } } @@ -1260,7 +1261,8 @@ public class ElementBusinessLogic extends BaseBusinessLogic { 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); + Either, JanusGraphOperationStatus> getCategory = janusGraphGenericDao + .getByCriteria(categoryType, props, categoryClazz); if (getCategory.isRight()) { return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); } @@ -1275,7 +1277,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.left(components); } finally { if (!inTransaction) { - titanDao.commit(); + janusGraphDao.commit(); } } } @@ -1283,7 +1285,8 @@ public class ElementBusinessLogic extends BaseBusinessLogic { private Either, StorageOperationStatus> collectComponents(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); + Either>, JanusGraphOperationStatus> parentNodes = janusGraphGenericDao + .getParentNodes(UniqueIdBuilder.getKeyByNodeType(categoryType), categoryUid, GraphEdgeLabels.CATEGORY, neededType, clazz); if (parentNodes.isLeft()) { for (ImmutablePair component : parentNodes.left().value()) { ComponentMetadataDataDefinition componentData = component.getLeft().getMetadataDataDefinition(); @@ -1359,7 +1362,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return result; } finally { if (!inTransaction) { - titanDao.commit(); + janusGraphDao.commit(); } } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java index 0b53da0018..d3037a9e53 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java @@ -8,8 +8,8 @@ import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.dto.ExternalRefDTO; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.jsontitan.operations.ExternalReferencesOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ExternalReferencesOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java index 9bab155cdf..7c5a596319 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java @@ -41,7 +41,7 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; @@ -54,8 +54,8 @@ import org.openecomp.sdc.be.info.GroupDefinitionInfo; import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.PropertyDefinition.GroupInstancePropertyValueUpdateBehavior; import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames; -import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; @@ -71,8 +71,8 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; -import static org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter.extractCapabilitiesFromGroups; -import static org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter.extractCapabilityPropertiesFromGroups; +import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilitiesFromGroups; +import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilityPropertiesFromGroups; @org.springframework.stereotype.Component("groupBusinessLogic") public class GroupBusinessLogic extends BaseBusinessLogic { @@ -247,9 +247,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } finally { if (result != null && result.isLeft()) { - titanDao.commit(); + janusGraphDao.commit(); } else { - titanDao.rollback(); + janusGraphDao.rollback(); } if (shouldLock) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); @@ -488,10 +488,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); - titanDao.rollback(); + janusGraphDao.rollback(); } else { log.debug("Going to execute commit on create group."); - titanDao.commit(); + janusGraphDao.commit(); } } @@ -718,10 +718,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); - titanDao.rollback(); + janusGraphDao.rollback(); } else { log.debug("Going to execute commit on create group."); - titanDao.commit(); + janusGraphDao.commit(); } } @@ -1109,12 +1109,12 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } private List onFailedGroupDBOperation(ResponseFormat responseFormat) { - titanDao.rollback(); + janusGraphDao.rollback(); throw new ByResponseFormatComponentException(responseFormat); } private GroupDefinition onFailedUpdateGroupDBOperation(ResponseFormat responseFormat) { - titanDao.rollback(); + janusGraphDao.rollback(); throw new ByResponseFormatComponentException(responseFormat); } @@ -1132,7 +1132,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { log.debug("#updatePolicyTargetReferencingDeletedGroup - removing all component {} policy targets referencing group {}", component.getUniqueId(), groupId); ActionStatus actionStatus = policyTargetsUpdateHandler.removePoliciesTargets(component, groupId, PolicyTargetType.GROUPS); if (ActionStatus.OK != actionStatus) { - titanDao.rollback(); + janusGraphDao.rollback(); throw new ByActionStatusComponentException(actionStatus, groupId); } } @@ -1143,11 +1143,11 @@ public class GroupBusinessLogic extends BaseBusinessLogic { Map groups = new HashMap<>(); Either, ResponseFormat> result = null; Either, StorageOperationStatus> createGroupsResult = null; - Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); + JanusGraphOperationStatus status = allDataTypes.right().value(); BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)))); } @@ -1213,11 +1213,11 @@ public class GroupBusinessLogic extends BaseBusinessLogic { Either, StorageOperationStatus> createGroupsResult = null; List groups = new ArrayList<>(); - Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); + JanusGraphOperationStatus status = allDataTypes.right().value(); BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)))); } @@ -1331,18 +1331,18 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (CollectionUtils.isNotEmpty(properties)) { if (CollectionUtils.isEmpty(groupTypeProperties)) { BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.MATCH_NOT_FOUND)))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.MATCH_NOT_FOUND)))); } Map groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(PropertyDefinition::getName, p -> p)); - Either addPropertyResult; + Either addPropertyResult; int i = 1; for (GroupProperty prop : properties) { addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes, groupType); if (addPropertyResult.isRight()) { BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "failed to validate property", ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyResult.right().value())))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertyResult.right().value())))); } updatedGroupTypeProperties.add(addPropertyResult.left().value()); @@ -1372,18 +1372,18 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return found; } - private Either handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map allDataTypes, String groupType) { + private Either handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map allDataTypes, String groupType) { if (prop == null) { - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT); } String propertyType = prop.getType(); String value = groupProperty.getValue(); - Either checkInnerType = propertyOperation.checkInnerType(prop); + Either checkInnerType = propertyOperation.checkInnerType(prop); if (checkInnerType.isRight()) { - TitanOperationStatus status = checkInnerType.right().value(); + JanusGraphOperationStatus status = checkInnerType.right().value(); return Either.right(status); } @@ -1397,7 +1397,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (isValid.isRight()) { Boolean res = isValid.right().value(); if (!res) { - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT); } } else { Object object = isValid.left().value(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java index b234bb6bd6..5a5e941c24 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java @@ -34,7 +34,7 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.GroupOperation; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java index 5bc0e5e3c3..80d6d65a06 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java @@ -26,7 +26,7 @@ import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentEx import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.GroupTypeDefinition; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -43,13 +43,13 @@ import static java.util.Collections.emptySet; public class GroupTypeBusinessLogic { private final GroupTypeOperation groupTypeOperation; - private final TitanDao titanDao; + private final JanusGraphDao janusGraphDao; private final UserValidations userValidations; private final ComponentsUtils componentsUtils; - public GroupTypeBusinessLogic(GroupTypeOperation groupTypeOperation, TitanDao titanDao, UserValidations userValidations, ComponentsUtils componentsUtils) { + public GroupTypeBusinessLogic(GroupTypeOperation groupTypeOperation, JanusGraphDao janusGraphDao, UserValidations userValidations, ComponentsUtils componentsUtils) { this.groupTypeOperation = groupTypeOperation; - this.titanDao = titanDao; + this.janusGraphDao = janusGraphDao; this.userValidations = userValidations; this.componentsUtils = componentsUtils; } @@ -61,7 +61,7 @@ public class GroupTypeBusinessLogic { Set excludeGroupTypes = getExcludedGroupTypes(internalComponentType); return groupTypeOperation.getAllGroupTypes(excludeGroupTypes); } finally { - titanDao.commit(); + janusGraphDao.commit(); } } @@ -81,7 +81,7 @@ public class GroupTypeBusinessLogic { } private GroupTypeDefinition failOnGetGroupType(StorageOperationStatus status, String groupType) { - titanDao.rollback(); + janusGraphDao.rollback(); if (status == StorageOperationStatus.NOT_FOUND) { throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_IS_INVALID, groupType); } else { 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 4a7b080fbc..0be6ed9c3a 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 @@ -31,7 +31,7 @@ import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.ComponentInstanceProperty; 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.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation; import org.openecomp.sdc.be.model.utils.TypeCompareUtils; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java index 0936472bb7..8aec0cdfe2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java @@ -43,7 +43,7 @@ import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.components.property.PropertyDeclarationOrchestrator; import org.openecomp.sdc.be.components.validation.ComponentValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.datamodel.utils.PropertyValueConstraintValidationUtil; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; @@ -241,7 +241,8 @@ public class InputsBusinessLogic extends BaseBusinessLogic { if (isValid.isRight()) { Boolean res = isValid.right().value(); if (Boolean.FALSE.equals(res)) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + JanusGraphOperationStatus.ILLEGAL_ARGUMENT)))); } } else { Object object = isValid.left().value(); @@ -342,10 +343,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic { if (!inTransaction) { if (result == null || result.isRight()) { log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP); - titanDao.rollback(); + janusGraphDao.rollback(); } else { log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP); - titanDao.commit(); + janusGraphDao.commit(); } } // unlock resource @@ -442,10 +443,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic { if (!inTransaction) { if (result == null || result.isRight()) { log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP); - titanDao.rollback(); + janusGraphDao.rollback(); } else { log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP); - titanDao.commit(); + janusGraphDao.commit(); } } // unlock resource @@ -529,10 +530,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic { if (!inTransaction) { if (result == null || result.isRight()) { log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP); - titanDao.rollback(); + janusGraphDao.rollback(); } else { log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP); - titanDao.commit(); + janusGraphDao.commit(); } } // unlock resource @@ -771,10 +772,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } finally { if (deleteEither == null || deleteEither.isRight()) { log.debug("Component id: {} delete input id: {} failed", componentId, inputId); - titanDao.rollback(); + janusGraphDao.rollback(); } else { log.debug("Component id: {} delete input id: {} success", componentId, inputId); - titanDao.commit(); + janusGraphDao.commit(); } unlockComponent(deleteEither, component); } @@ -882,10 +883,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic { if (result == null || result.isRight()) { log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP); - titanDao.rollback(); + janusGraphDao.rollback(); } else { log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP); - titanDao.commit(); + janusGraphDao.commit(); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java index 5cdaa6a590..7815b81755 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java @@ -139,7 +139,7 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()), true); if(removeArifactFromComponent.isRight()){ - titanDao.rollback(); + janusGraphDao.rollback(); ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId( componentsUtils.convertFromStorageResponse(removeArifactFromComponent.right().value()), storedOperation.getImplementation().getArtifactDisplayName()); @@ -148,7 +148,7 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(artifactUniqueId); if (cassandraStatus != CassandraOperationStatus.OK) { - titanDao.rollback(); + janusGraphDao.rollback(); ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId( componentsUtils.convertFromStorageResponse( componentsUtils.convertToStorageOperationStatus(cassandraStatus)), @@ -166,7 +166,7 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(interfaceDefinition)); if (deleteOperationEither.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( deleteOperationEither.right().value(), storedComponent.getComponentType()))); } @@ -175,19 +175,19 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { Either deleteInterfaceEither = interfaceOperation.deleteInterface( storedComponent.getUniqueId(), interfaceDefinition.getUniqueId()); if (deleteInterfaceEither.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( deleteInterfaceEither.right().value(), storedComponent.getComponentType()))); } } - titanDao.commit(); + janusGraphDao.commit(); interfaceDefinition.getOperations().putAll(operationsCollection); interfaceDefinition.getOperations().keySet().removeIf(key -> !(operationsToDelete.contains(key))); return Either.left(Collections.singletonList(interfaceDefinition)); } catch (Exception e) { LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "delete", e); - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_DELETED)); } finally { if (lockResult.isLeft() && lockResult.left().value()) { @@ -212,7 +212,7 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { if (lock) { Either lockResult = lockComponent(component.getUniqueId(), component, action); if (lockResult.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(lockResult.right().value()); } } @@ -253,12 +253,12 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { } } - titanDao.commit(); + janusGraphDao.commit(); interfaceDefinition.getOperations().keySet().removeIf(key -> !(operationsToGet.contains(key))); return Either.left(Collections.singletonList(interfaceDefinition)); } catch (Exception e) { LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "get", e); - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right( componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId)); } finally { @@ -335,7 +335,7 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { getOperationFromInterfaceDefinition(interfaceDef, operation.getUniqueId()); if (!optionalOperation.isPresent()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils .getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, storedComponent.getUniqueId())); @@ -354,7 +354,7 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()), true); if(removeArifactFromComponent.isRight()){ - titanDao.rollback(); + janusGraphDao.rollback(); ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId( componentsUtils.convertFromStorageResponse(removeArifactFromComponent.right().value()), storedOperation.getImplementation().getArtifactDisplayName()); @@ -363,7 +363,7 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(artifactUniqueId); if (cassandraStatus != CassandraOperationStatus.OK) { - titanDao.rollback(); + janusGraphDao.rollback(); ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId( componentsUtils.convertFromStorageResponse( @@ -383,18 +383,18 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { Either, StorageOperationStatus> addCreateOperationEither = interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), interfacesCollection); if (addCreateOperationEither.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( addCreateOperationEither.right().value(), storedComponent.getComponentType()))); } - titanDao.commit(); + janusGraphDao.commit(); interfacesCollection.forEach(interfaceDefinition -> interfaceDefinition.getOperations().entrySet().removeIf( entry -> !operationsCollection.values().stream().map(OperationDataDefinition::getName) .collect(Collectors.toList()).contains(entry.getValue().getName()))); return Either.left(interfacesCollection); } catch (Exception e) { - titanDao.rollback(); + janusGraphDao.rollback(); LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "addOrUpdate", e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { @@ -431,7 +431,7 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { interfaceOperation.addInterfaces(component.getUniqueId(), Collections.singletonList(interfaceDefinition)); if (interfaceCreateEither.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( interfaceCreateEither.right().value(), component.getComponentType()))); } @@ -580,7 +580,7 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { } catch (Exception e) { LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "get", e); - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND)); } finally { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java index 752ec4098a..54b7d2ea02 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java @@ -398,7 +398,7 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { .left() .bind(cmpt -> getPolicyById(cmpt, policyId)).left().map(PolicyDataDefinition::getProperties); } finally { - titanDao.commit(); + janusGraphDao.commit(); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java index cb4b6ff58c..a59156cd87 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java @@ -4,7 +4,7 @@ import fj.data.Either; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.PolicyTypeDefinition; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -25,13 +25,13 @@ public class PolicyTypeBusinessLogic { private static final Logger log = Logger.getLogger(PolicyTypeBusinessLogic.class); private PolicyTypeOperation policyTypeOperation; - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; private ComponentsUtils componentsUtils; private UserValidations userValidations; - public PolicyTypeBusinessLogic(PolicyTypeOperation policyTypeOperation, TitanDao titanDao, ComponentsUtils componentsUtils, UserValidations userValidations) { + public PolicyTypeBusinessLogic(PolicyTypeOperation policyTypeOperation, JanusGraphDao janusGraphDao, ComponentsUtils componentsUtils, UserValidations userValidations) { this.policyTypeOperation = policyTypeOperation; - this.titanDao = titanDao; + this.janusGraphDao = janusGraphDao; this.componentsUtils = componentsUtils; this.userValidations = userValidations; } 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 edd3b936a2..d0dc9fe7c0 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 @@ -29,7 +29,7 @@ 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.PolicyTypeDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; 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.IPolicyTypeOperation; 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 30a9f799fe..ff532b237d 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 @@ -232,7 +232,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { validateUserExists(userId, "validate Product Name Exists", false); Either dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT); // DE242223 - titanDao.commit(); + janusGraphDao.commit(); if (dataModelResponse.isLeft()) { Map result = new HashMap<>(); @@ -378,7 +378,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { for (Map.Entry>> entry : nonDuplicatedCategories.entrySet()) { catExist = false; CategoryDefinition categoryDefinition = null; - // over all categories from Titan + // over all categories from JanusGraph List categoriesList = allProductCategories.left().value(); if (categoriesList != null) { for (CategoryDefinition catInDb : categoriesList) { @@ -415,7 +415,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { } if (!groupExist) { // error grouping isn't defined - // in Titan + // in JanusGraph ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.GROUPING.getValue(), group); componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); return Either.right(responseFormat); @@ -426,7 +426,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { } } if (!subcatExist) { - // error sub category isn't defined in Titan + // error sub category isn't defined in JanusGraph ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.SUBCATEGORY.getValue(), subcat.getKey()); componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); return Either.right(responseFormat); @@ -437,7 +437,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { } } if (!catExist) { - // error category isn't defined in Titan + // error category isn't defined in JanusGraph ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.CATEGORY.getValue(), entry.getKey()); componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); return Either.right(responseFormat); 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 275d1726ed..f3a40ad9f7 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 @@ -34,7 +34,7 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; import org.openecomp.sdc.be.datatypes.elements.OperationInputDefinition; @@ -489,7 +489,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { } String innerType; - Either checkInnerType = getInnerType(type, propertyDefinition::getSchema); + Either checkInnerType = getInnerType(type, propertyDefinition::getSchema); if (checkInnerType.isRight()) { return StorageOperationStatus.INVALID_TYPE; } @@ -551,19 +551,19 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { return jsonElement.toString(); } - private Either getInnerType(ToscaPropertyType type, Supplier schemeGen) { + private Either getInnerType(ToscaPropertyType type, Supplier schemeGen) { String innerType = null; if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { SchemaDefinition def = schemeGen.get(); if (def == null) { log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + return Either.right(JanusGraphOperationStatus.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); + return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT); } innerType = propDef.getType(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java index 4a909785b2..695d82f5d9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java @@ -21,7 +21,7 @@ import java.util.Map; import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.RelationshipTypeDefinition; import org.openecomp.sdc.be.model.operations.impl.RelationshipTypeOperation; @@ -39,11 +39,11 @@ public class RelationshipTypeBusinessLogic { protected ComponentsUtils componentsUtils; public Either, ResponseFormat> getAllRelationshipTypes() { - Either, TitanOperationStatus> allRelationshipTypes = + Either, JanusGraphOperationStatus> allRelationshipTypes = relationshipTypeOperation.getAllRelationshipTypes(); if (allRelationshipTypes.isRight()) { - TitanOperationStatus operationStatus = allRelationshipTypes.right().value(); - if (TitanOperationStatus.NOT_FOUND == operationStatus) { + JanusGraphOperationStatus operationStatus = allRelationshipTypes.right().value(); + if (JanusGraphOperationStatus.NOT_FOUND == operationStatus) { BeEcompErrorManager.getInstance().logInternalDataError("FetchRelationshipTypes", "Relationship types " + "are " + "not loaded", diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java index 18671f8caf..19dd0f41a3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java @@ -68,7 +68,7 @@ public class RelationshipTypeImportManager { return commonImportManager.createElementTypesByDao(relationshipTypesToCreate, this::validateRelationshipType, relationshipType -> new ImmutablePair<>(ElementTypeEnum.RELATIONSHIP_TYPE, relationshipType.getType()), relationshipTypeName -> relationshipTypeOperation.getRelationshipTypeByName(relationshipTypeName) - .right().map(DaoStatusConverter::convertTitanStatusToStorageStatus), + .right().map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus), relationshipType -> relationshipTypeOperation.addRelationshipType(relationshipType, inTransaction), (newRelationshipType, oldRelationshipType) -> relationshipTypeOperation .updateRelationshipType(newRelationshipType, oldRelationshipType, inTransaction)); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java index c07a9fc09f..c2d9c95cf7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java @@ -25,7 +25,7 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.RequirementOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.RequirementOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; @@ -120,15 +120,15 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { result = requirementOperation.addRequirement(componentId, requirementsToReturn); } if (result.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat( componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()), "")); } - titanDao.commit(); + janusGraphDao.commit(); return Either.left(requirementsToReturn); } catch (Exception e) { - titanDao.rollback(); + janusGraphDao.rollback(); LOGGER.error(EXCEPTION_OCCURRED_DURING_REQUIREMENTS, "addOrUpdate", e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { @@ -222,15 +222,15 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { result = requirementOperation.addRequirement(componentId, requirementsToReturn); } if (result.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat( componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()), "")); } - titanDao.commit(); + janusGraphDao.commit(); return Either.left(requirementsToReturn); } catch (Exception e) { - titanDao.rollback(); + janusGraphDao.rollback(); LOGGER.error(EXCEPTION_OCCURRED_DURING_REQUIREMENTS, "addOrUpdate", e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { @@ -263,7 +263,7 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { Either, StorageOperationStatus> deleteRequirementEither = deleteRequirement(storedComponent, storedComponentRequirements, requirementDefinitionToDelete); if (deleteRequirementEither.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(deleteRequirementEither.right().value())); } requirementsToReturn.add(initiateNewRequirement(storedComponent, requirementDefinitionToUpdate)); @@ -300,7 +300,7 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { Either, StorageOperationStatus> deleteRequirementEither = deleteRequirement(storedComponent, storedComponentRequirements, requirementDefinitionToDelete); if (deleteRequirementEither.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(deleteRequirementEither.right().value())); } } @@ -392,17 +392,17 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { Either, StorageOperationStatus> result = deleteRequirement(storedComponent, storedComponentRequirements, requirementDefinitionToDelete); if (result.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); LOGGER.error("Failed to delete requirement from component {}. Response is {}", storedComponent.getName(), result.right().value()); return Either.right(componentsUtils.getResponseFormat(componentsUtils .convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()))); } - titanDao.commit(); + janusGraphDao.commit(); return Either.left(requirementDefinitionToDelete); } catch (Exception e) { LOGGER.error(EXCEPTION_OCCURRED_DURING_REQUIREMENTS, "delete", e); - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND)); } finally { if (lockResult.isLeft() && lockResult.left().value()) { @@ -462,7 +462,7 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { if (lockResult.isRight()) { LOGGER.debug(FAILED_TO_LOCK_COMPONENT_RESPONSE_IS, component.getName(), lockResult.right().value().getFormattedMessage()); - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(lockResult.right().value()); } } 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 0968e157e4..1fa9051a9a 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 @@ -75,7 +75,7 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum; import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils; import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; @@ -127,7 +127,7 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation; @@ -321,7 +321,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Either dataModelResponse = toscaOperationFacade .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE); // DE242223 - titanDao.commit(); + janusGraphDao.commit(); if (dataModelResponse.isLeft()) { Map result = new HashMap<>(); @@ -487,7 +487,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { throw e; } finally { - titanDao.commit(); + janusGraphDao.commit(); log.debug("unlock resource {}", lockedResourceId); graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); } @@ -1420,7 +1420,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { throw e; } finally { if (!inTransaction) { - titanDao.commit(); + janusGraphDao.commit(); } if (shouldLock) { graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), @@ -1431,7 +1431,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { private void rollback(boolean inTransaction, Resource resource, List createdArtifacts, List nodeTypesNewCreatedArtifacts) { if(!inTransaction) { - titanDao.rollback(); + janusGraphDao.rollback(); } if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) { createdArtifacts.addAll(nodeTypesNewCreatedArtifacts); @@ -2181,13 +2181,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Map> instInputs = new HashMap<>(); log.debug("#createResourceInstancesRelations - Before get all datatypes. "); - Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); + JanusGraphOperationStatus status = allDataTypes.right().value(); BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( - DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName)); + DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName)); } Resource finalResource = resource; @@ -2369,7 +2369,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } - private void processComponentInstance(String yamlName, Resource resource, List componentInstancesList, Either, TitanOperationStatus> allDataTypes, Map> instProperties, Map>> instCapabilties, Map>> instRequirements, Map> instDeploymentArtifacts, Map> instArtifacts, Map> instAttributes, Map originCompMap, Map> instInputs, UploadComponentInstanceInfo uploadComponentInstanceInfo) { + private void processComponentInstance(String yamlName, Resource resource, List componentInstancesList, Either, JanusGraphOperationStatus> allDataTypes, Map> instProperties, Map>> instCapabilties, Map>> instRequirements, Map> instDeploymentArtifacts, Map> instArtifacts, Map> instAttributes, Map originCompMap, Map> instInputs, UploadComponentInstanceInfo uploadComponentInstanceInfo) { Optional currentCompInstanceOpt = componentInstancesList.stream() .filter(i->i.getName().equals(uploadComponentInstanceInfo.getName())) .findFirst(); @@ -2435,7 +2435,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return originResource; } - private void processComponentInstanceCapabilities(Either, TitanOperationStatus> allDataTypes, Map>> instCapabilties, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, Resource originResource) { + private void processComponentInstanceCapabilities(Either, JanusGraphOperationStatus> allDataTypes, Map>> instCapabilties, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, Resource originResource) { Map> originCapabilities; if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) { originCapabilities = new HashMap<>(); @@ -2449,7 +2449,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { instCapabilties.put(currentCompInstance, originCapabilities); } - private void updateCapabilityPropertiesValues(Either, TitanOperationStatus> allDataTypes, Map> originCapabilities, Map> newPropertiesMap) { + private void updateCapabilityPropertiesValues(Either, JanusGraphOperationStatus> allDataTypes, Map> originCapabilities, Map> newPropertiesMap) { originCapabilities.values().stream() .flatMap(Collection::stream) .filter(c -> newPropertiesMap.containsKey(c.getName())) @@ -3240,10 +3240,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (result == null || result.isRight()) { BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); if (!inTransaction) { - titanDao.rollback(); + janusGraphDao.rollback(); } } else if (!inTransaction) { - titanDao.commit(); + janusGraphDao.commit(); } } } @@ -3429,9 +3429,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } finally { if (resourcePair == null) { BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); - titanDao.rollback(); + janusGraphDao.rollback(); } else if (!inTransaction) { - titanDao.commit(); + janusGraphDao.commit(); } if (needLock) { log.debug("unlock resource {}", lockedResourceId); @@ -3919,9 +3919,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } finally { if (result == null || !result.equals(StorageOperationStatus.OK)) { - titanDao.rollback(); + janusGraphDao.rollback(); } else { - titanDao.commit(); + janusGraphDao.commit(); } graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); } @@ -3947,11 +3947,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } finally { if (result == null || !result.equals(StorageOperationStatus.OK)) { - titanDao.rollback(); + janusGraphDao.rollback(); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName); } else { - titanDao.commit(); + janusGraphDao.commit(); } } if (resource != null) { @@ -3971,9 +3971,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } finally { if (result == null || !result.equals(StorageOperationStatus.OK)) { - titanDao.rollback(); + janusGraphDao.rollback(); } else { - titanDao.commit(); + janusGraphDao.commit(); } graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource); } @@ -4097,7 +4097,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } finally { if (!inTransaction) { - titanDao.commit(); + janusGraphDao.commit(); } if (needToUnlock) { graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource); @@ -4643,7 +4643,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Either, ActionStatus> categories = elementDao .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction); if (categories.isRight()) { - log.debug("failed to retrieve resource categories from Titan"); + log.debug("failed to retrieve resource categories from JanusGraph"); responseFormat = componentsUtils.getResponseFormat(categories.right().value()); componentsUtils.auditResource(responseFormat, user, resource, actionEnum); throw new ByActionStatusComponentException(categories.right().value()); @@ -4830,7 +4830,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (deleteArtifactByInterface.isRight()) { log.debug("Couldn't remove artifact definition with id {}", uniqueId); if (!inTransaction) { - titanDao.rollback(); + janusGraphDao.rollback(); } return Either.right(deleteArtifactByInterface.right().value()); } @@ -4852,7 +4852,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) { log.debug("Failed to remove all properties of resource"); if (!inTransaction) { - titanDao.rollback(); + janusGraphDao.rollback(); } return Either.right(componentsUtils.getResponseFormat( componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value()))); @@ -4865,7 +4865,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (inTransaction) { return Either.left(true); } - titanDao.commit(); + janusGraphDao.commit(); return Either.left(true); } 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 cd9be0fe72..dbb421b6a0 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 @@ -46,7 +46,7 @@ import org.openecomp.sdc.be.impl.WebAppContextWrapper; 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.jsonjanusgraph.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; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java index 6c41985c9a..2c0af5fec5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java @@ -117,9 +117,9 @@ 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.jsontitan.operations.ForwardingPathOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeFilterOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ForwardingPathOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.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; @@ -236,14 +236,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } Either result = toscaOperationFacade.updateDistributionStatus(service, user, newState); if (result.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); BeEcompErrorManager.getInstance().logBeSystemError("ChangeServiceDistributionState"); log.debug("service {} is change destribuation status failed", service.getUniqueId()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, service.getVersion(), service.getName()); createAudit(user, auditAction, comment, service, responseFormat); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } - titanDao.commit(); + janusGraphDao.commit(); Service updatedService = result.left().value(); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); log.debug(AUDIT_BEFORE_SENDING_RESPONSE); @@ -322,10 +322,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { operationList.add(operationEither.left().value()); } - titanDao.commit(); + janusGraphDao.commit(); return Either.left(operationList); } catch (Exception e) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { @@ -1013,7 +1013,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { Either dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE); // DE242223 - titanDao.commit(); + janusGraphDao.commit(); if (dataModelResponse.isLeft()) { Map result = new HashMap<>(); @@ -1073,12 +1073,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { try { Either updateResponse = toscaOperationFacade.updateToscaElement(serviceToUpdate); if (updateResponse.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata"); log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } - titanDao.commit(); + janusGraphDao.commit(); return Either.left(updateResponse.left().value()); } finally { graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); @@ -1099,7 +1099,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (lock) { Either lockResult = lockComponent(service.getUniqueId(), service, "Delete Forwarding Path on Service"); if (lockResult.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(componentsUtils .convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); } @@ -1108,15 +1108,15 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { result = forwardingPathOperation.deleteForwardingPath(service ,pathIdsToDelete); if (result.isRight()) { log.debug(FAILED_TO_LOCK_SERVICE_RESPONSE_IS, service.getName(), result.right().value()); - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE))); } - titanDao.commit(); + janusGraphDao.commit(); log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, service.getSystemName()); } catch (Exception e){ log.error("Exception occurred during delete forwarding path : {}", e.getMessage(), e); - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); @@ -1214,7 +1214,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { result = forwardingPathOperation.addForwardingPath(serviceId, forwardingPathDataDefinition); } if (result.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat( componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE), "")); @@ -1225,12 +1225,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } } catch (Exception e) { - titanDao.rollback(); + janusGraphDao.rollback(); log.error("Exception occurred during add or update forwarding path property values: {}", e.getMessage(), e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } - titanDao.commit(); + janusGraphDao.commit(); } finally { if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) { graphLockOperation.unlockComponent(storedService.getUniqueId(), NodeTypeEnum.Service); @@ -1608,7 +1608,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { log.debug("validating service category {} against valid categories list", list); Either, ActionStatus> categorys = elementDao.getAllServiceCategories(); if (categorys.isRight()) { - log.debug("failed to retrieve service categories from Titan"); + log.debug("failed to retrieve service categories from JanusGraph"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(categorys.right().value()); return Either.right(responseFormat); } @@ -1666,10 +1666,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (result == null || !result.equals(StorageOperationStatus.OK)) { log.warn("operation failed. do rollback"); BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); - titanDao.rollback(); + janusGraphDao.rollback(); } else { log.debug("operation success. do commit"); - titanDao.commit(); + janusGraphDao.commit(); } graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); } @@ -1708,10 +1708,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (result == null || !result.equals(StorageOperationStatus.OK)) { log.warn("operation failed. do rollback"); BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); - titanDao.rollback(); + janusGraphDao.rollback(); } else { log.debug("operation success. do commit"); - titanDao.commit(); + janusGraphDao.commit(); } graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); } @@ -2006,12 +2006,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { try { Either result = toscaOperationFacade.updateDistributionStatus(service, user, state); if (result.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); BeEcompErrorManager.getInstance().logBeSystemError("updateDistributionStatusForActivation"); log.debug("service {} change distribution status failed", serviceId); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } - titanDao.commit(); + janusGraphDao.commit(); return Either.left(result.left().value()); } finally { graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); @@ -2688,7 +2688,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (lock) { Either lockResult = lockComponent(service.getUniqueId(), service, "Delete Service Filter from service"); if (lockResult.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(componentsUtils .convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); } @@ -2697,15 +2697,15 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { result = serviceFilterOperation.deleteNodeFilter(service , resourceId); if (result.isRight()) { log.debug("Failed to delete node filter in service {}. Response is {}. ", service.getName(), result.right().value()); - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE))); } - titanDao.commit(); + janusGraphDao.commit(); log.debug("Node filter successfully changed in service {} . ", service.getSystemName()); } catch (Exception e){ log.error("Exception occurred during delete forwarding path : {}", e.getMessage(), e); - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); @@ -2760,17 +2760,17 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { try { result = serviceFilterOperation.createNodeFilter(serviceId, componentInstanceId); if (result.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat( componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE), "")); } else { serviceFilterResult = result.left().value(); } - titanDao.commit(); + janusGraphDao.commit(); } catch (Exception e) { - titanDao.rollback(); + janusGraphDao.rollback(); log.error("Exception occurred during add or update service filter property values: {}", e.getMessage(), e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -2832,17 +2832,17 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { Either result = serviceFilterOperation.updateProperties(serviceId, componentInstanceId, serviceFilter ,properties); if (result.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat( componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE), "")); } else { serviceFilterResult = result.left().value(); } - titanDao.commit(); + janusGraphDao.commit(); } catch (Exception e) { - titanDao.rollback(); + janusGraphDao.rollback(); log.error("Exception occurred during add or update service filter property values: {}", e.getMessage(), e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -2926,17 +2926,17 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } if (result.isRight()) { - titanDao.rollback(); + janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat( componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE), "")); } else { serviceFilterResult = result.left().value(); } - titanDao.commit(); + janusGraphDao.commit(); } catch (Exception e) { - titanDao.rollback(); + janusGraphDao.rollback(); log.error("Exception occurred during add or update node filter property values: {}", e.getMessage(), e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java index 93d79a361e..9346c41cac 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java @@ -10,7 +10,7 @@ import org.openecomp.sdc.be.model.Component; 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.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java index cc6e9e9cd3..a85a9c73bf 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java @@ -6,7 +6,7 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; import org.openecomp.sdc.common.log.wrappers.Logger; import java.util.List; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java index 10a35d0128..cb2fc5b5af 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java @@ -5,7 +5,7 @@ import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.PolicyDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java index 2d6f354139..e51caabd00 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java @@ -24,8 +24,8 @@ package org.openecomp.sdc.be.components.impl.utils; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; @@ -34,29 +34,29 @@ import org.springframework.stereotype.Component; @Component public class ExceptionUtils { - private final TitanDao titanDao; + private final JanusGraphDao janusGraphDao; - public ExceptionUtils(TitanDao titanDao) { - this.titanDao = titanDao; + public ExceptionUtils(JanusGraphDao janusGraphDao) { + this.janusGraphDao = janusGraphDao; } public T rollBackAndThrow(ActionStatus actionStatus, String ... params) { - titanDao.rollback(); + janusGraphDao.rollback(); throw new ByActionStatusComponentException(actionStatus, params); } public T rollBackAndThrow(ResponseFormat responseFormat) { - titanDao.rollback(); + janusGraphDao.rollback(); throw new ByResponseFormatComponentException(responseFormat); } public T rollBackAndThrow(StorageOperationStatus status, String ... params) { - titanDao.rollback(); + janusGraphDao.rollback(); throw new StorageException(status, params); } - public T rollBackAndThrow(TitanOperationStatus status, String ... params) { - titanDao.rollback(); + public T rollBackAndThrow(JanusGraphOperationStatus status, String ... params) { + janusGraphDao.rollback(); throw new StorageException(status, params); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java index e9289de839..5826ef1254 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java @@ -25,16 +25,16 @@ import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; 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.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; -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.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.tosca.ToscaUtils; @@ -62,8 +62,8 @@ public class CertificationChangeTransition extends LifeCycleTransition { private ArtifactsBusinessLogic artifactsManager; private NodeTemplateOperation nodeTemplateOperation; - public CertificationChangeTransition(LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + public CertificationChangeTransition(LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao); this.name = name; @@ -202,12 +202,12 @@ public class CertificationChangeTransition extends LifeCycleTransition { BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); if ( !inTransaction ) { log.debug("operation failed. do rollback"); - titanDao.rollback(); + janusGraphDao.rollback(); } } else { if ( !inTransaction ) { log.debug("operation success. do commit"); - titanDao.commit(); + janusGraphDao.commit(); } } } 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 7456a58994..a0e9bc8c15 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 @@ -25,17 +25,17 @@ import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; 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.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; 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.*; -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.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; 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; @@ -52,8 +52,8 @@ public class CertificationRequestTransition extends LifeCycleTransition { private ServiceBusinessLogic serviceBusinessLogic; public CertificationRequestTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ServiceBusinessLogic serviceBusinessLogic, - ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao); // authorized roles Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; @@ -193,12 +193,12 @@ public class CertificationRequestTransition extends LifeCycleTransition { BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); if (!inTransaction) { log.debug("operation failed. do rollback"); - titanDao.rollback(); + janusGraphDao.rollback(); } } else { if (!inTransaction) { log.debug("operation success. do commit"); - titanDao.commit(); + janusGraphDao.commit(); } } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java index 89ed22f5c4..f6cc7dcb53 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java @@ -24,7 +24,7 @@ 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.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -32,11 +32,11 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.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.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; 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; @@ -49,8 +49,8 @@ public class CheckinTransition extends LifeCycleTransition { private static final Logger log = Logger.getLogger(CheckinTransition.class); - public CheckinTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + public CheckinTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao); // authorized roles Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; @@ -100,12 +100,12 @@ public class CheckinTransition extends LifeCycleTransition { BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); if (!inTransaction) { log.debug("operation failed. do rollback"); - titanDao.rollback(); + janusGraphDao.rollback(); } } else { if (!inTransaction) { log.debug("operation success. do commit"); - titanDao.commit(); + janusGraphDao.commit(); } } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java index 33b625002f..d97c171868 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java @@ -24,18 +24,18 @@ 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.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.impl.ComponentsUtils; 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.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.tosca.ToscaUtils; @@ -50,8 +50,8 @@ public class CheckoutTransition extends LifeCycleTransition { private static final Logger log = Logger.getLogger(CheckoutTransition.class); - CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao); // authorized roles Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; @@ -131,12 +131,12 @@ public class CheckoutTransition extends LifeCycleTransition { BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); if (!inTransaction) { log.debug("operation failed. do rollback"); - titanDao.rollback(); + janusGraphDao.rollback(); } } else { if (!inTransaction) { log.debug("operation success. do commit"); - titanDao.commit(); + janusGraphDao.commit(); } } } 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 0057f615bf..180b7f0286 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 @@ -25,7 +25,7 @@ import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; @@ -34,8 +34,8 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; 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.jsonjanusgraph.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; 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; @@ -52,7 +52,7 @@ public abstract class LifeCycleTransition { @Autowired protected ToscaElementLifecycleOperation lifeCycleOperation; @Autowired - protected TitanDao titanDao; + protected JanusGraphDao janusGraphDao; protected ComponentsUtils componentUtils; protected Map> authorizedRoles; @@ -60,7 +60,7 @@ public abstract class LifeCycleTransition { ToscaOperationFacade toscaOperationFacade; - protected LifeCycleTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation2, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + protected LifeCycleTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation2, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) { this.configurationManager = ConfigurationManager.getConfigurationManager(); this.lifeCycleOperation = lifecycleOperation2; @@ -68,7 +68,7 @@ public abstract class LifeCycleTransition { this.authorizedRoles = new HashMap<>(); this.resourceAuthorizedRoles = new HashMap<>(); this.toscaOperationFacade = toscaOperationFacade; - this.titanDao = titanDao; + this.janusGraphDao = janusGraphDao; } public abstract LifeCycleTransitionEnum getName(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java index 981f0bdff2..befca2480a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java @@ -29,18 +29,18 @@ import org.openecomp.sdc.be.components.impl.*; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; 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.*; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; -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.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -71,7 +71,7 @@ public class LifecycleBusinessLogic { private ArtifactsBusinessLogic artifactsBusinessLogic; @Autowired - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Autowired private CapabilityOperation capabilityOperation; @@ -129,30 +129,37 @@ public class LifecycleBusinessLogic { private void initStateOperations() { stateTransitions = new HashMap<>(); - LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, + janusGraphDao); stateTransitions.put(checkoutOp.getName().name(), checkoutOp); - UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, + janusGraphDao); undoCheckoutOp.setArtifactsBusinessLogic(artifactsBusinessLogic); stateTransitions.put(undoCheckoutOp.getName().name(), undoCheckoutOp); - LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation, toscaOperationFacade, + janusGraphDao); stateTransitions.put(checkinOp.getName().name(), checkinOp); LifeCycleTransition certificationRequest = new CertificationRequestTransition(componentUtils, lifecycleOperation, serviceBusinessLogic, toscaOperationFacade, - titanDao); + janusGraphDao); stateTransitions.put(certificationRequest.getName().name(), certificationRequest); - LifeCycleTransition startCertification = new StartCertificationTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + LifeCycleTransition startCertification = new StartCertificationTransition(componentUtils, lifecycleOperation, toscaOperationFacade, + janusGraphDao); stateTransitions.put(startCertification.getName().name(), startCertification); - LifeCycleTransition failCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.FAIL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + LifeCycleTransition failCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.FAIL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, + janusGraphDao); stateTransitions.put(failCertification.getName().name(), failCertification); - LifeCycleTransition cancelCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CANCEL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + LifeCycleTransition cancelCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CANCEL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, + janusGraphDao); stateTransitions.put(cancelCertification.getName().name(), cancelCertification); - CertificationChangeTransition successCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + CertificationChangeTransition successCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentUtils, lifecycleOperation, toscaOperationFacade, + janusGraphDao); successCertification.setArtifactsManager(artifactsBusinessLogic); successCertification.setNodeTemplateOperation(nodeTemplateOperation); stateTransitions.put(successCertification.getName().name(), successCertification); @@ -534,9 +541,9 @@ public class LifecycleBusinessLogic { log.info("unlock component {}", resource.getUniqueId()); if (!inTransaction) { if (result.isLeft()) { - titanDao.commit(); + janusGraphDao.commit(); } else { - titanDao.rollback(); + janusGraphDao.rollback(); } if (needLock) { NodeTypeEnum nodeType = resource.getComponentType().getNodeType(); 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 fd3e24f2fb..582b3fd81c 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 @@ -24,17 +24,17 @@ 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.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.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.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; 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,8 +47,8 @@ public class StartCertificationTransition extends LifeCycleTransition { private static final Logger log = Logger.getLogger(StartCertificationTransition.class); - public StartCertificationTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + public StartCertificationTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao); // authorized roles Role[] rsrcServiceStartCertificationRoles = { Role.ADMIN, Role.TESTER }; @@ -97,12 +97,12 @@ public class StartCertificationTransition extends LifeCycleTransition { BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); if (!inTransaction) { log.debug("operation failed. do rollback"); - titanDao.rollback(); + janusGraphDao.rollback(); } } else { if (!inTransaction) { log.debug("operation success. do commit"); - titanDao.commit(); + janusGraphDao.commit(); } } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java index c6429c70bb..ff4746dcc3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java @@ -25,17 +25,17 @@ import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; 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.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.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.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; 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; @@ -48,8 +48,8 @@ public class UndoCheckoutTransition extends LifeCycleTransition { private static final Logger log = Logger.getLogger(CheckoutTransition.class); private ArtifactsBusinessLogic artifactsManager; - public UndoCheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + public UndoCheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao); // authorized roles Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; @@ -126,10 +126,10 @@ public class UndoCheckoutTransition extends LifeCycleTransition { if (result == null || result.isRight()) { BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Undo Checkout failed on graph"); log.debug("operation failed. do rollback"); - titanDao.rollback(); + janusGraphDao.rollback(); } else { log.debug("operation success. do commit"); - titanDao.commit(); + janusGraphDao.commit(); } } return result; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java index 00e49dcbc0..9e01fb9c30 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java @@ -7,7 +7,7 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import java.util.List; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java index 1220ec4d97..eddff124b5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java @@ -8,7 +8,7 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/ComponentGroupMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/ComponentGroupMergeCommand.java index 1638aea737..90b0ed4e8e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/ComponentGroupMergeCommand.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/ComponentGroupMergeCommand.java @@ -7,7 +7,7 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.core.annotation.Order; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/GroupPropertiesMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/GroupPropertiesMergeCommand.java index a84360b69b..68ee15e877 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/GroupPropertiesMergeCommand.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/GroupPropertiesMergeCommand.java @@ -9,7 +9,7 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; import org.springframework.core.annotation.Order; import java.util.List; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java index 802dc2271f..fd45f9c59d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java @@ -6,7 +6,7 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.springframework.core.annotation.Order; import java.util.List; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/GlobalInputsMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/GlobalInputsMergeCommand.java index 66e8dc4ee0..84cb111d51 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/GlobalInputsMergeCommand.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/GlobalInputsMergeCommand.java @@ -8,7 +8,7 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.springframework.core.annotation.Order; import java.util.List; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsMergeCommand.java index 3cf4c0df65..8580844f7c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsMergeCommand.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsMergeCommand.java @@ -5,7 +5,7 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.common.log.wrappers.Logger; import java.util.List; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java index 7863243765..28a6623ee7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java @@ -12,7 +12,7 @@ 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.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.core.annotation.Order; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java index f6de767ed4..6ed252d2d2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java @@ -3,7 +3,7 @@ package org.openecomp.sdc.be.components.merge.instance; import fj.data.Either; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java index 13e85085d6..5e7d3628d2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java @@ -8,7 +8,7 @@ import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ForwardingPathUtils; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsMergeBL.java index 037ab86368..b04ee22f7e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsMergeBL.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsMergeBL.java @@ -9,7 +9,7 @@ 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.InputDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.springframework.core.annotation.Order; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsRedeclareHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsRedeclareHandler.java index c09fb91d1f..4feef4bb5d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsRedeclareHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsRedeclareHandler.java @@ -8,7 +8,7 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.utils.ComponentUtilities; import org.openecomp.sdc.common.log.wrappers.Logger; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInterfacesMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInterfacesMerge.java index 60e60b0408..bc8288896a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInterfacesMerge.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInterfacesMerge.java @@ -12,7 +12,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInterface; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java index 31b3207d6c..e6260286f7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java @@ -8,7 +8,7 @@ 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.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropertiesMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropertiesMergeBL.java index 04c43b4c65..7eb5518d44 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropertiesMergeBL.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropertiesMergeBL.java @@ -9,7 +9,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.springframework.core.annotation.Order; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java index dc037abe80..0bcbaf0556 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java @@ -4,7 +4,7 @@ import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java index 995eae701c..de7179865d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java @@ -11,7 +11,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.log.wrappers.Logger; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ExternalRefsMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ExternalRefsMergeBL.java index 68a8333e31..bc6e0309ef 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ExternalRefsMergeBL.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ExternalRefsMergeBL.java @@ -27,7 +27,7 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ExternalReferencesOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ExternalReferencesOperation; import org.openecomp.sdc.exception.ResponseFormat; import java.util.List; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/policy/PoliciesMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/policy/PoliciesMergeCommand.java index e57317f165..2f5698af4e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/policy/PoliciesMergeCommand.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/policy/PoliciesMergeCommand.java @@ -9,7 +9,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.PolicyDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.core.annotation.Order; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java index df7b877364..82bc0f4b75 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java @@ -7,7 +7,7 @@ import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.DataTypeDefinition; @@ -44,7 +44,7 @@ public class PropertyDataValueMergeBusinessLogic { * @param newProp the new property to merge value into */ public void mergePropertyValue(PropertyDataDefinition oldProp, PropertyDataDefinition newProp, List getInputNamesToMerge) { - Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll(); if (dataTypesEither.isRight()) { LOGGER.debug("failed to fetch data types, skip merging of previous property values. status: {}", dataTypesEither.right().value()); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java index 55cf75b769..2dde63f1f2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java @@ -8,8 +8,8 @@ import org.openecomp.sdc.be.components.merge.instance.RelationMergeInfo; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java index a099aad15c..837872917e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java @@ -7,7 +7,7 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclarator.java index d7b366e0a8..fdcfd35ca4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclarator.java @@ -20,7 +20,7 @@ import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstancePropInput; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.common.log.wrappers.Logger; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclarator.java index 14ea9300fe..2026e1136d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclarator.java @@ -16,7 +16,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.common.log.wrappers.Logger; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java index ae76dadbf0..b1910ad217 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java @@ -30,7 +30,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java index bdb79c71bb..9f43284104 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java @@ -21,7 +21,7 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.json.simple.JSONObject; import org.openecomp.sdc.be.components.utils.PropertiesUtils; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertiesOwner; @@ -466,10 +466,12 @@ public abstract class DefaultPropertyDeclarator prepareValueBeforeDelete(InputDefinition inputForDelete, PropertyDataDefinition inputValue, List pathOfComponentInstances) { Either deleteEither = prepareValueBeforeDelete(inputForDelete, inputValue); - Either findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(), + Either findDefaultValue = propertyOperation + .findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(), (String) inputValue.getDefaultValue()); if (findDefaultValue.isRight()) { - deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())))); + deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils + .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(findDefaultValue.right().value())))); return deleteEither; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclarator.java index 17059104ff..9cf6ff9fa4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclarator.java @@ -35,7 +35,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PolicyDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.PolicyOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.PolicyOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.common.log.wrappers.Logger; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclarator.java index 2726f67342..0c6f8a24b4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclarator.java @@ -15,7 +15,7 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PolicyDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentPropertyToPolicyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentPropertyToPolicyDeclarator.java index 6bd09c1622..362f80ff1f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentPropertyToPolicyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentPropertyToPolicyDeclarator.java @@ -13,7 +13,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogic.java index ef3ffb8953..ffb4805285 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogic.java @@ -6,13 +6,13 @@ import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.jsontitan.operations.UpgradeOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.UpgradeOperation; 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; @@ -31,7 +31,7 @@ public class UpgradeBusinessLogic { private final ToscaOperationFacade toscaOperationFacade; private final ComponentsUtils componentsUtils; private final UpgradeOperation upgradeOperation; - private final TitanDao titanDao; + private final JanusGraphDao janusGraphDao; private LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("automated upgrade"); private static final List UUID_PROPS_NAMES = Arrays.asList("depending_service_uuid", "providing_service_uuid"); @@ -41,14 +41,14 @@ public class UpgradeBusinessLogic { private static final Logger LOGGER = Logger.getLogger(UpgradeBusinessLogic.class); public UpgradeBusinessLogic(LifecycleBusinessLogic lifecycleBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBusinessLogic, UserValidations userValidations, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, - UpgradeOperation upgradeOperation, TitanDao titanDao) { + UpgradeOperation upgradeOperation, JanusGraphDao janusGraphDao) { this.lifecycleBusinessLogic = lifecycleBusinessLogic; this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; this.userValidations = userValidations; this.toscaOperationFacade = toscaOperationFacade; this.componentsUtils = componentsUtils; this.upgradeOperation = upgradeOperation; - this.titanDao = titanDao; + this.janusGraphDao = janusGraphDao; } @@ -113,7 +113,7 @@ public class UpgradeBusinessLogic { .map(rf -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(rf))); } finally { // all operation were read only. no commit needed - titanDao.rollback(); + janusGraphDao.rollback(); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java index 9dbf012653..bdd7f656b3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java @@ -32,7 +32,7 @@ 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.GroupDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/NodeFilterValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/NodeFilterValidator.java index 8d2808851b..c16927f040 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/NodeFilterValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/NodeFilterValidator.java @@ -20,7 +20,7 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.ui.model.UIConstraint; import org.openecomp.sdc.exception.ResponseFormat; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PropertyValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PropertyValidator.java index 94751593fa..b42aa4cfa7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PropertyValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PropertyValidator.java @@ -6,7 +6,7 @@ import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; @@ -92,11 +92,11 @@ public class PropertyValidator { break; } - Either, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); + Either, JanusGraphOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); + JanusGraphOperationStatus status = allDataTypes.right().value(); BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to validate property. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)))); } type = property.getType(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java index fa35b64cf3..8611321b87 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java @@ -12,7 +12,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; import org.openecomp.sdc.common.log.wrappers.Logger; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java index 78bb5e67e1..c71c7960ab 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java @@ -30,7 +30,7 @@ import org.openecomp.sdc.be.externalapi.servlet.representation.*; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java index 3a823ded76..c9430107df 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java @@ -25,7 +25,7 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.HealingTitanDao; +import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.common.api.Constants; @@ -118,7 +118,7 @@ public class BeServletFilter implements ContainerRequestFilter, ContainerRespons audit.startLog(requestContext); } - writeToTitan(responseContext); + writeToJanusGraph(responseContext); //write to Audit log in case it's valuable action // (e.g. ignoring healthCheck and any other unlogged urls as in yaml @@ -144,18 +144,18 @@ public class BeServletFilter implements ContainerRequestFilter, ContainerRespons } } - private void writeToTitan(ContainerResponseContext responseContext) { + private void writeToJanusGraph(ContainerResponseContext responseContext) { log.debug("Close transaction from filter"); - HealingTitanDao titanDao = getTitanDao(); - if (titanDao != null) { + HealingJanusGraphDao janusGraphDao = getJanusGraphDao(); + if (janusGraphDao != null) { int status = responseContext.getStatus(); if (status == Response.Status.OK.getStatusCode() || status == Response.Status.CREATED.getStatusCode() || status == Response.Status.NO_CONTENT.getStatusCode()) { - titanDao.commit(); + janusGraphDao.commit(); log.debug("Doing commit from filter"); } else { - titanDao.rollback(); + janusGraphDao.rollback(); log.debug("Doing rollback from filter"); } } @@ -202,12 +202,12 @@ public class BeServletFilter implements ContainerRequestFilter, ContainerRespons return webApplicationContext.getBean(ComponentsUtils.class); } - private HealingTitanDao getTitanDao() { + private HealingJanusGraphDao getJanusGraphDao() { ServletContext context = this.sr.getSession().getServletContext(); WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - return webApplicationContext.getBean(HealingTitanDao.class); + return webApplicationContext.getBean(HealingJanusGraphDao.class); } // Extracted for purpose of clear method name, for logback %M parameter diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java index 31ba52749a..158cc2d842 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java @@ -92,7 +92,7 @@ public class ComponentsAvailabilityFilter implements ContainerRequestFilter { List healthCheckInfos = new ArrayList<>(); HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(servletContext); - healthCheckBusinessLogic.getTitanHealthCheck(healthCheckInfos); // Titan + healthCheckBusinessLogic.getJanusGraphHealthCheck(healthCheckInfos); // JanusGraph return healthCheckInfos; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java index 245eb59301..8e06c02767 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java @@ -31,8 +31,8 @@ import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.utils.ComponentUtilities; import org.openecomp.sdc.be.tosca.ToscaUtils.SubstitutionEntry; 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 7b40781f3f..2f1357ea13 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 @@ -40,8 +40,8 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.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.resources.data.ESArtifactData; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/GroupExportParserImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/GroupExportParserImpl.java index d7adb54c08..ff69eaa90b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/GroupExportParserImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/GroupExportParserImpl.java @@ -3,7 +3,7 @@ package org.openecomp.sdc.be.tosca; import fj.data.Either; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; @@ -44,7 +44,7 @@ public class GroupExportParserImpl implements GroupExportParser { } private Map getDataTypes() { - Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll(); if (dataTypesEither.isRight()) { log.error("Failed to retrieve all data types {}", dataTypesEither.right().value()); throw new SdcResourceNotFoundException(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PolicyExportParserImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PolicyExportParserImpl.java index 0ebdf0e362..84b4193940 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PolicyExportParserImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PolicyExportParserImpl.java @@ -3,7 +3,7 @@ package org.openecomp.sdc.be.tosca; import fj.data.Either; import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.*; @@ -43,7 +43,7 @@ public class PolicyExportParserImpl implements PolicyExportParser { } private Map getDataTypes() { - Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll(); if (dataTypesEither.isRight()) { log.error("Failed to retrieve all data types {}", dataTypesEither.right().value()); throw new SdcResourceNotFoundException(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java index e6e69bf8de..603da09a1d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java @@ -32,7 +32,7 @@ import org.apache.commons.lang3.tuple.Triple; import org.onap.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.elements.*; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -41,8 +41,8 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter; @@ -249,7 +249,7 @@ public class ToscaExportHandler { toscaNode.setInterface_types(proxyInterfaceTypes); } - Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll(); if (dataTypesEither.isRight()) { log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value()); return Either.right(ToscaError.GENERAL_ERROR); @@ -548,7 +548,7 @@ public class ToscaExportHandler { .collect(Collectors.toList()); toscaNode.setInterface_types(addInterfaceTypeElement(component, allGlobalInterfaceTypes)); - Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll(); if (dataTypesEither.isRight()) { log.debug("Failed to fetch all data types :", dataTypesEither.right().value()); return Either.right(ToscaError.GENERAL_ERROR); @@ -1028,7 +1028,7 @@ public class ToscaExportHandler { String derivedFrom = ((Resource) origComponent).getToscaResourceName(); toscaNodeType.setDerived_from(derivedFrom); - Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll(); if (dataTypesEither.isRight()) { log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value()); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java index 59dd8d0f00..32cb604e76 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java @@ -20,13 +20,10 @@ package org.openecomp.sdc.be.tosca; -import org.apache.commons.lang3.StringUtils; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import java.lang.reflect.Field; import java.util.*; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java index a332e6401a..62a5e8ccfe 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java @@ -8,7 +8,7 @@ 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.Service; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.tosca.CapabilityRequirementConverter; import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java index b7e4c53844..a56607d4ce 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java @@ -25,7 +25,7 @@ import org.apache.tinkerpop.gremlin.structure.Edge; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.LifecycleStateEnum; @@ -57,7 +57,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { @Resource private ComponentsUtils componentsUtils; @Autowired - private TitanGenericDao titanDao; + private JanusGraphGenericDao janusGraphDao; @Override public Either getUser(String userId, boolean inTransaction) { @@ -603,9 +603,9 @@ public class UserBusinessLogic implements IUserBusinessLogic { // commit will be perform outside!!! if (result == null || result.isRight()) { log.debug("getUserPendingTasksList failed to perform fetching"); - titanDao.rollback(); + janusGraphDao.rollback(); } else { - titanDao.commit(); + janusGraphDao.commit(); } } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java index ea041359fd..b964321c8a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java @@ -34,6 +34,6 @@ public interface ITransactionSdnc { Either invokeGeneralDBAction(boolean isLastAction, DBTypeEnum dbType, IDBAction dbAction, IDBAction dbRollbackAction); - Either invokeTitanAction(boolean isLastAction, IDBAction dbAction); + Either invokeJanusGraphAction(boolean isLastAction, IDBAction dbAction); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java index fc7c90509f..60f89ce012 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java @@ -30,7 +30,7 @@ public final class TransactionUtils { } public enum DBTypeEnum { - ELASTIC_SEARCH, TITAN, MYSTERY, SWIFT + ELASTIC_SEARCH, JANUSGRAPH, MYSTERY, SWIFT } public enum TransactionCodeEnum { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/JanusGraphCommitHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/JanusGraphCommitHandler.java new file mode 100644 index 0000000000..dad79b5f76 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/JanusGraphCommitHandler.java @@ -0,0 +1,52 @@ +/*- + * ============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.common.transaction.impl; + +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.common.transaction.api.ICommitHandler; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; + +public class JanusGraphCommitHandler implements ICommitHandler { + + private JanusGraphGenericDao janusGraphGenericDao; + + public JanusGraphCommitHandler(JanusGraphGenericDao janusGraphGenericDao) { + this.janusGraphGenericDao = janusGraphGenericDao; + } + + @Override + public DBActionCodeEnum doCommit() { + DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; + JanusGraphOperationStatus janusGraphStatus = janusGraphGenericDao.commit(); + if (janusGraphStatus != JanusGraphOperationStatus.OK) { + result = DBActionCodeEnum.FAIL_GENERAL; + } + return result; + } + + @Override + public DBTypeEnum getDBType() { + return DBTypeEnum.JANUSGRAPH; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/JanusGraphRollbackHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/JanusGraphRollbackHandler.java new file mode 100644 index 0000000000..ed2633fa11 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/JanusGraphRollbackHandler.java @@ -0,0 +1,55 @@ +/*- + * ============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.common.transaction.impl; + +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.common.transaction.api.RollbackHandler; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; + +public class JanusGraphRollbackHandler extends RollbackHandler { + + private JanusGraphGenericDao janusGraphGenericDao; + + public JanusGraphRollbackHandler(Integer transactionId, String userId, String actionType, JanusGraphGenericDao janusGraphGenericDao) { + super(transactionId, userId, actionType); + this.janusGraphGenericDao = janusGraphGenericDao; + } + + public DBTypeEnum getDBType() { + return DBTypeEnum.JANUSGRAPH; + } + + protected boolean isRollbackForPersistenceData() { + return false; + } + + public DBActionCodeEnum doNonPersistenceDataRollback() { + DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; + JanusGraphOperationStatus janusGraphStatus = janusGraphGenericDao.rollback(); + if (janusGraphStatus != JanusGraphOperationStatus.OK) { + result = DBActionCodeEnum.FAIL_GENERAL; + } + return result; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java deleted file mode 100644 index c86241ebf1..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java +++ /dev/null @@ -1,52 +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.common.transaction.impl; - -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.common.transaction.api.ICommitHandler; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; - -public class TitanCommitHandler implements ICommitHandler { - - private TitanGenericDao titanGenericDao; - - public TitanCommitHandler(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; - } - - @Override - public DBActionCodeEnum doCommit() { - DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; - TitanOperationStatus titanStatus = titanGenericDao.commit(); - if (titanStatus != TitanOperationStatus.OK) { - result = DBActionCodeEnum.FAIL_GENERAL; - } - return result; - } - - @Override - public DBTypeEnum getDBType() { - return DBTypeEnum.TITAN; - } - -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java deleted file mode 100644 index 89d2b9da8e..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java +++ /dev/null @@ -1,55 +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.common.transaction.impl; - -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.common.transaction.api.RollbackHandler; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; - -public class TitanRollbackHandler extends RollbackHandler { - - private TitanGenericDao titanGenericDao; - - public TitanRollbackHandler(Integer transactionId, String userId, String actionType, TitanGenericDao titanGenericDao) { - super(transactionId, userId, actionType); - this.titanGenericDao = titanGenericDao; - } - - public DBTypeEnum getDBType() { - return DBTypeEnum.TITAN; - } - - protected boolean isRollbackForPersistenceData() { - return false; - } - - public DBActionCodeEnum doNonPersistenceDataRollback() { - DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; - TitanOperationStatus titanStatus = titanGenericDao.rollback(); - if (titanStatus != TitanOperationStatus.OK) { - result = DBActionCodeEnum.FAIL_GENERAL; - } - return result; - } - -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java index 9d95c26ec9..78264484fb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java @@ -23,7 +23,7 @@ package org.openecomp.sdc.common.transaction.mngr; import com.google.common.collect.EvictingQueue; import com.google.common.collect.Queues; import org.openecomp.sdc.be.dao.impl.ESCatalogDAO; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.transaction.api.ITransactionSdnc; import org.openecomp.sdc.common.transaction.api.TransactionUtils; @@ -45,7 +45,7 @@ public class TransactionManager { @Resource private ESCatalogDAO esCatalogDao; @Resource - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; /** * userId and actionType parameters are used only for logging purposes. @@ -55,7 +55,8 @@ public class TransactionManager { init(); } log.debug("TransactionManager creating new SdncTransaction"); - ITransactionSdnc tx = new TransactionSdncImpl(generateTransactionID(), userId, actionType, esCatalogDao, titanGenericDao); + ITransactionSdnc tx = new TransactionSdncImpl(generateTransactionID(), userId, actionType, esCatalogDao, + janusGraphGenericDao); transactions.add(tx); return tx; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java index 1c07e50e0a..93a2c9db82 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java @@ -23,15 +23,15 @@ package org.openecomp.sdc.common.transaction.mngr; import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.impl.ESCatalogDAO; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.transaction.api.*; import org.openecomp.sdc.common.transaction.api.TransactionUtils.*; import org.openecomp.sdc.common.transaction.impl.ESAction; import org.openecomp.sdc.common.transaction.impl.ESRollbackHandler; -import org.openecomp.sdc.common.transaction.impl.TitanCommitHandler; -import org.openecomp.sdc.common.transaction.impl.TitanRollbackHandler; +import org.openecomp.sdc.common.transaction.impl.JanusGraphCommitHandler; +import org.openecomp.sdc.common.transaction.impl.JanusGraphRollbackHandler; import org.openecomp.sdc.common.util.MethodActivationStatusEnum; import java.util.ArrayList; @@ -45,14 +45,14 @@ public class TransactionSdncImpl implements ITransactionSdnc { private RollbackManager rollbackManager; private CommitManager commitManager; private ESCatalogDAO esCatalogDao; - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; private Integer transactionId; private TransactionStatusEnum status; private String userId, actionType; - TransactionSdncImpl(Integer transactionId, String userId, ActionTypeEnum actionTypeEnum, ESCatalogDAO esCatalogDao, TitanGenericDao titanGenericDao) { + TransactionSdncImpl(Integer transactionId, String userId, ActionTypeEnum actionTypeEnum, ESCatalogDAO esCatalogDao, JanusGraphGenericDao janusGraphGenericDao) { this.esCatalogDao = esCatalogDao; - this.titanGenericDao = titanGenericDao; + this.janusGraphGenericDao = janusGraphGenericDao; this.transactionId = transactionId; this.userId = userId; actionType = actionTypeEnum.name(); @@ -64,13 +64,14 @@ public class TransactionSdncImpl implements ITransactionSdnc { private List initCommitHandlers() { List commitHandlers = new ArrayList<>(); - commitHandlers.add(new TitanCommitHandler(titanGenericDao)); + commitHandlers.add(new JanusGraphCommitHandler(janusGraphGenericDao)); return commitHandlers; } private List initRollbackHandlers() { List rolebackHandlers = new ArrayList<>(); - rolebackHandlers.add(new TitanRollbackHandler(transactionId, userId, actionType, titanGenericDao)); + rolebackHandlers.add(new JanusGraphRollbackHandler(transactionId, userId, actionType, + janusGraphGenericDao)); rolebackHandlers.add(new ESRollbackHandler(transactionId, userId, actionType)); return rolebackHandlers; } @@ -115,10 +116,10 @@ public class TransactionSdncImpl implements ITransactionSdnc { return result; } - public Either invokeTitanAction(boolean isLastAction, IDBAction dbAction) { + public Either invokeJanusGraphAction(boolean isLastAction, IDBAction dbAction) { Either result; if (status == TransactionStatusEnum.OPEN) { - result = invokeAction(isLastAction, dbAction, DBTypeEnum.TITAN); + result = invokeAction(isLastAction, dbAction, DBTypeEnum.JANUSGRAPH); } else { result = handleActionOnClosedTransaction(); } diff --git a/catalog-be/src/main/resources/config/configuration.yaml b/catalog-be/src/main/resources/config/configuration.yaml index d23f87eb96..0e6e248ef0 100644 --- a/catalog-be/src/main/resources/config/configuration.yaml +++ b/catalog-be/src/main/resources/config/configuration.yaml @@ -42,15 +42,15 @@ supportAllottedResourcesAndProxy: true deleteLockTimeoutInSeconds: 60 maxDeleteComponents: 10 -titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties -titanInMemoryGraph: false -titanLockTimeout: 1800 +janusGraphCfgFile: /home/vagrant/catalog-be/config/catalog-be/janusgraph.properties +janusGraphInMemoryGraph: false +janusGraphLockTimeout: 1800 -# The interval to try and reconnect to titan DB when it is down during ASDC startup: -titanReconnectIntervalInSeconds: 3 +# The interval to try and reconnect to janusGraph DB when it is down during ASDC startup: +janusGraphReconnectIntervalInSeconds: 3 -# The read timeout towards Titan DB when health check is invoked: -titanHealthCheckReadTimeout: 1 +# The read timeout towards Janus Graph DB when health check is invoked: +janusGraphHealthCheckReadTimeout: 1 # The interval to try and reconnect to Elasticsearch when it is down during ASDC startup: esReconnectIntervalInSeconds: 3 diff --git a/catalog-be/src/main/resources/config/janusgraph.properties b/catalog-be/src/main/resources/config/janusgraph.properties new file mode 100644 index 0000000000..5411a44224 --- /dev/null +++ b/catalog-be/src/main/resources/config/janusgraph.properties @@ -0,0 +1,11 @@ +storage.backend=cassandra +storage.hostname=localhost +storage.port=9160 + +cache.db-cache = false +cache.db-cache-clean-wait = 20 +cache.db-cache-time = 180000 +cache.db-cache-size = 0.5 + +cache.tx-cache-size = 500000 +storage.cassandra.keyspace=sdctitan diff --git a/catalog-be/src/main/resources/config/titan.properties b/catalog-be/src/main/resources/config/titan.properties deleted file mode 100644 index 5411a44224..0000000000 --- a/catalog-be/src/main/resources/config/titan.properties +++ /dev/null @@ -1,11 +0,0 @@ -storage.backend=cassandra -storage.hostname=localhost -storage.port=9160 - -cache.db-cache = false -cache.db-cache-clean-wait = 20 -cache.db-cache-time = 180000 -cache.db-cache-size = 0.5 - -cache.tx-cache-size = 500000 -storage.cassandra.keyspace=sdctitan diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/MockGenerator.java b/catalog-be/src/test/java/org/openecomp/sdc/be/MockGenerator.java index ea66ec707b..84d25a2a44 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/MockGenerator.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/MockGenerator.java @@ -2,7 +2,7 @@ package org.openecomp.sdc.be; import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.impl.ComponentsUtils; import static org.mockito.Mockito.mock; @@ -14,6 +14,6 @@ public class MockGenerator { } public static ExceptionUtils mockExceptionUtils() { - return new ExceptionUtils(mock(TitanDao.class)); + return new ExceptionUtils(mock(JanusGraphDao.class)); } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java index 20f7f1874a..4ee63f7ba5 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java @@ -9,12 +9,11 @@ import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; -import org.openecomp.sdc.be.components.impl.ServiceBusinessLogicTest; import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; 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.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -23,8 +22,8 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ForwardingPathOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; 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; @@ -62,7 +61,7 @@ public abstract class BaseServiceBusinessLogicTest { AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class); ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class); GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); - TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class); ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); @@ -138,7 +137,7 @@ public abstract class BaseServiceBusinessLogicTest { bl.setUserAdmin(mockUserAdmin); bl.setArtifactBl(artifactBl); bl.setGraphLockOperation(graphLockOperation); - bl.setTitanGenericDao(mockTitanDao); + bl.setJanusGraphGenericDao(mockJanusGraphDao); bl.setToscaOperationFacade(toscaOperationFacade); bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); bl.setComponentsUtils(componentsUtils); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java index 822e76464c..000de2cd4b 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java @@ -47,29 +47,29 @@ public class HealthCheckBusinessLogicTest { statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); assertFalse("check false", statusChanged); - HealthCheckInfo checkInfoTitanUp = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.UP, null, null); - HealthCheckInfo checkInfoTitanDown = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, null); + HealthCheckInfo checkInfoJanusGraphUp = new HealthCheckInfo(Constants.HC_COMPONENT_JANUSGRAPH, HealthCheckStatus.UP, null, null); + HealthCheckInfo checkInfoJanusGraphDown = new HealthCheckInfo(Constants.HC_COMPONENT_JANUSGRAPH, HealthCheckStatus.DOWN, null, null); - checkInfosLeft.add(checkInfoTitanUp); + checkInfosLeft.add(checkInfoJanusGraphUp); - checkInfosRight.add(checkInfoTitanUp); + checkInfosRight.add(checkInfoJanusGraphUp); statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); assertFalse("check false", statusChanged); - checkInfosRight.remove(checkInfoTitanUp); + checkInfosRight.remove(checkInfoJanusGraphUp); statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); assertTrue("check true", statusChanged); - checkInfosRight.add(checkInfoTitanDown); + checkInfosRight.add(checkInfoJanusGraphDown); statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); assertTrue("check true", statusChanged); - checkInfosRight.remove(checkInfoTitanDown); + checkInfosRight.remove(checkInfoJanusGraphDown); statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); assertTrue("check true", statusChanged); - checkInfosRight.add(checkInfoTitanUp); + checkInfosRight.add(checkInfoJanusGraphUp); statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); assertFalse("check false", statusChanged); 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 4f2bb78079..971f7b8f20 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 @@ -31,11 +31,11 @@ import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.IPropertyOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -81,7 +81,7 @@ public class PropertyBusinessLogicTest { @Mock IGraphLockOperation graphLockOperation; @Mock - TitanDao titanDao; + JanusGraphDao janusGraphDao; @InjectMocks private PropertyBusinessLogic bl = new PropertyBusinessLogic(); @@ -291,16 +291,16 @@ public class PropertyBusinessLogicTest { resource.setUniqueId(resourceId); Field baseBusinessLogic3; - baseBusinessLogic3 = bl.getClass().getSuperclass().getDeclaredField("titanDao"); + baseBusinessLogic3 = bl.getClass().getSuperclass().getDeclaredField("janusGraphDao"); baseBusinessLogic3.setAccessible(true); - baseBusinessLogic3.set(bl, titanDao); + baseBusinessLogic3.set(bl, janusGraphDao); Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); StorageOperationStatus lockResult = StorageOperationStatus.OK; when(graphLockOperation.lockComponent(any(), any())).thenReturn(lockResult); - //doNothing().when(titanDao).commit(); + //doNothing().when(janusGraphDao).commit(); Either result; @@ -327,16 +327,16 @@ public class PropertyBusinessLogicTest { resource.setUniqueId(resourceId); Field baseBusinessLogic3; - baseBusinessLogic3 = bl.getClass().getSuperclass().getDeclaredField("titanDao"); + baseBusinessLogic3 = bl.getClass().getSuperclass().getDeclaredField("janusGraphDao"); baseBusinessLogic3.setAccessible(true); - baseBusinessLogic3.set(bl, titanDao); + baseBusinessLogic3.set(bl, janusGraphDao); Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); StorageOperationStatus lockResult = StorageOperationStatus.OK; when(graphLockOperation.lockComponent(any(), any())).thenReturn(lockResult); - //doNothing().when(titanDao).commit(); + //doNothing().when(janusGraphDao).commit(); Either result; @@ -363,16 +363,16 @@ public class PropertyBusinessLogicTest { resource.setUniqueId(resourceId); Field baseBusinessLogic3; - baseBusinessLogic3 = bl.getClass().getSuperclass().getDeclaredField("titanDao"); + baseBusinessLogic3 = bl.getClass().getSuperclass().getDeclaredField("janusGraphDao"); baseBusinessLogic3.setAccessible(true); - baseBusinessLogic3.set(bl, titanDao); + baseBusinessLogic3.set(bl, janusGraphDao); Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); StorageOperationStatus lockResult = StorageOperationStatus.OK; when(graphLockOperation.lockComponent(any(), any())).thenReturn(lockResult); - //doNothing().when(titanDao).commit(); + //doNothing().when(janusGraphDao).commit(); Either result; 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 2e9112607f..00e3f03074 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 @@ -35,7 +35,7 @@ import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; 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; @@ -81,7 +81,7 @@ public class ResourceImportManagerTest { configurationManager = new ConfigurationManager(configurationSource); Configuration configuration = new Configuration(); - configuration.setTitanInMemoryGraph(true); + configuration.setJanusGraphInMemoryGraph(true); configurationManager.setConfiguration(configuration); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java index 9dab8f4b96..28f97ad858 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java @@ -23,7 +23,7 @@ import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DistributionStatusEnum; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/csar/CsarBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/csar/CsarBusinessLogicTest.java index fdaedbb942..c4b76a2a37 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/csar/CsarBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/csar/CsarBusinessLogicTest.java @@ -59,7 +59,7 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; 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.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.CsarOperation; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilderTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilderTest.java index 63018ee232..7484ff0e09 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilderTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilderTest.java @@ -15,7 +15,7 @@ import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.common.api.ArtifactTypeEnum; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogicTest.java index 83966be4d5..5fa074705d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogicTest.java @@ -104,14 +104,14 @@ public class HealthCheckBusinessLogicTest extends BeConfDependentTest{ } @Test - public void testGetTitanHealthCheck() throws Exception { + public void testGetJanusGraphHealthCheck() throws Exception { HealthCheckBusinessLogic testSubject; List healthCheckInfos = new LinkedList<>(); List result; // default test testSubject = createTestSubject(); - result = testSubject.getTitanHealthCheck(healthCheckInfos); + result = testSubject.getJanusGraphHealthCheck(healthCheckInfos); } @Test diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogicTest.java index a2f8b09566..1cdd089539 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogicTest.java @@ -40,7 +40,7 @@ import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -48,7 +48,7 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.AdditionalInformationDefinition; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -77,7 +77,7 @@ public class AdditionalInformationBusinessLogicTest { @Mock private ComponentsUtils componentsUtils; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private IAdditionalInformationOperation additionalInformationOperation; @Mock diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogicTest.java index 8029e788d9..c4a3e59dab 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogicTest.java @@ -13,8 +13,8 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ArchiveOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArchiveOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.exception.ResponseFormat; 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 066813448f..65718630da 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 @@ -41,16 +41,16 @@ import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; 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.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.model.operations.api.*; import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation; @@ -115,7 +115,7 @@ public class ArtifactBusinessLogicTest { @Mock private IGraphLockOperation graphLockOperation; @Mock - TitanDao titanDao; + JanusGraphDao janusGraphDao; @Mock private IInterfaceLifecycleOperation interfaceLifecycleOperation; @Mock @@ -560,7 +560,7 @@ public class ArtifactBusinessLogicTest { when(componentsUtils.getResponseFormat(any(ActionStatus.class))).thenReturn(new ResponseFormat()); artifactBL.generateAndSaveHeatEnvArtifact(artifactDefinition, String.valueOf(PAYLOAD), ComponentTypeEnum.SERVICE, new Service(), RESOURCE_INSTANCE_NAME, USER, INSTANCE_ID, true, false); - verify(titanDao, times(1)).commit(); + verify(janusGraphDao, times(1)).commit(); } @Test diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogicTest.java index 9b4482c5ec..27e9f3f871 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogicTest.java @@ -50,9 +50,9 @@ import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; @@ -78,10 +78,10 @@ import org.openecomp.sdc.be.model.ResourceMetadataDefinition; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; 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.InterfaceOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; 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.IInterfaceLifecycleOperation; @@ -154,9 +154,9 @@ public class ArtifactsBusinessLogicTest { public ComponentsUtils componentsUtils; @Mock public ToscaOperationFacade toscaOperationFacade; - TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class); @Mock - TitanDao titanDao; + JanusGraphDao janusGraphDao; @Mock private UserBusinessLogic userBusinessLogic; @Mock @@ -238,7 +238,7 @@ public class ArtifactsBusinessLogicTest { when(toscaOperationFacade.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(StorageOperationStatus.OK); Map emptyDataTypes = new HashMap<>(); when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes)); - when(mockTitanDao.commit()).thenReturn(TitanOperationStatus.OK); + when(mockJanusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK); Either resourceStorageOperationStatusEither = Either .right(StorageOperationStatus.BAD_REQUEST); @@ -511,7 +511,7 @@ public class ArtifactsBusinessLogicTest { when(componentsUtils.getResponseFormat(any(ActionStatus.class))).thenReturn(new ResponseFormat()); artifactBL.generateAndSaveHeatEnvArtifact(artifactDefinition, String.valueOf(PAYLOAD), ComponentTypeEnum.SERVICE, new Service(), RESOURCE_INSTANCE_NAME, USER, INSTANCE_ID, true, false); - verify(titanDao, times(1)).commit(); + verify(janusGraphDao, times(1)).commit(); } private ArtifactDefinition buildArtifactPayload() { @@ -530,7 +530,7 @@ public class ArtifactsBusinessLogicTest { when(componentsUtils.getResponseFormat(any(ActionStatus.class))).thenReturn(new ResponseFormat()); artifactBL.generateAndSaveHeatEnvArtifact(artifactDefinition, String.valueOf(PAYLOAD), ComponentTypeEnum.SERVICE, new Service(), RESOURCE_INSTANCE_NAME, USER, INSTANCE_ID, true, false); - verify(titanDao, times(1)).commit(); + verify(janusGraphDao, times(1)).commit(); return artifactDefinition; } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogicTest.java index 88918de1a3..55f4367c21 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogicTest.java @@ -11,22 +11,19 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.openecomp.sdc.be.components.validation.UserValidations; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.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.PropertyOperation; -import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.exception.ResponseFormat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyObject; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; import fj.data.Either; @@ -40,7 +37,7 @@ public class AttributeBusinessLogicTest { UserValidations userValidations = Mockito.mock(UserValidations.class); ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - TitanDao titanDao = Mockito.mock(TitanDao.class); + JanusGraphDao janusGraphDao = Mockito.mock(JanusGraphDao.class); ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class); PropertyOperation propertyOperation = Mockito.mock(PropertyOperation.class); @@ -67,9 +64,9 @@ public class AttributeBusinessLogicTest { baseBusinessLogic2.setAccessible(true); baseBusinessLogic2.set(attributeBusinessLogic, componentsUtils); - baseBusinessLogic3 = attributeBusinessLogic.getClass().getSuperclass().getDeclaredField("titanDao"); + baseBusinessLogic3 = attributeBusinessLogic.getClass().getSuperclass().getDeclaredField("janusGraphDao"); baseBusinessLogic3.setAccessible(true); - baseBusinessLogic3.set(attributeBusinessLogic, titanDao); + baseBusinessLogic3.set(attributeBusinessLogic, janusGraphDao); baseBusinessLogic = attributeBusinessLogic.getClass().getSuperclass().getDeclaredField("toscaOperationFacade"); baseBusinessLogic.setAccessible(true); @@ -185,7 +182,7 @@ public class AttributeBusinessLogicTest { Map data=new HashMap<>(); data.put("ONE",new DataTypeDefinition()); - Either, TitanOperationStatus> allDataTypes = Either.left(data); + Either, JanusGraphOperationStatus> allDataTypes = Either.left(data); when(applicationDataTypeCache.getAll()).thenReturn(allDataTypes); when(propertyOperation.isPropertyDefaultValueValid(anyObject(),anyObject())).thenReturn(true); @@ -301,7 +298,7 @@ public class AttributeBusinessLogicTest { Map data=new HashMap<>(); data.put("ONE",new DataTypeDefinition()); - Either, TitanOperationStatus> allDataTypes = Either.left(data); + Either, JanusGraphOperationStatus> allDataTypes = Either.left(data); when(applicationDataTypeCache.getAll()).thenReturn(allDataTypes); when(propertyOperation.isPropertyDefaultValueValid(anyObject(),anyObject())).thenReturn(true); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogicTest.java index 55b87f41cf..b75d52cb42 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogicTest.java @@ -28,8 +28,8 @@ import org.openecomp.sdc.be.components.validation.CapabilitiesValidation; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -45,8 +45,8 @@ 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.jsontitan.operations.CapabilitiesOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.CapabilitiesOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; import org.openecomp.sdc.be.user.Role; @@ -76,7 +76,7 @@ public class CapabilitiesBusinessLogicTest { private final String componentId = "resourceId1"; private final String capabilityId = "uniqueId1"; - private final TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + private final JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class); private final UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); private final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); private final UserValidations userValidations = Mockito.mock(UserValidations.class); @@ -127,13 +127,13 @@ public class CapabilitiesBusinessLogicTest { "0", "10")))); when(capabilitiesOperation.deleteCapabilities( anyObject(), anyString())) .thenReturn(StorageOperationStatus.OK); - when(mockTitanDao.commit()).thenReturn(TitanOperationStatus.OK); + when(mockJanusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK); capabilitiesBusinessLogicMock = new CapabilitiesBusinessLogic(); capabilitiesBusinessLogicMock.setComponentsUtils(componentsUtils); capabilitiesBusinessLogicMock.setUserAdmin(mockUserAdmin); capabilitiesBusinessLogicMock.setGraphLockOperation(graphLockOperation); - capabilitiesBusinessLogicMock.setTitanGenericDao(mockTitanDao); + capabilitiesBusinessLogicMock.setJanusGraphGenericDao(mockJanusGraphDao); capabilitiesBusinessLogicMock.setToscaOperationFacade(toscaOperationFacade); capabilitiesBusinessLogicMock.setUserValidations(userValidations); capabilitiesBusinessLogicMock.setCapabilitiesOperation(capabilitiesOperation); @@ -178,7 +178,7 @@ public class CapabilitiesBusinessLogicTest { } @Test - public void shouldFailCreateCapabilitiesWhenOperationFailedInTitan(){ + public void shouldFailCreateCapabilitiesWhenOperationFailedInJanusGraph(){ List capabilityDefinitions = createMockCapabilityListToReturn( createCapability("capName2", "capDesc", "capType", "source1", "0", "10")); @@ -274,7 +274,7 @@ public class CapabilitiesBusinessLogicTest { } @Test - public void shouldFailUpdateCapabilitiesWhenOperationFailedInTitan(){ + public void shouldFailUpdateCapabilitiesWhenOperationFailedInJanusGraph(){ List capabilityDefinitions = createMockCapabilityListToReturn( createCapability("capName2", "capDesc", "capType", "source1", "0", "10")); @@ -312,7 +312,7 @@ public class CapabilitiesBusinessLogicTest { } @Test - public void shouldFailDeleteCapabilitiesWhenOperationFailedInTitan(){ + public void shouldFailDeleteCapabilitiesWhenOperationFailedInJanusGraph(){ Resource resource = createComponent(true); resource.setComponentType(ComponentTypeEnum.RESOURCE); validateUserRoles(Role.ADMIN, Role.DESIGNER); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java index 00c172e8e6..66d7225360 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java @@ -30,7 +30,7 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -54,7 +54,7 @@ import static org.mockito.Mockito.when; public class CapabilityTypeImportManagerTest { private static final CapabilityTypeOperation capabilityTypeOperation = mock(CapabilityTypeOperation.class); private static final ComponentsUtils componentsUtils = mock(ComponentsUtils.class); - private static final TitanGenericDao titanGenericDao = mock(TitanGenericDao.class); + private static final JanusGraphGenericDao JANUS_GRAPH_GENERIC_DAO = mock(JanusGraphGenericDao.class); private static final PropertyOperation propertyOperation = mock(PropertyOperation.class); private CommonImportManager commonImportManager = new CommonImportManager(componentsUtils, propertyOperation); private CapabilityTypeImportManager manager = new CapabilityTypeImportManager(capabilityTypeOperation, commonImportManager); @@ -69,7 +69,7 @@ public class CapabilityTypeImportManagerTest { }); - when(propertyOperation.getTitanGenericDao()).thenReturn(titanGenericDao); + when(propertyOperation.getJanusGraphGenericDao()).thenReturn(JANUS_GRAPH_GENERIC_DAO); when(capabilityTypeOperation.getCapabilityType(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CommonImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CommonImportManagerTest.java index 15eeb31f48..3402a5b637 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CommonImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CommonImportManagerTest.java @@ -10,7 +10,7 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -34,7 +34,7 @@ public class CommonImportManagerTest { @Mock PropertyOperation propertyOperation; @Mock - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; @Mock private Function> validator; @@ -51,7 +51,7 @@ public class CommonImportManagerTest { public void startUp() { commonImportManager = new CommonImportManager(componentsUtils, propertyOperation); - when(propertyOperation.getTitanGenericDao()).thenReturn(titanGenericDao); + when(propertyOperation.getJanusGraphGenericDao()).thenReturn(janusGraphGenericDao); } @Test @@ -71,7 +71,7 @@ public class CommonImportManagerTest { verify(elementAdder, never()).apply(Mockito.any()); verify(elementUpgrader, never()).apply(Mockito.any(), Mockito.any()); - verify(titanGenericDao).rollback(); + verify(janusGraphGenericDao).rollback(); } @Test @@ -91,7 +91,7 @@ public class CommonImportManagerTest { verify(elementAdder, never()).apply(Mockito.any()); verify(elementUpgrader, never()).apply(Mockito.any(), Mockito.any()); - verify(titanGenericDao).rollback(); + verify(janusGraphGenericDao).rollback(); } @Test @@ -114,7 +114,7 @@ public class CommonImportManagerTest { verify(elementAdder, never()).apply(Mockito.any()); verify(elementUpgrader, never()).apply(Mockito.any(), Mockito.any()); - verify(titanGenericDao).rollback(); + verify(janusGraphGenericDao).rollback(); } @Test @@ -139,7 +139,7 @@ public class CommonImportManagerTest { verify(elementAdder).apply(type1); verify(elementUpgrader, never()).apply(Mockito.any(), Mockito.any()); - verify(titanGenericDao).rollback(); + verify(janusGraphGenericDao).rollback(); } @@ -160,7 +160,7 @@ public class CommonImportManagerTest { verify(elementAdder).apply(type1); verify(elementUpgrader, never()).apply(Mockito.any(), Mockito.any()); - verify(titanGenericDao).commit(); + verify(janusGraphGenericDao).commit(); assertEquals(type1, result.left().value().get(0).getLeft()); assertEquals(true, result.left().value().get(0).getRight()); @@ -189,7 +189,7 @@ public class CommonImportManagerTest { verify(elementAdder, never()).apply(Mockito.any()); verify(elementUpgrader).apply(type1_1, type1); - verify(titanGenericDao).rollback(); + verify(janusGraphGenericDao).rollback(); } @Test @@ -209,7 +209,7 @@ public class CommonImportManagerTest { verify(elementAdder, never()).apply(Mockito.any()); verify(elementUpgrader).apply(type1_1, type1); - verify(titanGenericDao).commit(); + verify(janusGraphGenericDao).commit(); assertEquals(type1_1, result.left().value().get(0).getLeft()); assertEquals(true, result.left().value().get(0).getRight()); @@ -232,7 +232,7 @@ public class CommonImportManagerTest { verify(elementAdder, never()).apply(Mockito.any()); verify(elementUpgrader).apply(type1_1, type1); - verify(titanGenericDao).commit(); + verify(janusGraphGenericDao).commit(); assertEquals(type1_1, result.left().value().get(0).getLeft()); assertEquals(false, result.left().value().get(0).getRight()); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java index 50bb276c97..ad5ddafe0e 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java @@ -46,9 +46,9 @@ import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.*; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; @@ -74,16 +74,14 @@ import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ForwardingPathOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.function.BiPredicate; - import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; @@ -94,7 +92,6 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.when; /** * The test suite designed for test functionality of ComponentInstanceBusinessLogic class @@ -143,7 +140,7 @@ public class ComponentInstanceBusinessLogicTest { @Mock private UserValidations userValidations; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private ArtifactsBusinessLogic artifactBusinessLogic; @Mock @@ -716,8 +713,8 @@ public class ComponentInstanceBusinessLogicTest { // default test testSubject = createTestSubject(); - TitanDao mock = Mockito.mock(TitanDao.class); - testSubject.setTitanGenericDao(mock); + JanusGraphDao mock = Mockito.mock(JanusGraphDao.class); + testSubject.setJanusGraphGenericDao(mock); result = testSubject.deleteComponentInstance(containerComponentParam, containerComponentId, componentInstanceId, userId); } @@ -1203,7 +1200,7 @@ public class ComponentInstanceBusinessLogicTest { when(toscaOperationFacade.getToscaElement(containerComponentId)).thenReturn(leftServiceOp); when(toscaOperationFacade.getToscaElement(eq(containerComponentId), any(ComponentParametersView.class))) .thenReturn(leftServiceOp); - when(titanDao.rollback()).thenReturn(TitanOperationStatus.OK); + when(janusGraphDao.rollback()).thenReturn(JanusGraphOperationStatus.OK); when(graphLockOperation.unlockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service))) .thenReturn(StorageOperationStatus.OK); when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service))) @@ -1231,7 +1228,7 @@ public class ComponentInstanceBusinessLogicTest { when(toscaOperationFacade.getToscaElement(containerComponentId)).thenReturn(leftServiceOp); when(toscaOperationFacade.getToscaElement(eq(containerComponentId), any(ComponentParametersView.class))) .thenReturn(leftServiceOp); - when(titanDao.rollback()).thenReturn(TitanOperationStatus.OK); + when(janusGraphDao.rollback()).thenReturn(JanusGraphOperationStatus.OK); when(graphLockOperation.unlockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service))) .thenReturn(StorageOperationStatus.OK); when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service))) @@ -1460,7 +1457,7 @@ public class ComponentInstanceBusinessLogicTest { .thenReturn(result2); when(toscaOperationFacade.getToscaElement(eq(service.getUniqueId()), any(ComponentParametersView.class))) .thenReturn(cont); - when(titanDao.commit()).thenReturn(TitanOperationStatus.OK); + when(janusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK); result = componentInstanceBusinessLogic .batchDeleteComponentInstance(containerComponentParam, containerComponentId, diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/DataTypeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/DataTypeBusinessLogicTest.java index 9219de1aac..d6b59205aa 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/DataTypeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/DataTypeBusinessLogicTest.java @@ -46,7 +46,7 @@ import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.user.IUserBusinessLogic; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/DataTypesServiceTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/DataTypesServiceTest.java index 5cf3ef3a95..f53d2f9094 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/DataTypesServiceTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/DataTypesServiceTest.java @@ -4,14 +4,12 @@ import fj.data.Either; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; + import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyObject; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import org.mockito.Mockito; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; @@ -26,8 +24,8 @@ public class DataTypesServiceTest { DataTypesService dataTypesService = new DataTypesService(componentsUtils); Map mapreturn = new HashMap<>(); - TitanOperationStatus titanOperationStatus = TitanOperationStatus.NOT_FOUND; - Either, TitanOperationStatus> allDataTypes; + JanusGraphOperationStatus janusGraphOperationStatus = JanusGraphOperationStatus.NOT_FOUND; + Either, JanusGraphOperationStatus> allDataTypes; @Before public void setup() { @@ -44,7 +42,7 @@ public class DataTypesServiceTest { @Test public void getAllDataTypes_failure() { - allDataTypes = Either.right(titanOperationStatus); + allDataTypes = Either.right(janusGraphOperationStatus); when(applicationDataTypeCache.getAll()).thenReturn(allDataTypes); Assert.assertEquals(true,dataTypesService.getAllDataTypes(applicationDataTypeCache).isRight()); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java index d445c9c88c..75355b984b 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java @@ -13,12 +13,12 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; @@ -32,7 +32,7 @@ import org.openecomp.sdc.be.model.User; 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.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.ElementOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; @@ -73,13 +73,13 @@ public class ElementBLTest { private Resource notDeletedResource = new Resource(); @Mock - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; @Mock private ToscaOperationFacade toscaOperationFacade; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private UserValidations userValidations; @@ -109,7 +109,7 @@ public class ElementBLTest { initServicesList(); initResourceslist(); - when(titanDao.commit()).thenReturn(TitanOperationStatus.OK); + when(janusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK); } private void initCategoriesList() { @@ -158,9 +158,10 @@ public class ElementBLTest { public void testFetchElementsByCategoryName_filterDeleted() { ArgumentCaptor criteriaCapture = ArgumentCaptor.forClass(Map.class); - when(titanGenericDao.getByCriteria(eq(NodeTypeEnum.ServiceNewCategory), criteriaCapture.capture(), eq(CategoryData.class))) + when(janusGraphGenericDao + .getByCriteria(eq(NodeTypeEnum.ServiceNewCategory), criteriaCapture.capture(), eq(CategoryData.class))) .thenReturn(Either.left(categories)); - when(titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ServiceNewCategory), + when(janusGraphGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ServiceNewCategory), CATEGORY_UNIQUE_ID, GraphEdgeLabels.CATEGORY, NodeTypeEnum.Service, ServiceMetadataData.class)) .thenReturn(Either.left(services)); when(toscaOperationFacade.getToscaElement(SERVICE_NOT_DELETED_ID, JsonParseFlagEnum.ParseMetadata)) @@ -185,7 +186,7 @@ public class ElementBLTest { @Test public void testFetchResourcesBySubcategoryUid_filterDeleted() { - when(titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceSubcategory), + when(janusGraphGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceSubcategory), CATEGORY_UNIQUE_ID, GraphEdgeLabels.CATEGORY, NodeTypeEnum.Resource, ResourceMetadataData.class)) .thenReturn(Either.left(resources)); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogicTest.java index 6d30003810..6f97621d74 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogicTest.java @@ -39,7 +39,7 @@ import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponent import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -50,7 +50,7 @@ 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.category.SubCategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.user.Role; @@ -78,7 +78,7 @@ public class ElementBusinessLogicTest { private UserBusinessLogic userAdminManager; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private UserValidations userValidations; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicTest.java index 2ddfcb497a..6024462292 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicTest.java @@ -42,8 +42,8 @@ import org.openecomp.sdc.be.components.validation.AccessValidations; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -56,9 +56,9 @@ import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.model.GroupInstanceProperty; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; -import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; @@ -109,7 +109,7 @@ public class GroupBusinessLogicTest { @Mock private PropertyOperation propertyOperation; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock PolicyTargetsUpdateHandler policyTargetsUpdateHandler; @@ -125,7 +125,7 @@ public class GroupBusinessLogicTest { List groupDefinitions = new ArrayList<>(); GroupDefinition groupDefinition = new GroupDefinition(); groupDefinitions.add(groupDefinition); - when(dataTypeCache.getAll()).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); + when(dataTypeCache.getAll()).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); result = test.createGroups(component, groupDefinitions, true); Assert.assertTrue(result.isRight()); } @@ -277,7 +277,7 @@ public class GroupBusinessLogicTest { when(accessValidations.validateUserCanWorkOnComponent("compid", ComponentTypeEnum.SERVICE, "USR01", "DeleteGroup")).thenReturn(component); when(groupsOperation.deleteGroups(anyObject(),anyList())).thenReturn(Either.right(StorageOperationStatus.ARTIFACT_NOT_FOUND)); - when(titanDao.rollback()).thenReturn(TitanOperationStatus.OK); + when(janusGraphDao.rollback()).thenReturn(JanusGraphOperationStatus.OK); GroupDefinition Gdefinition = test.deleteGroup("compid", ComponentTypeEnum.SERVICE, "GRP.01", "USR01"); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java index ffeb80ec00..9d7ca19eb5 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java @@ -28,30 +28,21 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import fj.data.Either; -import java.util.Arrays; -import java.util.Optional; -import org.apache.commons.lang3.tuple.ImmutablePair; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.components.property.PropertyDeclarationOrchestrator; import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -71,14 +62,22 @@ 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.cache.ApplicationDataTypeCache; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.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.GraphLockOperation; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.be.user.IUserBusinessLogic; import org.openecomp.sdc.exception.ResponseFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + public class InputsBusinessLogicTest { private static final String COMPONENT_INSTANCE_ID = "instanceId"; @@ -120,7 +119,7 @@ public class InputsBusinessLogicTest { private PropertyOperation propertyOperation; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private DataTypeBusinessLogic dataTypeBusinessLogic; @@ -251,7 +250,7 @@ public class InputsBusinessLogicTest { when(propertyDeclarationOrchestrator.declarePropertiesToInputs(any(), any())).thenReturn(Either.left( declaredPropertiesToInputs)); when(toscaOperationFacadeMock.addInputsToComponent(any(), any())).thenReturn(Either.left(declaredPropertiesToInputs)); - when(titanDao.commit()).thenReturn(TitanOperationStatus.OK); + when(janusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK); when(graphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); when(graphLockOperation.unlockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); when(componentInstanceBusinessLogic.setInputConstraint(any())).thenReturn(Collections.emptyList()); @@ -456,7 +455,7 @@ public class InputsBusinessLogicTest { // for createListInputsInGraph: when(toscaOperationFacadeMock.addInputsToComponent(anyMap(), eq(COMPONENT_ID))).thenReturn(Either.left(Arrays.asList(listInput))); // for rollback/commit: - when(titanDao.commit()).thenReturn(TitanOperationStatus.OK); + when(janusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK); // for unlock resource when(graphLockOperation.unlockComponent(COMPONENT_ID, NodeTypeEnum.Service)).thenReturn(StorageOperationStatus.OK); @@ -510,7 +509,7 @@ public class InputsBusinessLogicTest { when(graphLockOperation.lockComponent(COMPONENT_ID, NodeTypeEnum.Service)).thenReturn(StorageOperationStatus.OK); when(toscaOperationFacadeMock.addDataTypesToComponent(dataTypesMapCaptor.capture(), eq(COMPONENT_ID))).thenReturn(Either.left(new ArrayList<>())); when(propertyDeclarationOrchestrator.getPropOwnerId(componentInstInputsMap)).thenReturn(COMPONENT_INSTANCE_ID); - when(applicationDataTypeCache.getAll()).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); + when(applicationDataTypeCache.getAll()).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); when(componentsUtilsMock.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY)).thenReturn(new ResponseFormat()); Either, ResponseFormat> result = diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogicTest.java index d5b1f06b82..42eca256a2 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogicTest.java @@ -44,8 +44,8 @@ import org.openecomp.sdc.be.components.validation.InterfaceOperationValidation; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -57,9 +57,9 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations; -import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.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.InterfaceLifecycleOperation; @@ -89,7 +89,7 @@ public class InterfaceOperationBusinessLogicTest { @Mock private IGraphLockOperation graphLockOperation; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private InterfaceLifecycleOperation interfaceLifecycleOperation; @Mock @@ -122,7 +122,7 @@ public class InterfaceOperationBusinessLogicTest { when(interfaceOperationValidation .validateDeleteOperationContainsNoMappedOutput(any(), any(), any())) .thenReturn(Either.left(true)); - when(titanDao.commit()).thenReturn(TitanOperationStatus.OK); + when(janusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK); } private List createInputsForResource() { @@ -432,7 +432,7 @@ public class InterfaceOperationBusinessLogicTest { @Test public void getInterfaceOperationTestFailOnException() { - when(titanDao.commit()).thenThrow(new RuntimeException()); + when(janusGraphDao.commit()).thenThrow(new RuntimeException()); Assert.assertTrue(interfaceOperationBusinessLogic.getInterfaceOperation(resourceId, interfaceId, Collections.singletonList(operationId), user, true).isRight()); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java index e55578c989..d5abdabec3 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java @@ -51,8 +51,8 @@ import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -72,8 +72,8 @@ 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.cache.ApplicationDataTypeCache; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.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.PolicyTypeOperation; @@ -98,7 +98,7 @@ public class PolicyBusinessLogicTest { @Mock private UserValidations userValidations; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private ApplicationDataTypeCache dataTypeCache; @Mock @@ -144,7 +144,7 @@ public class PolicyBusinessLogicTest { public void initBl() { businessLogic.setComponentsUtils(componentsUtils); businessLogic.setToscaOperationFacade(toscaOperationFacade); - businessLogic.setTitanGenericDao(titanDao); + businessLogic.setJanusGraphGenericDao(janusGraphDao); businessLogic.setUserValidations(userValidations); businessLogic.setGraphLockOperation(graphLockOperation); businessLogic.setPolicyTypeOperation(policyTypeOperation); @@ -452,11 +452,11 @@ public class PolicyBusinessLogicTest { } private void stubCommit() { - when(titanDao.commit()).thenReturn(TitanOperationStatus.OK); + when(janusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK); } private void stubRollback() { - when(titanDao.rollback()).thenReturn(TitanOperationStatus.OK); + when(janusGraphDao.rollback()).thenReturn(JanusGraphOperationStatus.OK); } private void stubUnlockAndCommit() { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java index 04f0a58ebf..3b9a43af28 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java @@ -45,7 +45,7 @@ import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -55,7 +55,7 @@ import org.openecomp.sdc.be.model.PolicyDefinition; 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.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; @@ -73,7 +73,7 @@ public class PolicyPropertiesBusinessLogicTest { private UserValidations userValidations; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private ToscaOperationFacade toscaOperationFacade; @@ -90,7 +90,7 @@ public class PolicyPropertiesBusinessLogicTest { @Before public void setUp() throws Exception { testInstance.setUserValidations(userValidations); - testInstance.setTitanGenericDao(titanDao); + testInstance.setJanusGraphGenericDao(janusGraphDao); testInstance.setToscaOperationFacade(toscaOperationFacade); testInstance.setComponentsUtils(componentsUtils); @@ -121,7 +121,7 @@ public class PolicyPropertiesBusinessLogicTest { @After public void tearDown() { - verify(titanDao).commit(); + verify(janusGraphDao).commit(); } @Test diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java index db74b2d2ed..d9be41136d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java @@ -34,7 +34,7 @@ import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponent import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.PolicyTypeDefinition; import org.openecomp.sdc.be.model.User; @@ -63,7 +63,7 @@ public class PolicyTypeBusinessLogicTest { @InjectMocks private PolicyTypeBusinessLogic testInstance; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private PolicyTypeOperation policyTypeOperation; @Mock diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogicTest.java index e8d7300733..dd523b8b36 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogicTest.java @@ -36,7 +36,7 @@ import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.components.validation.ValidationUtils; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.datatypes.elements.ProductMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -48,7 +48,7 @@ import org.openecomp.sdc.be.model.User; 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.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; 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.StorageOperationStatus; @@ -87,7 +87,7 @@ public class ProductBusinessLogicTest { private ToscaOperationFacade toscaOperationFacade; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private ValidationUtils validationUtils; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogicTest.java index 3cac5f5b15..da726505af 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogicTest.java @@ -28,8 +28,8 @@ import org.openecomp.sdc.be.components.validation.RequirementValidation; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -42,8 +42,8 @@ import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.RequirementOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.RequirementOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; import org.openecomp.sdc.be.user.Role; @@ -73,7 +73,7 @@ public class RequirementBusinessLogicTest { private final String componentId = "resourceId1"; private final String requirementId = "uniqueId1"; - private final TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + private final JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class); private final UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); private final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); private final UserValidations userValidations = Mockito.mock(UserValidations.class); @@ -124,14 +124,14 @@ public class RequirementBusinessLogicTest { "0", "10")))); when(requirementOperation.deleteRequirements( anyObject(), anyString())) .thenReturn(StorageOperationStatus.OK); - when(mockTitanDao.commit()).thenReturn(TitanOperationStatus.OK); + when(mockJanusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK); requirementsBusinessLogicMock = new RequirementBusinessLogic(); requirementsBusinessLogicMock.setComponentsUtils(componentsUtils); requirementsBusinessLogicMock.setUserAdmin(mockUserAdmin); requirementsBusinessLogicMock.setGraphLockOperation(graphLockOperation); - requirementsBusinessLogicMock.setTitanGenericDao(mockTitanDao); + requirementsBusinessLogicMock.setJanusGraphGenericDao(mockJanusGraphDao); requirementsBusinessLogicMock.setToscaOperationFacade(toscaOperationFacade); requirementsBusinessLogicMock.setUserValidations(userValidations); requirementsBusinessLogicMock.setRequirementOperation(requirementOperation); @@ -265,7 +265,7 @@ public class RequirementBusinessLogicTest { } @Test - public void shouldFailUpdateRequirementWhenOperationFailedInTitan(){ + public void shouldFailUpdateRequirementWhenOperationFailedInJanusGraph(){ List requirementDefinitions = createMockRequirementListToReturn( createRequirement("reqName", "capType", "node", "source1", "6", "11")); @@ -287,7 +287,7 @@ public class RequirementBusinessLogicTest { @Test - public void shouldFailDeleteRequirementWhenOperationFailedInTitan(){ + public void shouldFailDeleteRequirementWhenOperationFailedInJanusGraph(){ Resource resource = createComponent(true); resource.setComponentType(ComponentTypeEnum.RESOURCE); validateUserRoles(Role.ADMIN, Role.DESIGNER); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java index 9b5387c7b9..5844047784 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java @@ -45,8 +45,8 @@ import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; @@ -62,10 +62,10 @@ 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.cache.ApplicationDataTypeCache; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTypeOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; @@ -143,7 +143,7 @@ public class ResourceBusinessLogicTest { final ServletContext servletContext = Mockito.mock(ServletContext.class); IElementOperation mockElementDao; - TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class); UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class); @@ -242,7 +242,7 @@ public class ResourceBusinessLogicTest { when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate); Map emptyDataTypes = new HashMap<>(); when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes)); - when(mockTitanDao.commit()).thenReturn(TitanOperationStatus.OK); + when(mockJanusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK); // BL object artifactManager.setNodeTemplateOperation(nodeTemplateOperation); @@ -255,7 +255,7 @@ public class ResourceBusinessLogicTest { bl.setGraphLockOperation(graphLockOperation); bl.setArtifactsManager(artifactManager); bl.setPropertyOperation(propertyOperation); - bl.setTitanGenericDao(mockTitanDao); + bl.setJanusGraphGenericDao(mockJanusGraphDao); bl.setApplicationDataTypeCache(applicationDataTypeCache); bl.setCacheManagerOperation(cacheManager); bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); 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 e54ac699db..67f7e2d5b2 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 @@ -31,7 +31,7 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.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.UniqueIdBuilder; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicTest.java index 5c539477d5..c8e3fd9a22 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogicTest.java @@ -37,14 +37,14 @@ import org.openecomp.sdc.be.components.validation.UserValidations; 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.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; 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.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; 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; @@ -75,9 +75,7 @@ import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; public class ServiceBusinessLogicTest { @@ -93,7 +91,7 @@ public class ServiceBusinessLogicTest { private AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class); private ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class); private GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); - private TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + private JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class); private ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); private CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); @@ -168,7 +166,7 @@ public class ServiceBusinessLogicTest { bl.setUserAdmin(mockUserAdmin); bl.setArtifactBl(artifactBl); bl.setGraphLockOperation(graphLockOperation); - bl.setTitanGenericDao(mockTitanDao); + bl.setJanusGraphGenericDao(mockJanusGraphDao); bl.setToscaOperationFacade(toscaOperationFacade); bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); bl.setComponentsUtils(componentsUtils); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java index 6f23faa25b..a37feb950e 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java @@ -11,7 +11,7 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; 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.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.exception.ResponseFormat; import java.util.Arrays; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperationTest.java index 7cad89c2ec..e12bfb445f 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperationTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperationTest.java @@ -20,7 +20,7 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import java.util.ArrayList; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperationTest.java index dbacd82e74..3819175c30 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperationTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperationTest.java @@ -17,7 +17,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import java.util.List; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandlerTest.java index 82bf7612df..2723746ae4 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandlerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandlerTest.java @@ -36,7 +36,7 @@ import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import java.util.List; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/YamlTemplateParsingHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/YamlTemplateParsingHandlerTest.java index 151303fa26..347c95217d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/YamlTemplateParsingHandlerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/YamlTemplateParsingHandlerTest.java @@ -44,7 +44,7 @@ import org.openecomp.sdc.be.components.csar.YamlTemplateParsingHandler; import org.openecomp.sdc.be.components.impl.AnnotationBusinessLogic; import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic; import org.openecomp.sdc.be.components.validation.AnnotationValidator; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations; @@ -59,7 +59,7 @@ public class YamlTemplateParsingHandlerTest { @Mock private AnnotationValidator annotationValidator; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Mock private User user; @@ -103,7 +103,7 @@ public class YamlTemplateParsingHandlerTest { AnnotationBusinessLogic annotationBusinessLogic = new AnnotationBusinessLogic(annotationTypeOperations, annotationValidator); - handler = new YamlTemplateParsingHandler(titanDao, groupTypeBusinessLogic, annotationBusinessLogic); + handler = new YamlTemplateParsingHandler(janusGraphDao, groupTypeBusinessLogic, annotationBusinessLogic); stubGetGroupType(); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java index d85226d64d..f8401e8aa5 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java @@ -49,15 +49,18 @@ public class CertificationChangeTransitionTest extends LifecycleTestBase { super.setup(); // checkout transition object - certifyTransitionObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + certifyTransitionObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, + janusGraphDao); certifyTransitionObj.setConfigurationManager(configurationManager); certifyTransitionObj.setLifeCycleOperation(toscaElementLifecycleOperation); - certificationCancelObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + certificationCancelObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, + janusGraphDao); certificationCancelObj.setConfigurationManager(configurationManager); certificationCancelObj.setLifeCycleOperation(toscaElementLifecycleOperation); - certificationFailObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + certificationFailObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, + janusGraphDao); certificationFailObj.setConfigurationManager(configurationManager); certificationFailObj.setLifeCycleOperation(toscaElementLifecycleOperation); @@ -74,7 +77,8 @@ public class CertificationChangeTransitionTest extends LifecycleTestBase { User user = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null); for (LifeCycleTransitionEnum value : LifeCycleTransitionEnum.values()) { - new CertificationChangeTransition(value, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + new CertificationChangeTransition(value, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, + janusGraphDao); } } 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 3a686e5a33..70833f40b6 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 @@ -33,8 +33,8 @@ import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.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.tosca.ToscaExportHandler; @@ -66,7 +66,8 @@ public class CertificationRequestTest extends LifecycleTestBase { @Before public void setup() { super.setup(); - rfcObj = new CertificationRequestTransition(componentsUtils, toscaElementLifecycleOperation, serviceBusinessLogic, toscaOperationFacade, titanDao); + rfcObj = new CertificationRequestTransition(componentsUtils, toscaElementLifecycleOperation, serviceBusinessLogic, toscaOperationFacade, + janusGraphDao); rfcObj.setConfigurationManager(configurationManager); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransitionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransitionTest.java index 0f18de2ce5..48b79eafd3 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransitionTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransitionTest.java @@ -26,14 +26,14 @@ import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; 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.TitanGraphClient; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.exception.ResponseFormat; @@ -48,7 +48,7 @@ public class CertificationRequestTransitionTest extends LifecycleTestBase { private CertificationRequestTransition createTestSubject() { return new CertificationRequestTransition( new ComponentsUtils(new AuditingManager(new AuditingDao(), new AuditCassandraDao(), new TestConfigurationProvider())), - new ToscaElementLifecycleOperation(), new ServiceBusinessLogic(), new ToscaOperationFacade(), new TitanDao(new TitanGraphClient())); + new ToscaElementLifecycleOperation(), new ServiceBusinessLogic(), new ToscaOperationFacade(), new JanusGraphDao(new JanusGraphClient())); } @Test diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java index d6bf92fb98..7e1310dff0 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java @@ -44,7 +44,8 @@ public class CheckinTest extends LifecycleTestBase { super.setup(); // checkout transition object - checkinObj = new CheckinTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + checkinObj = new CheckinTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, + janusGraphDao); checkinObj.setLifeCycleOperation(toscaElementLifecycleOperation); checkinObj.setConfigurationManager(configurationManager); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java index 4097f7aa79..8f5362a12d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java @@ -48,7 +48,8 @@ public class CheckoutTest extends LifecycleTestBase { super.setup(); // checkout transition object - checkoutObj = new CheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + checkoutObj = new CheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, + janusGraphDao); checkoutObj.setLifeCycleOperation(toscaElementLifecycleOperation); checkoutObj.setConfigurationManager(configurationManager); bl.setToscaOperationFacade(toscaOperationFacade); 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 9cdeaec721..e2432ce584 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 @@ -31,18 +31,18 @@ import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; 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.*; -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.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.user.Role; @@ -76,7 +76,7 @@ public class LifecycleTestBase { protected Service serviceResponse; protected static ConfigurationManager configurationManager = null; protected ResponseFormatManager responseManager = null; - protected TitanDao titanDao = Mockito.mock(TitanDao.class); + protected JanusGraphDao janusGraphDao = Mockito.mock(JanusGraphDao.class); protected ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); protected static ComponentsUtils componentsUtils; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java index 3d3bb24432..ac43c535c1 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java @@ -43,7 +43,8 @@ public class UndoCheckoutTest extends LifecycleTestBase { super.setup(); // checkout transition object - undoCheckoutObj = new UndoCheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + undoCheckoutObj = new UndoCheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, + janusGraphDao); undoCheckoutObj.setLifeCycleOperation(toscaElementLifecycleOperation); undoCheckoutObj.setConfigurationManager(configurationManager); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java index 89b82b91d2..5f1ddd2563 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java @@ -14,7 +14,7 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import java.util.List; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java index ed554d20f5..2eb45df6f1 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java @@ -13,7 +13,7 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import static org.junit.Assert.*; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/group/ComponentGroupMergeCommandTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/group/ComponentGroupMergeCommandTest.java index 26b0034704..e8b2535f88 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/group/ComponentGroupMergeCommandTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/group/ComponentGroupMergeCommandTest.java @@ -19,7 +19,7 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; import java.util.List; import java.util.Map; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/group/GroupPropertiesMergeCommandTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/group/GroupPropertiesMergeCommandTest.java index b815251ea1..ef20068397 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/group/GroupPropertiesMergeCommandTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/group/GroupPropertiesMergeCommandTest.java @@ -18,7 +18,7 @@ import org.openecomp.sdc.be.datatypes.enums.CreatedFrom; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; import java.util.List; import java.util.stream.Stream; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/BaseComponentInputsMerge.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/BaseComponentInputsMerge.java index e1d4d39e52..bbeae6db75 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/BaseComponentInputsMerge.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/BaseComponentInputsMerge.java @@ -9,7 +9,7 @@ import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import java.util.List; import java.util.Map; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBLTest.java index 817aa5dde3..3506959db4 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBLTest.java @@ -17,7 +17,7 @@ import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import java.util.Arrays; import java.util.List; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java index d4d79b94ce..19181c97a1 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java @@ -10,7 +10,7 @@ import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.exception.ResponseFormat; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java index af6b72ef5d..65783fd13d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java @@ -21,7 +21,7 @@ import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.impl.ExternalConfiguration; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsRedeclareHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsRedeclareHandlerTest.java index f94906b90e..8385ea8f90 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsRedeclareHandlerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsRedeclareHandlerTest.java @@ -21,7 +21,7 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import java.util.Collections; import java.util.List; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInterfacesMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInterfacesMergeTest.java index 69caa8e389..5e4fb9ee1a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInterfacesMergeTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInterfacesMergeTest.java @@ -24,7 +24,7 @@ import org.openecomp.sdc.be.model.ComponentInstanceInterface; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.api.UserRoleEnum; import org.openecomp.sdc.test.utils.InterfaceOperationTestUtils; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java index c9c9f666dd..38506e1184 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java @@ -9,7 +9,7 @@ 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.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java index c6e5bed950..5d69a82939 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java @@ -9,7 +9,7 @@ import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java index 1b6aa00c69..eef868d86a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java @@ -18,7 +18,7 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ExternalRefsMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ExternalRefsMergeBLTest.java index 65f88358a5..6f1725d062 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ExternalRefsMergeBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ExternalRefsMergeBLTest.java @@ -9,7 +9,7 @@ import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ExternalReferencesOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ExternalReferencesOperation; import javax.annotation.Resource; import java.util.*; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java index 85e4cb2e5b..2cefadab59 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java @@ -13,7 +13,7 @@ import org.openecomp.sdc.be.impl.ForwardingPathUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.common.api.UserRoleEnum; import org.openecomp.sdc.exception.ResponseFormat; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/policy/PoliciesMergeCommandTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/policy/PoliciesMergeCommandTest.java index 5d5ccb0551..228b82149e 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/policy/PoliciesMergeCommandTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/policy/PoliciesMergeCommandTest.java @@ -20,7 +20,7 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import java.util.HashMap; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java index 32edf3e631..54fbdbc113 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java @@ -14,7 +14,7 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import java.util.Collections; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java index 98cd89c9a9..ee43f11231 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java @@ -12,7 +12,7 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import java.util.Collections; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java index ef87dba483..b1585ff254 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java @@ -11,11 +11,11 @@ import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; import org.openecomp.sdc.be.components.utils.GroupDefinitionBuilder; import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.components.utils.ServiceBuilder; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -39,11 +39,11 @@ public class MergeInstanceUtilsTest { private ToscaOperationFacade toscaOperationFacade; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @Before public void startUp() { - ExceptionUtils exceptionUtils = new ExceptionUtils(titanDao); + ExceptionUtils exceptionUtils = new ExceptionUtils(janusGraphDao); mergeInstanceUtils = new MergeInstanceUtils(toscaOperationFacade, exceptionUtils); } @@ -121,7 +121,7 @@ public class MergeInstanceUtilsTest { when(toscaOperationFacade.getToscaElement("inst1Uid")).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); assertThatExceptionOfType(StorageException.class) .isThrownBy(() -> mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, oldVf, "inst1", emptyList())); - verify(titanDao).rollback(); + verify(janusGraphDao).rollback(); } @Test diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java index 0af5915c21..095463b9ca 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java @@ -6,14 +6,14 @@ import org.junit.Before; import org.openecomp.sdc.be.components.BeConfDependentTest; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; -import org.openecomp.sdc.be.components.path.beans.TitanGraphTestSetup; +import org.openecomp.sdc.be.components.path.beans.JanusGraphTestSetup; import org.openecomp.sdc.be.components.path.utils.GraphTestUtils; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanGraphClient; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; @@ -25,7 +25,7 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum; 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.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.tosca.CapabilityRequirementConverter; @@ -48,7 +48,7 @@ public abstract class BaseForwardingPathTest extends BeConfDependentTest impleme private ForwardingPathDataDefinition forwardingPathDataDefinition; @Autowired - protected TitanGraphClient titanGraphClient; + protected JanusGraphClient janusGraphClient; @Autowired protected CapabilityRequirementConverter capabiltyRequirementConvertor; @@ -66,11 +66,11 @@ public abstract class BaseForwardingPathTest extends BeConfDependentTest impleme protected ComponentInstanceBusinessLogic componentInstanceBusinessLogic; @javax.annotation.Resource - protected TitanDao titanDao; + protected JanusGraphDao janusGraphDao; @Before - public void initTitan() { - TitanGraphTestSetup.createGraph(titanGraphClient.getGraph().left().value()); + public void initJanusGraph() { + JanusGraphTestSetup.createGraph(janusGraphClient.getGraph().left().value()); categoryDefinition = new CategoryDefinition(); categoryDefinition.setName(CATEGORY_NAME); } @@ -105,12 +105,13 @@ public abstract class BaseForwardingPathTest extends BeConfDependentTest impleme props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, "org.openecomp.resource.abstract.nodes.service"); - GraphTestUtils.createServiceVertex(titanDao, props); + GraphTestUtils.createServiceVertex(janusGraphDao, props); - GraphVertex resourceVertex = GraphTestUtils.createResourceVertex(titanDao, props, ResourceTypeEnum.PNF); + GraphVertex resourceVertex = GraphTestUtils.createResourceVertex(janusGraphDao, props, ResourceTypeEnum.PNF); resourceVertex.setJsonMetadataField(JsonPresentationFields.VERSION, "0.1"); - Either vertexTitanOperationStatusEither = titanDao.updateVertex(resourceVertex); - assertTrue(vertexTitanOperationStatusEither.isLeft()); + Either vertexJanusGraphOperationStatusEither = janusGraphDao + .updateVertex(resourceVertex); + assertTrue(vertexJanusGraphOperationStatusEither.isLeft()); } private Service createTestService() { @@ -153,7 +154,7 @@ public abstract class BaseForwardingPathTest extends BeConfDependentTest impleme cat.setMetadataProperties(metadataProperties); cat.updateMetadataJsonWithCurrentMetadataProperties(); - Either catRes = titanDao.createVertex(cat); + Either catRes = janusGraphDao.createVertex(cat); assertTrue(catRes.isLeft()); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java index fd9e25f475..eca9986209 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java @@ -14,7 +14,7 @@ import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java index 09e1a72b44..3656caf904 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java @@ -4,7 +4,7 @@ import fj.data.Either; import org.openecomp.sdc.be.impl.ForwardingPathUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @org.springframework.stereotype.Component("tosca-operation-facade") diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryJanusGraphClient.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryJanusGraphClient.java new file mode 100644 index 0000000000..10bd1ab6ca --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryJanusGraphClient.java @@ -0,0 +1,216 @@ +package org.openecomp.sdc.be.components.path.beans; + + +import org.janusgraph.core.*; +import org.janusgraph.core.schema.ConsistencyModifier; +import org.janusgraph.core.schema.JanusGraphIndex; +import org.janusgraph.core.schema.JanusGraphManagement; +import org.janusgraph.core.util.JanusGraphCleanup; +import org.janusgraph.diskstorage.BackendException; +import org.janusgraph.diskstorage.ResourceUnavailableException; +import org.janusgraph.diskstorage.locking.PermanentLockingException; +import org.janusgraph.graphdb.database.idassigner.IDPoolExhaustedException; +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.be.dao.JanusGraphClientStrategy; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.ArrayList; +import java.util.HashMap; + +@Component("janusgraph-client") +public class InMemoryJanusGraphClient extends JanusGraphClient { + + + private static final Logger logger = LoggerFactory.getLogger(InMemoryJanusGraphClient.class); + + private static final String OK = "GOOD"; + + public InMemoryJanusGraphClient() { + } + + + private JanusGraph graph; + JanusGraphClientStrategy janusGraphClientStrategy; + + public InMemoryJanusGraphClient(JanusGraphClientStrategy janusGraphClientStrategy) { + super(); + this.janusGraphClientStrategy = janusGraphClientStrategy; + logger.info("** JanusGraphClient created"); + } + + @PostConstruct + public JanusGraphOperationStatus createGraph() { + + logger.info("** createGraph started **"); + graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open(); + createJanusGraphSchema(); + + logger.info("** in memory graph created"); + return JanusGraphOperationStatus.OK; + + } + + + public void cleanupGraph() { + if (graph != null) { + // graph.shutdown(); + graph.close(); + try { + JanusGraphFactory.drop(graph); + } catch (BackendException e) { + e.printStackTrace(); + } + } + } + + public JanusGraphOperationStatus createGraph(String janusGraphCfgFile) { + logger.info("** open graph with {} started", janusGraphCfgFile); + try { + logger.info("openGraph : try to load file {}", janusGraphCfgFile); + graph = JanusGraphFactory.open(janusGraphCfgFile); + if (graph.isClosed()) { + logger.error("janusgraph graph was not initialized"); + return JanusGraphOperationStatus.NOT_CREATED; + } + + } catch (Exception e) { + this.graph = null; + logger.info("createGraph : failed to open JanusGraph graph with configuration file: {}", janusGraphCfgFile, e); + return JanusGraphOperationStatus.NOT_CONNECTED; + } + + logger.info("** JanusGraph graph created "); + + return JanusGraphOperationStatus.OK; + } + + + public Either getGraph() { + if (graph != null) { + return Either.left(graph); + } else { + return Either.right(JanusGraphOperationStatus.NOT_CREATED); + } + } + + public JanusGraphOperationStatus commit() { + if (graph != null) { + try { + graph.tx().commit(); + return JanusGraphOperationStatus.OK; + } catch (Exception e) { + return handleJanusGraphException(e); + } + } else { + return JanusGraphOperationStatus.NOT_CREATED; + } + } + + public JanusGraphOperationStatus rollback() { + if (graph != null) { + try { + // graph.rollback(); + graph.tx().rollback(); + return JanusGraphOperationStatus.OK; + } catch (Exception e) { + return handleJanusGraphException(e); + } + } else { + return JanusGraphOperationStatus.NOT_CREATED; + } + } + + public static JanusGraphOperationStatus handleJanusGraphException(Exception e) { + if (e instanceof JanusGraphConfigurationException) { + return JanusGraphOperationStatus.JANUSGRAPH_CONFIGURATION; + } + if (e instanceof SchemaViolationException) { + return JanusGraphOperationStatus.JANUSGRAPH_SCHEMA_VIOLATION; + } + if (e instanceof PermanentLockingException) { + return JanusGraphOperationStatus.JANUSGRAPH_SCHEMA_VIOLATION; + } + if (e instanceof IDPoolExhaustedException) { + return JanusGraphOperationStatus.GENERAL_ERROR; + } + if (e instanceof InvalidElementException) { + return JanusGraphOperationStatus.INVALID_ELEMENT; + } + if (e instanceof InvalidIDException) { + return JanusGraphOperationStatus.INVALID_ID; + } + if (e instanceof QueryException) { + return JanusGraphOperationStatus.INVALID_QUERY; + } + if (e instanceof ResourceUnavailableException) { + return JanusGraphOperationStatus.RESOURCE_UNAVAILABLE; + } + if (e instanceof IllegalArgumentException) { + // TODO check the error message?? + return JanusGraphOperationStatus.ILLEGAL_ARGUMENT; + } + + return JanusGraphOperationStatus.GENERAL_ERROR; + } + + public boolean getHealth() { + return true; + } + + private boolean isGraphOpen() { + return true; + } + + + private static final String JANUSGRAPH_HEALTH_CHECK_STR = "janusGraphHealthCheck"; + + + private void createJanusGraphSchema() { + + JanusGraphManagement graphMgt = graph.openManagement(); + JanusGraphIndex index = null; + for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) { + PropertyKey propKey = null; + if (!graphMgt.containsPropertyKey(prop.getProperty())) { + Class clazz = prop.getClazz(); + if (!ArrayList.class.getName().equals(clazz.getName()) && !HashMap.class.getName().equals(clazz.getName())) { + propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); + } + } else { + propKey = graphMgt.getPropertyKey(prop.getProperty()); + } + if (prop.isIndexed()) { + if (!graphMgt.containsGraphIndex(prop.getProperty())) { + if (prop.isUnique()) { + index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex(); + + graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures + // only + // one + // name + // per + // vertex + graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures + // name + // uniqueness + // in + // the + // graph + + } else { + graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex(); + } + } + } + } + graphMgt.commit(); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java deleted file mode 100644 index 96899b49c2..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java +++ /dev/null @@ -1,211 +0,0 @@ -package org.openecomp.sdc.be.components.path.beans; - - -import com.thinkaurelius.titan.core.*; -import com.thinkaurelius.titan.core.schema.ConsistencyModifier; -import com.thinkaurelius.titan.core.schema.TitanGraphIndex; -import com.thinkaurelius.titan.core.schema.TitanManagement; -import com.thinkaurelius.titan.core.util.TitanCleanup; -import com.thinkaurelius.titan.diskstorage.ResourceUnavailableException; -import com.thinkaurelius.titan.diskstorage.locking.PermanentLockingException; -import com.thinkaurelius.titan.graphdb.database.idassigner.IDPoolExhaustedException; -import fj.data.Either; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.sdc.be.dao.TitanClientStrategy; -import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanGraphClient; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import java.util.ArrayList; -import java.util.HashMap; - -@Component("titan-client") -public class InMemoryTitanGraphClient extends TitanGraphClient { - - - private static final Logger logger = LoggerFactory.getLogger(InMemoryTitanGraphClient.class); - - private static final String OK = "GOOD"; - - public InMemoryTitanGraphClient() { - } - - - private TitanGraph graph; - TitanClientStrategy titanClientStrategy; - - public InMemoryTitanGraphClient(TitanClientStrategy titanClientStrategy) { - super(); - this.titanClientStrategy = titanClientStrategy; - logger.info("** TitanGraphClient created"); - } - - @PostConstruct - public TitanOperationStatus createGraph() { - - logger.info("** createGraph started **"); - graph = TitanFactory.build().set("storage.backend", "inmemory").open(); - createTitanSchema(); - - logger.info("** in memory graph created"); - return TitanOperationStatus.OK; - - } - - - public void cleanupGraph() { - if (graph != null) { - // graph.shutdown(); - graph.close(); - TitanCleanup.clear(graph); - } - } - - public TitanOperationStatus createGraph(String titanCfgFile) { - logger.info("** open graph with {} started", titanCfgFile); - try { - logger.info("openGraph : try to load file {}", titanCfgFile); - graph = TitanFactory.open(titanCfgFile); - if (graph.isClosed()) { - logger.error("titan graph was not initialized"); - return TitanOperationStatus.NOT_CREATED; - } - - } catch (Exception e) { - this.graph = null; - logger.info("createGraph : failed to open Titan graph with configuration file: {}", titanCfgFile, e); - return TitanOperationStatus.NOT_CONNECTED; - } - - logger.info("** Titan graph created "); - - return TitanOperationStatus.OK; - } - - - public Either getGraph() { - if (graph != null) { - return Either.left(graph); - } else { - return Either.right(TitanOperationStatus.NOT_CREATED); - } - } - - public TitanOperationStatus commit() { - if (graph != null) { - try { - graph.tx().commit(); - return TitanOperationStatus.OK; - } catch (Exception e) { - return handleTitanException(e); - } - } else { - return TitanOperationStatus.NOT_CREATED; - } - } - - public TitanOperationStatus rollback() { - if (graph != null) { - try { - // graph.rollback(); - graph.tx().rollback(); - return TitanOperationStatus.OK; - } catch (Exception e) { - return handleTitanException(e); - } - } else { - return TitanOperationStatus.NOT_CREATED; - } - } - - public static TitanOperationStatus handleTitanException(Exception e) { - if (e instanceof TitanConfigurationException) { - return TitanOperationStatus.TITAN_CONFIGURATION; - } - if (e instanceof SchemaViolationException) { - return TitanOperationStatus.TITAN_SCHEMA_VIOLATION; - } - if (e instanceof PermanentLockingException) { - return TitanOperationStatus.TITAN_SCHEMA_VIOLATION; - } - if (e instanceof IDPoolExhaustedException) { - return TitanOperationStatus.GENERAL_ERROR; - } - if (e instanceof InvalidElementException) { - return TitanOperationStatus.INVALID_ELEMENT; - } - if (e instanceof InvalidIDException) { - return TitanOperationStatus.INVALID_ID; - } - if (e instanceof QueryException) { - return TitanOperationStatus.INVALID_QUERY; - } - if (e instanceof ResourceUnavailableException) { - return TitanOperationStatus.RESOURCE_UNAVAILABLE; - } - if (e instanceof IllegalArgumentException) { - // TODO check the error message?? - return TitanOperationStatus.ILLEGAL_ARGUMENT; - } - - return TitanOperationStatus.GENERAL_ERROR; - } - - public boolean getHealth() { - return true; - } - - private boolean isGraphOpen() { - return true; - } - - - private static final String TITAN_HEALTH_CHECK_STR = "titanHealthCheck"; - - - private void createTitanSchema() { - - TitanManagement graphMgt = graph.openManagement(); - TitanGraphIndex index = null; - for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) { - PropertyKey propKey = null; - if (!graphMgt.containsPropertyKey(prop.getProperty())) { - Class clazz = prop.getClazz(); - if (!ArrayList.class.getName().equals(clazz.getName()) && !HashMap.class.getName().equals(clazz.getName())) { - propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); - } - } else { - propKey = graphMgt.getPropertyKey(prop.getProperty()); - } - if (prop.isIndexed()) { - if (!graphMgt.containsGraphIndex(prop.getProperty())) { - if (prop.isUnique()) { - index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex(); - - graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures - // only - // one - // name - // per - // vertex - graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures - // name - // uniqueness - // in - // the - // graph - - } else { - graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex(); - } - } - } - } - graphMgt.commit(); - } - -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/JanusGraphTestSetup.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/JanusGraphTestSetup.java new file mode 100644 index 0000000000..0a11c45a6c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/JanusGraphTestSetup.java @@ -0,0 +1,166 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.janusgraph.core.PropertyKey; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphQuery; +import org.janusgraph.core.schema.ConsistencyModifier; +import org.janusgraph.core.schema.JanusGraphIndex; +import org.janusgraph.core.schema.JanusGraphManagement; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.utils.UserStatusEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.resources.data.UserData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class JanusGraphTestSetup { + + + private static final Logger logger = LoggerFactory.getLogger(JanusGraphTestSetup.class); + + private static JanusGraph graph; + + public static boolean createGraph( JanusGraph graph) { + JanusGraphTestSetup.graph = graph; + createIndexesAndDefaults(); + + logger.info("** JanusGraph graph created "); + + return true; + } + + private static boolean isVertexExist(Map properties) { + JanusGraphQuery query = graph.query(); + + if (properties != null && !properties.isEmpty()) { + for (Map.Entry entry : properties.entrySet()) { + query = query.has(entry.getKey(), entry.getValue()); + } + } + Iterable vertecies = query.vertices(); + java.util.Iterator iterator = vertecies.iterator(); + if (iterator.hasNext()) { + return true; + } + return false; + } + + private static void createDefaultAdminUser() { + createUser(getDefaultUserAdmin()); + graph.tx().commit(); + + } + + private static void createUser(UserData user) { + Map checkedProperties = new HashMap<>(); + checkedProperties.put(GraphPropertiesDictionary.USERID.getProperty(), user.getUserId()); + checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); + Map properties = null; + if (!isVertexExist(checkedProperties)) { + Vertex vertex = graph.addVertex(); + vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); + properties = user.toGraphMap(); + for (Map.Entry entry : properties.entrySet()) { + vertex.property(entry.getKey(), entry.getValue()); + } + } + } + + private static UserData getDefaultUserAdmin() { + UserData userData = new UserData(); + userData.setAction(ActionEnum.Create); + userData.setElementType(GraphElementTypeEnum.Node); + userData.setUserId("jh0003"); + userData.setEmail("admin@sdc.com"); + userData.setFirstName("Jimmy"); + userData.setLastName("Hendrix"); + userData.setRole("ADMIN"); + userData.setStatus(UserStatusEnum.ACTIVE.name()); + userData.setLastLoginTime(0L); + return userData; + } + + + private static void createVertexIndixes() { + logger.info("** createVertexIndixes started"); + + JanusGraphManagement graphMgt = graph.openManagement(); + JanusGraphIndex index = null; + for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) { + PropertyKey propKey = null; + if (!graphMgt.containsPropertyKey(prop.getProperty())) { + Class clazz = prop.getClazz(); + if (!ArrayList.class.getName().equals(clazz.getName()) && !HashMap.class.getName().equals(clazz.getName())) { + propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); + } + } else { + propKey = graphMgt.getPropertyKey(prop.getProperty()); + } + if (prop.isIndexed()) { + if (!graphMgt.containsGraphIndex(prop.getProperty())) { + if (prop.isUnique()) { + index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex(); + + graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures + // only + // one + // name + // per + // vertex + graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures + // name + // uniqueness + // in + // the + // graph + + } else { + graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex(); + } + } + } + } + graphMgt.commit(); + logger.info("** createVertexIndixes ended"); + + } + + private static void createEdgeIndixes() { + logger.info("** createEdgeIndixes started"); + JanusGraphManagement graphMgt = graph.openManagement(); + for (GraphEdgePropertiesDictionary prop : GraphEdgePropertiesDictionary.values()) { + if (!graphMgt.containsGraphIndex(prop.getProperty())) { + PropertyKey propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); + graphMgt.buildIndex(prop.getProperty(), Edge.class).addKey(propKey).buildCompositeIndex(); + + } + } + graphMgt.commit(); + logger.info("** createEdgeIndixes ended"); + } + + private static void createIndexesAndDefaults() { + createVertexIndixes(); + createEdgeIndixes(); + createDefaultAdminUser(); + createRootCatalogVertex(); + } + private static void createRootCatalogVertex(){ + Vertex vertex = graph.addVertex(); + vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty(), IdBuilderUtils.generateUniqueId()); + vertex.property(GraphPropertyEnum.LABEL.getProperty(), VertexTypeEnum.CATALOG_ROOT.getName()); + graph.tx().commit(); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java deleted file mode 100644 index 7a7eff879a..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java +++ /dev/null @@ -1,166 +0,0 @@ -package org.openecomp.sdc.be.components.path.beans; - -import com.thinkaurelius.titan.core.PropertyKey; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanGraphQuery; -import com.thinkaurelius.titan.core.schema.ConsistencyModifier; -import com.thinkaurelius.titan.core.schema.TitanGraphIndex; -import com.thinkaurelius.titan.core.schema.TitanManagement; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum; -import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; -import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; -import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.utils.UserStatusEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.resources.data.UserData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -public class TitanGraphTestSetup { - - - private static final Logger logger = LoggerFactory.getLogger(TitanGraphTestSetup.class); - - private static TitanGraph graph; - - public static boolean createGraph( TitanGraph graph) { - TitanGraphTestSetup.graph = graph; - createIndexesAndDefaults(); - - logger.info("** Titan graph created "); - - return true; - } - - private static boolean isVertexExist(Map properties) { - TitanGraphQuery query = graph.query(); - - if (properties != null && !properties.isEmpty()) { - for (Map.Entry entry : properties.entrySet()) { - query = query.has(entry.getKey(), entry.getValue()); - } - } - Iterable vertecies = query.vertices(); - java.util.Iterator iterator = vertecies.iterator(); - if (iterator.hasNext()) { - return true; - } - return false; - } - - private static void createDefaultAdminUser() { - createUser(getDefaultUserAdmin()); - graph.tx().commit(); - - } - - private static void createUser(UserData user) { - Map checkedProperties = new HashMap<>(); - checkedProperties.put(GraphPropertiesDictionary.USERID.getProperty(), user.getUserId()); - checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); - Map properties = null; - if (!isVertexExist(checkedProperties)) { - Vertex vertex = graph.addVertex(); - vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); - properties = user.toGraphMap(); - for (Map.Entry entry : properties.entrySet()) { - vertex.property(entry.getKey(), entry.getValue()); - } - } - } - - private static UserData getDefaultUserAdmin() { - UserData userData = new UserData(); - userData.setAction(ActionEnum.Create); - userData.setElementType(GraphElementTypeEnum.Node); - userData.setUserId("jh0003"); - userData.setEmail("admin@sdc.com"); - userData.setFirstName("Jimmy"); - userData.setLastName("Hendrix"); - userData.setRole("ADMIN"); - userData.setStatus(UserStatusEnum.ACTIVE.name()); - userData.setLastLoginTime(0L); - return userData; - } - - - private static void createVertexIndixes() { - logger.info("** createVertexIndixes started"); - - TitanManagement graphMgt = graph.openManagement(); - TitanGraphIndex index = null; - for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) { - PropertyKey propKey = null; - if (!graphMgt.containsPropertyKey(prop.getProperty())) { - Class clazz = prop.getClazz(); - if (!ArrayList.class.getName().equals(clazz.getName()) && !HashMap.class.getName().equals(clazz.getName())) { - propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); - } - } else { - propKey = graphMgt.getPropertyKey(prop.getProperty()); - } - if (prop.isIndexed()) { - if (!graphMgt.containsGraphIndex(prop.getProperty())) { - if (prop.isUnique()) { - index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex(); - - graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures - // only - // one - // name - // per - // vertex - graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures - // name - // uniqueness - // in - // the - // graph - - } else { - graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex(); - } - } - } - } - graphMgt.commit(); - logger.info("** createVertexIndixes ended"); - - } - - private static void createEdgeIndixes() { - logger.info("** createEdgeIndixes started"); - TitanManagement graphMgt = graph.openManagement(); - for (GraphEdgePropertiesDictionary prop : GraphEdgePropertiesDictionary.values()) { - if (!graphMgt.containsGraphIndex(prop.getProperty())) { - PropertyKey propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); - graphMgt.buildIndex(prop.getProperty(), Edge.class).addKey(propKey).buildCompositeIndex(); - - } - } - graphMgt.commit(); - logger.info("** createEdgeIndixes ended"); - } - - private static void createIndexesAndDefaults() { - createVertexIndixes(); - createEdgeIndixes(); - createDefaultAdminUser(); - createRootCatalogVertex(); - } - private static void createRootCatalogVertex(){ - Vertex vertex = graph.addVertex(); - vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty(), IdBuilderUtils.generateUniqueId()); - vertex.property(GraphPropertyEnum.LABEL.getProperty(), VertexTypeEnum.CATALOG_ROOT.getName()); - graph.tx().commit(); - } -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java index 78f4964b7e..0ae1d8c80c 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java @@ -20,15 +20,15 @@ package org.openecomp.sdc.be.components.path.utils; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import org.apache.tinkerpop.gremlin.structure.io.IoCore; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; @@ -44,21 +44,21 @@ import java.util.UUID; public final class GraphTestUtils { - public static GraphVertex createRootCatalogVertex(TitanDao titanDao) { + public static GraphVertex createRootCatalogVertex(JanusGraphDao janusGraphDao) { GraphVertex catalogRootVertex = new GraphVertex(VertexTypeEnum.CATALOG_ROOT); catalogRootVertex.setUniqueId(IdBuilderUtils.generateUniqueId()); - return titanDao.createVertex(catalogRootVertex) + return janusGraphDao.createVertex(catalogRootVertex) .either(v -> v, s -> null); } - public static GraphVertex createRootArchiveVertex(TitanDao titanDao) { + public static GraphVertex createRootArchiveVertex(JanusGraphDao janusGraphDao) { GraphVertex archiveRootVertex = new GraphVertex(VertexTypeEnum.ARCHIVE_ROOT); archiveRootVertex.setUniqueId(IdBuilderUtils.generateUniqueId()); - return titanDao.createVertex(archiveRootVertex) + return janusGraphDao.createVertex(archiveRootVertex) .either(v -> v, s -> null); } - public static GraphVertex createResourceVertex(TitanDao titanDao, Map metadataProps, ResourceTypeEnum type) { + public static GraphVertex createResourceVertex(JanusGraphDao janusGraphDao, Map metadataProps, ResourceTypeEnum type) { GraphVertex vertex = new GraphVertex(); if (type == ResourceTypeEnum.VF) { vertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); @@ -77,12 +77,12 @@ public final class GraphTestUtils { for (Map.Entry prop : metadataProps.entrySet()) { vertex.addMetadataProperty(prop.getKey(), prop.getValue()); } - titanDao.createVertex(vertex); - titanDao.commit(); + janusGraphDao.createVertex(vertex); + janusGraphDao.commit(); return vertex; } - public static GraphVertex createServiceVertex(TitanDao titanDao, Map metadataProps){ + public static GraphVertex createServiceVertex(JanusGraphDao janusGraphDao, Map metadataProps){ GraphVertex vertex = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); String uuid = UUID.randomUUID().toString(); @@ -95,27 +95,27 @@ public final class GraphTestUtils { for (Map.Entry prop : metadataProps.entrySet()) { vertex.addMetadataProperty(prop.getKey(), prop.getValue()); } - titanDao.createVertex(vertex); - titanDao.commit(); + janusGraphDao.createVertex(vertex); + janusGraphDao.commit(); return vertex; } - public static void clearGraph(TitanDao titanDao) { - Either graphResult = titanDao.getGraph(); - TitanGraph graph = graphResult.left().value(); + public static void clearGraph(JanusGraphDao janusGraphDao) { + Either graphResult = janusGraphDao.getGraph(); + JanusGraph graph = graphResult.left().value(); - Iterable vertices = graph.query().vertices(); + Iterable vertices = graph.query().vertices(); if (vertices != null) { - Iterator iterator = vertices.iterator(); + Iterator iterator = vertices.iterator(); while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); + JanusGraphVertex vertex = iterator.next(); vertex.remove(); } } - titanDao.commit(); + janusGraphDao.commit(); } - public static String exportGraphMl(TitanGraph graph, String outputDirectory) { + public static String exportGraphMl(JanusGraph graph, String outputDirectory) { String result = null; String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml"; try { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeceleratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeceleratorTest.java index c2bbb034ce..9c2752ea38 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeceleratorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeceleratorTest.java @@ -11,7 +11,7 @@ import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import java.util.LinkedList; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclaratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclaratorTest.java index 14a4a02313..8ea89d2f76 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclaratorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclaratorTest.java @@ -53,7 +53,7 @@ import org.openecomp.sdc.be.model.ComponentInstancePropInput; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclaratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclaratorTest.java index bad71961bd..0f744c23aa 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclaratorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclaratorTest.java @@ -59,7 +59,7 @@ 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.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclaratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclaratorTest.java index b432502996..c9e32e7327 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclaratorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclaratorTest.java @@ -50,7 +50,7 @@ import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentPropertyToPolicyDeclaratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentPropertyToPolicyDeclaratorTest.java index 11292dc0e1..68889a3594 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentPropertyToPolicyDeclaratorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentPropertyToPolicyDeclaratorTest.java @@ -22,7 +22,7 @@ import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition; import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @RunWith(MockitoJUnitRunner.class) diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java index 586cc55462..9577b536f9 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java @@ -27,7 +27,7 @@ import org.openecomp.sdc.be.model.ComponentInstancePropInput; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.PolicyOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.PolicyOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclaratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclaratorTest.java index f85388a06b..0f065b8ffb 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclaratorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclaratorTest.java @@ -17,7 +17,7 @@ import org.openecomp.sdc.be.model.ComponentInstancePropInput; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.PolicyOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.PolicyOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclaratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclaratorTest.java index c44b907344..e343202042 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclaratorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclaratorTest.java @@ -2,8 +2,6 @@ package org.openecomp.sdc.be.components.property.propertytopolicydeclarators; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -21,7 +19,6 @@ import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.Spy; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; @@ -30,7 +27,7 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; public class ComponentInstancePropertyToPolicyDeclaratorTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogicTest.java index ea9095fd11..c23bb1c6b8 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogicTest.java @@ -34,7 +34,7 @@ import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -53,8 +53,8 @@ import org.openecomp.sdc.be.model.ResourceMetadataDefinition; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.ServiceMetadataDefinition; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.jsontitan.operations.UpgradeOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.UpgradeOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; @@ -106,7 +106,7 @@ public class UpgradeBusinessLogicTest { private UpgradeOperation upgradeOperation; @Mock - private TitanDao titanDao; + private JanusGraphDao janusGraphDao; @InjectMocks private UpgradeBusinessLogic upgradeBusinessLogic; @@ -116,7 +116,8 @@ public class UpgradeBusinessLogicTest { MockitoAnnotations.initMocks(this); upgradeBusinessLogic = new UpgradeBusinessLogic(lifecycleBusinessLogic, componentInstanceBusinessLogic, - userValidations, toscaOperationFacade, componentsUtils, upgradeOperation, titanDao); + userValidations, toscaOperationFacade, componentsUtils, upgradeOperation, + janusGraphDao); user = new User(); user.setRole(Role.ADMIN.name()); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/AnnotationValidatorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/AnnotationValidatorTest.java index 480c8cfec7..8815510369 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/AnnotationValidatorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/AnnotationValidatorTest.java @@ -34,7 +34,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.Annotation; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -71,7 +71,7 @@ public class AnnotationValidatorTest { public void setUp() throws Exception { annotationValidator = new AnnotationValidator(propertyValidator, exceptionUtils, dataTypeCache, componentsUtils); allData = Collections.emptyMap(); - Either, TitanOperationStatus> cacheResponse = Either.left(allData); + Either, JanusGraphOperationStatus> cacheResponse = Either.left(allData); Mockito.when(dataTypeCache.getAll()).thenReturn(cacheResponse); annotationTypeProperties = Collections.emptyList(); propertyDataDefinitions = new ArrayList<>(); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ComponentValidationsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ComponentValidationsTest.java index c3b5a6bc08..c6d7e569d3 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ComponentValidationsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ComponentValidationsTest.java @@ -33,7 +33,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java index dfc1b18837..1ff159f317 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java @@ -39,7 +39,7 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; import org.openecomp.sdc.exception.ResponseFormat; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/utils/PropertyValueConstraintValidationUtilTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/utils/PropertyValueConstraintValidationUtilTest.java index 95020b6112..16df8f31be 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/utils/PropertyValueConstraintValidationUtilTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/utils/PropertyValueConstraintValidationUtilTest.java @@ -29,14 +29,14 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.exception.ResponseFormat; @@ -68,7 +68,7 @@ public class PropertyValueConstraintValidationUtilTest { @Test public void primitiveValueSuccessTest() { - Either, TitanOperationStatus> either = Either.left(dataTypeDefinitionMap); + Either, JanusGraphOperationStatus> either = Either.left(dataTypeDefinitionMap); Mockito.when(applicationDataTypeCache.getAll()).thenReturn(either); PropertyDefinition propertyDefinition = new PropertyDefinition(); @@ -84,7 +84,7 @@ public class PropertyValueConstraintValidationUtilTest { @Test public void primitiveValueFailTest() { - Either, TitanOperationStatus> either = Either.left(dataTypeDefinitionMap); + Either, JanusGraphOperationStatus> either = Either.left(dataTypeDefinitionMap); Mockito.when(applicationDataTypeCache.getAll()).thenReturn(either); PropertyDefinition propertyDefinition = new PropertyDefinition(); @@ -100,7 +100,7 @@ public class PropertyValueConstraintValidationUtilTest { @Test public void complexWithValidValueSuccessTest() { - Either, TitanOperationStatus> either = Either.left(dataTypeDefinitionMap); + Either, JanusGraphOperationStatus> either = Either.left(dataTypeDefinitionMap); Mockito.when(applicationDataTypeCache.getAll()).thenReturn(either); PropertyDefinition propertyDefinition = new PropertyDefinition(); @@ -116,7 +116,7 @@ public class PropertyValueConstraintValidationUtilTest { @Test public void complexWithValidValueFailTest() { - Either, TitanOperationStatus> either = Either.left(dataTypeDefinitionMap); + Either, JanusGraphOperationStatus> either = Either.left(dataTypeDefinitionMap); Mockito.when(applicationDataTypeCache.getAll()).thenReturn(either); PropertyDefinition propertyDefinition = new PropertyDefinition(); @@ -132,7 +132,7 @@ public class PropertyValueConstraintValidationUtilTest { @Test public void complexWithListWithPrimitiveValueSuccessTest() { - Either, TitanOperationStatus> either = Either.left(dataTypeDefinitionMap); + Either, JanusGraphOperationStatus> either = Either.left(dataTypeDefinitionMap); Mockito.when(applicationDataTypeCache.getAll()).thenReturn(either); PropertyDefinition propertyDefinition = new PropertyDefinition(); @@ -148,7 +148,7 @@ public class PropertyValueConstraintValidationUtilTest { @Test public void complexWithListWithPrimitiveValueFailTest() { - Either, TitanOperationStatus> either = Either.left(dataTypeDefinitionMap); + Either, JanusGraphOperationStatus> either = Either.left(dataTypeDefinitionMap); Mockito.when(applicationDataTypeCache.getAll()).thenReturn(either); PropertyDefinition propertyDefinition = new PropertyDefinition(); @@ -164,7 +164,7 @@ public class PropertyValueConstraintValidationUtilTest { @Test public void complexWithMapWithPrimitiveValueSuccessTest() { - Either, TitanOperationStatus> either = Either.left(dataTypeDefinitionMap); + Either, JanusGraphOperationStatus> either = Either.left(dataTypeDefinitionMap); Mockito.when(applicationDataTypeCache.getAll()).thenReturn(either); PropertyDefinition propertyDefinition = new PropertyDefinition(); @@ -180,7 +180,7 @@ public class PropertyValueConstraintValidationUtilTest { @Test public void complexWithMapWithPrimitiveValueFailTest() { - Either, TitanOperationStatus> either = Either.left(dataTypeDefinitionMap); + Either, JanusGraphOperationStatus> either = Either.left(dataTypeDefinitionMap); Mockito.when(applicationDataTypeCache.getAll()).thenReturn(either); PropertyDefinition propertyDefinition = new PropertyDefinition(); @@ -196,7 +196,7 @@ public class PropertyValueConstraintValidationUtilTest { @Test public void inputValidValueSuccessTest() { - Either, TitanOperationStatus> either = Either.left(dataTypeDefinitionMap); + Either, JanusGraphOperationStatus> either = Either.left(dataTypeDefinitionMap); Mockito.when(applicationDataTypeCache.getAll()).thenReturn(either); InputDefinition inputDefinition = new InputDefinition(); @@ -216,7 +216,7 @@ public class PropertyValueConstraintValidationUtilTest { @Test public void inputValidValueFailTest() { - Either, TitanOperationStatus> either = Either.left(dataTypeDefinitionMap); + Either, JanusGraphOperationStatus> either = Either.left(dataTypeDefinitionMap); Mockito.when(applicationDataTypeCache.getAll()).thenReturn(either); InputDefinition inputDefinition = new InputDefinition(); @@ -235,7 +235,7 @@ public class PropertyValueConstraintValidationUtilTest { @Test public void serviceConsumptionValidValueSuccessTest() { - Either, TitanOperationStatus> either = Either.left(dataTypeDefinitionMap); + Either, JanusGraphOperationStatus> either = Either.left(dataTypeDefinitionMap); Mockito.when(applicationDataTypeCache.getAll()).thenReturn(either); PropertyDefinition propertyDefinition = new PropertyDefinition(); @@ -251,7 +251,7 @@ public class PropertyValueConstraintValidationUtilTest { } @Test public void serviceConsumptionValidValueFailTest() { - Either, TitanOperationStatus> either = Either.left(dataTypeDefinitionMap); + Either, JanusGraphOperationStatus> either = Either.left(dataTypeDefinitionMap); Mockito.when(applicationDataTypeCache.getAll()).thenReturn(either); PropertyDefinition propertyDefinition = new PropertyDefinition(); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java index 5a2b598ed8..e011aabdd9 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java @@ -35,16 +35,16 @@ import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponent import org.openecomp.sdc.be.components.path.utils.GraphTestUtils; import org.openecomp.sdc.be.components.validation.AccessValidations; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.DAOTitanStrategy; -import org.openecomp.sdc.be.dao.TitanClientStrategy; +import org.openecomp.sdc.be.dao.DAOJanusGraphStrategy; +import org.openecomp.sdc.be.dao.JanusGraphClientStrategy; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.impl.HealingPipelineDao; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.HealingTitanDao; -import org.openecomp.sdc.be.dao.titan.HealingTitanGenericDao; -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.dao.jsongraph.HealingJanusGraphDao; +import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.dto.ExternalRefDTO; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -52,8 +52,8 @@ import org.openecomp.sdc.be.impl.ServletUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.operations.*; -import org.openecomp.sdc.be.model.jsontitan.utils.IdMapper; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.*; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.IdMapper; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.impl.OperationUtils; @@ -110,7 +110,7 @@ public class ExternalRefServletTest extends JerseyTest { private static final ToscaOperationFacade toscaOperationFacadeMock = Mockito.mock(ToscaOperationFacade.class); private static final AccessValidations accessValidationsMock = Mockito.mock(AccessValidations.class); private static final ComponentLocker componentLocker = Mockito.mock(ComponentLocker.class); - private static final HealingTitanGenericDao titanGenericDao = Mockito.mock(HealingTitanGenericDao.class); + private static final HealingJanusGraphGenericDao janusGraphGenericDao = Mockito.mock(HealingJanusGraphGenericDao.class); private static final ICacheMangerOperation cacheManagerOperation = Mockito.mock(ICacheMangerOperation.class); private static final IGraphLockOperation graphLockOperation = Mockito.mock(IGraphLockOperation.class); @@ -136,7 +136,7 @@ public class ExternalRefServletTest extends JerseyTest { private GraphVertex serviceVertex; private GraphVertex resourceVertex; private ExternalReferencesOperation externalReferenceOperation; - private HealingTitanDao titanDao; + private HealingJanusGraphDao janusGraphDao; private OperationUtils operationUtils; @Bean @@ -145,7 +145,7 @@ public class ExternalRefServletTest extends JerseyTest { } @Bean - OperationUtils operationUtils() {return new OperationUtils(titanDao());} + OperationUtils operationUtils() {return new OperationUtils(janusGraphDao());} @Bean ComponentExceptionMapper componentExceptionMapper() { @@ -174,9 +174,9 @@ public class ExternalRefServletTest extends JerseyTest { @Bean ExternalReferencesOperation externalReferencesOperation() { - this.externalReferenceOperation = new ExternalReferencesOperation(titanDao(), nodeTypeOpertaion(), topologyTemplateOperation(), idMapper()); + this.externalReferenceOperation = new ExternalReferencesOperation(janusGraphDao(), nodeTypeOpertaion(), topologyTemplateOperation(), idMapper()); this.externalReferenceOperation.setHealingPipelineDao(healingPipelineDao()); - GraphTestUtils.clearGraph(titanDao); + GraphTestUtils.clearGraph(janusGraphDao); initGraphForTest(); return this.externalReferenceOperation; } @@ -202,7 +202,7 @@ public class ExternalRefServletTest extends JerseyTest { @Bean ArchiveOperation archiveOperation() { - return new ArchiveOperation(titanDao(), graphLockOperation()); + return new ArchiveOperation(janusGraphDao(), graphLockOperation()); } @Bean @@ -231,19 +231,19 @@ public class ExternalRefServletTest extends JerseyTest { } @Bean - HealingTitanDao titanDao() { - this.titanDao = new HealingTitanDao(titanGraphClient()); - return titanDao; + HealingJanusGraphDao janusGraphDao() { + this.janusGraphDao = new HealingJanusGraphDao(janusGraphClient()); + return janusGraphDao; } @Bean - TitanGraphClient titanGraphClient() { - return new TitanGraphClient(titanClientStrategy()); + JanusGraphClient janusGraphClient() { + return new JanusGraphClient(janusGraphClientStrategy()); } @Bean - TitanClientStrategy titanClientStrategy() { - return new DAOTitanStrategy(); + JanusGraphClientStrategy janusGraphClientStrategy() { + return new DAOJanusGraphStrategy(); } @Bean @@ -257,8 +257,8 @@ public class ExternalRefServletTest extends JerseyTest { } @Bean - TitanGenericDao titanGenericDao() { - return titanGenericDao; + JanusGraphGenericDao janusGraphGenericDao() { + return janusGraphGenericDao; } @Bean("healingPipelineDao") @@ -273,11 +273,11 @@ public class ExternalRefServletTest extends JerseyTest { private void initGraphForTest() { if (!setupDone) { - resourceVertex = GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VF); + resourceVertex = GraphTestUtils.createResourceVertex(janusGraphDao, new HashMap<>(), ResourceTypeEnum.VF); resourceVertexUuid = resourceVertex.getUniqueId(); //create a service and add ref - serviceVertex = GraphTestUtils.createServiceVertex(titanDao, new HashMap<>()); + serviceVertex = GraphTestUtils.createServiceVertex(janusGraphDao, new HashMap<>()); serviceVertexUuid = this.serviceVertex.getUniqueId(); //monitoring references @@ -289,8 +289,8 @@ public class ExternalRefServletTest extends JerseyTest { //workflow references externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, WORKFLOW_OBJECT_TYPE, REF_6); - final TitanOperationStatus commit = this.titanDao.commit(); - assertThat(commit).isEqualTo(TitanOperationStatus.OK); + final JanusGraphOperationStatus commit = this.janusGraphDao.commit(); + assertThat(commit).isEqualTo(JanusGraphOperationStatus.OK); } } @@ -353,7 +353,7 @@ public class ExternalRefServletTest extends JerseyTest { ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); org.openecomp.sdc.be.config.Configuration configuration = new org.openecomp.sdc.be.config.Configuration(); - configuration.setTitanInMemoryGraph(true); + configuration.setJanusGraphInMemoryGraph(true); configurationManager.setConfiguration(configuration); ExternalConfiguration.setAppName("catalog-be"); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ArchiveEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ArchiveEndpointTest.java index f315ddf9d0..2ad52251f6 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ArchiveEndpointTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ArchiveEndpointTest.java @@ -53,17 +53,17 @@ import org.openecomp.sdc.be.components.path.utils.GraphTestUtils; import org.openecomp.sdc.be.components.validation.AccessValidations; import org.openecomp.sdc.be.components.validation.ComponentValidations; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.DAOTitanStrategy; -import org.openecomp.sdc.be.dao.TitanClientStrategy; +import org.openecomp.sdc.be.dao.DAOJanusGraphStrategy; +import org.openecomp.sdc.be.dao.JanusGraphClientStrategy; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.impl.HealingPipelineDao; +import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.HealingTitanDao; +import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.titan.HealingTitanGenericDao; -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.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; @@ -75,13 +75,13 @@ import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.catalog.CatalogComponent; -import org.openecomp.sdc.be.model.jsontitan.operations.ArchiveOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.CategoryOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArchiveOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.CategoryOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTypeOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -121,14 +121,15 @@ public class ArchiveEndpointTest extends JerseyTest { private static final AccessValidations accessValidationsMock = mock(AccessValidations.class); private static final ComponentValidations componentValidationsMock = mock(ComponentValidations.class); private static final IGraphLockOperation graphLockOperation = mock(IGraphLockOperation.class); - private static final HealingTitanGenericDao titanGenericDao = mock(HealingTitanGenericDao.class); + private static final HealingJanusGraphGenericDao + janusGraphGenericDao = mock(HealingJanusGraphGenericDao.class); private static final HealingPipelineDao HEALING_PIPELINE_DAO = mock(HealingPipelineDao.class); private static final ICacheMangerOperation cacheManagerOperation = mock(ICacheMangerOperation.class); private static GraphVertex serviceVertex; private static GraphVertex resourceVertex; private static GraphVertex resourceVertexVspArchived; - private static HealingTitanDao titanDao; + private static HealingJanusGraphDao janusGraphDao; @Configuration @PropertySource("classpath:dao.properties") @@ -158,13 +159,13 @@ public class ArchiveEndpointTest extends JerseyTest { @Bean ArchiveBusinessLogic archiveBusinessLogic() { - return new ArchiveBusinessLogic(titanDao(), accessValidations(), archiveOperation(), toscaOperationFacade(), componentUtils); + return new ArchiveBusinessLogic(janusGraphDao(), accessValidations(), archiveOperation(), toscaOperationFacade(), componentUtils); } @Bean ArchiveOperation archiveOperation() { - this.archiveOperation = new ArchiveOperation(titanDao(), graphLockOperation()); - GraphTestUtils.clearGraph(titanDao); + this.archiveOperation = new ArchiveOperation(janusGraphDao(), graphLockOperation()); + GraphTestUtils.clearGraph(janusGraphDao); initGraphForTest(); return this.archiveOperation; } @@ -210,19 +211,19 @@ public class ArchiveEndpointTest extends JerseyTest { } @Bean - HealingTitanDao titanDao() { - titanDao = new HealingTitanDao(titanGraphClient()); - return titanDao; + HealingJanusGraphDao janusGraphDao() { + janusGraphDao = new HealingJanusGraphDao(janusGraphClient()); + return janusGraphDao; } @Bean - TitanGraphClient titanGraphClient() { - return new TitanGraphClient(titanClientStrategy()); + JanusGraphClient janusGraphClient() { + return new JanusGraphClient(janusGraphClientStrategy()); } @Bean - TitanClientStrategy titanClientStrategy() { - return new DAOTitanStrategy(); + JanusGraphClientStrategy janusGraphClientStrategy() { + return new DAOJanusGraphStrategy(); } @Bean @@ -236,8 +237,8 @@ public class ArchiveEndpointTest extends JerseyTest { } @Bean - TitanGenericDao titanGenericDao() { - return titanGenericDao; + JanusGraphGenericDao janusGraphGenericDao() { + return janusGraphGenericDao; } @Bean @@ -247,31 +248,31 @@ public class ArchiveEndpointTest extends JerseyTest { private void initGraphForTest() { //Create Catalog Root - catalogVertex = GraphTestUtils.createRootCatalogVertex(titanDao); + catalogVertex = GraphTestUtils.createRootCatalogVertex(janusGraphDao); //Create Archive Root - GraphTestUtils.createRootArchiveVertex(titanDao); + GraphTestUtils.createRootArchiveVertex(janusGraphDao); createSingleVersionServiceAndResource(); } private void createSingleVersionServiceAndResource() { //Create Service for Scenario 1 Tests (1 Service) - serviceVertex = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); + serviceVertex = GraphTestUtils.createServiceVertex(janusGraphDao, propsForHighestVersion()); Map props = propsForHighestVersion(); props.put(GraphPropertyEnum.IS_VSP_ARCHIVED, false); props.put(GraphPropertyEnum.CSAR_UUID, CSAR_UUID1); - resourceVertex = GraphTestUtils.createResourceVertex(titanDao, props, ResourceTypeEnum.VF); + resourceVertex = GraphTestUtils.createResourceVertex(janusGraphDao, props, ResourceTypeEnum.VF); props = propsForHighestVersion(); props.put(GraphPropertyEnum.IS_VSP_ARCHIVED, true); props.put(GraphPropertyEnum.CSAR_UUID, CSAR_UUID2); - resourceVertexVspArchived = GraphTestUtils.createResourceVertex(titanDao, props, ResourceTypeEnum.VF); + resourceVertexVspArchived = GraphTestUtils.createResourceVertex(janusGraphDao, props, ResourceTypeEnum.VF); //Connect Service/Resource to Catalog Root - titanDao.createEdge(catalogVertex, serviceVertex, EdgeLabelEnum.CATALOG_ELEMENT, null); - titanDao.createEdge(catalogVertex, resourceVertex, EdgeLabelEnum.CATALOG_ELEMENT, null); + janusGraphDao.createEdge(catalogVertex, serviceVertex, EdgeLabelEnum.CATALOG_ELEMENT, null); + janusGraphDao.createEdge(catalogVertex, resourceVertex, EdgeLabelEnum.CATALOG_ELEMENT, null); } private Map propsForHighestVersion(){ @@ -328,7 +329,7 @@ public class ArchiveEndpointTest extends JerseyTest { ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); org.openecomp.sdc.be.config.Configuration configuration = new org.openecomp.sdc.be.config.Configuration(); - configuration.setTitanInMemoryGraph(true); + configuration.setJanusGraphInMemoryGraph(true); configurationManager.setConfiguration(configuration); ExternalConfiguration.setAppName("catalog-be"); @@ -412,16 +413,16 @@ public class ArchiveEndpointTest extends JerseyTest { } private void checkoutComponent(GraphVertex component) { - Either vE = titanDao.getVertexById(component.getUniqueId()); + Either vE = janusGraphDao.getVertexById(component.getUniqueId()); GraphVertex v = vE.left().value(); v.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); v.setJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - titanDao.updateVertex(v); - titanDao.commit(); + janusGraphDao.updateVertex(v); + janusGraphDao.commit(); } private void assertOnVertexProp(String componentId, Object expectedValue) { - Either vE = titanDao.getVertexById(componentId); + Either vE = janusGraphDao.getVertexById(componentId); GraphVertex v = vE.left().value(); assertThat(v.getMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED)).isEqualTo(expectedValue); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AutomatedUpgradeEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AutomatedUpgradeEndpointTest.java index 2a959ec843..60fb579ae9 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AutomatedUpgradeEndpointTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AutomatedUpgradeEndpointTest.java @@ -19,13 +19,13 @@ import org.openecomp.sdc.be.components.upgrade.UpgradeStatus; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.jsontitan.operations.UpgradeOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.UpgradeOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.api.Constants; @@ -71,7 +71,7 @@ public class AutomatedUpgradeEndpointTest extends JerseySpringBaseTest { private static ToscaOperationFacade toscaOperationFacade; private static ComponentsUtils componentsUtils; private static UpgradeOperation upgradeOperation; - private static TitanDao titanDao; + private static JanusGraphDao janusGraphDao; private static User user; private static Resource vfPrev; @@ -96,7 +96,8 @@ public class AutomatedUpgradeEndpointTest extends JerseySpringBaseTest { @Bean UpgradeBusinessLogic upgradeBusinessLogic() { - return new UpgradeBusinessLogic(lifecycleBusinessLogic, componentInstanceBusinessLogic, userValidations, toscaOperationFacade, componentsUtils, upgradeOperation, titanDao); + return new UpgradeBusinessLogic(lifecycleBusinessLogic, componentInstanceBusinessLogic, userValidations, toscaOperationFacade, componentsUtils, upgradeOperation, + janusGraphDao); } } @@ -108,7 +109,7 @@ public class AutomatedUpgradeEndpointTest extends JerseySpringBaseTest { toscaOperationFacade = mock(ToscaOperationFacade.class); componentsUtils = mock(ComponentsUtils.class); upgradeOperation = mock(UpgradeOperation.class); - titanDao = mock(TitanDao.class); + janusGraphDao = mock(JanusGraphDao.class); user = mock(User.class); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java index 38373bdb08..d9ae9cc53e 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java @@ -23,7 +23,7 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupProperty; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.GroupOperation; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java index 1af04ac207..6acfd36e0a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java @@ -15,8 +15,8 @@ import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic; import org.openecomp.sdc.be.components.utils.GroupTypeBuilder; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.datatypes.elements.GroupTypeDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -47,7 +47,6 @@ import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; public class GroupTypesEndpointTest extends JerseySpringBaseTest { @@ -57,10 +56,10 @@ public class GroupTypesEndpointTest extends JerseySpringBaseTest { private static final HashSet EXCLUDED_TYPES = Sets.newHashSet("Root", "Heat"); private static ComponentsUtils componentsUtils; - private static TitanGenericDao titanGenericDao; + private static JanusGraphGenericDao janusGraphGenericDao; private static CapabilityTypeOperation capabilityTypeOperation; private static DerivedFromOperation derivedFromOperation; - private static TitanDao titanDao; + private static JanusGraphDao janusGraphDao; private static PropertyOperation propertyOperation; private static CapabilityOperation capabilityOperation; private static UserValidations userValidations; @@ -81,12 +80,12 @@ public class GroupTypesEndpointTest extends JerseySpringBaseTest { @Bean GroupTypeBusinessLogic groupTypeBusinessLogic() { - return new GroupTypeBusinessLogic(groupTypeOperation(), titanDao, userValidations, componentsUtils); + return new GroupTypeBusinessLogic(groupTypeOperation(), janusGraphDao, userValidations, componentsUtils); } @Bean GroupTypeOperation groupTypeOperation() { - return new GroupTypeOperation(titanGenericDao, propertyOperation, capabilityTypeOperation, capabilityOperation, derivedFromOperation, operationUtils); + return new GroupTypeOperation(janusGraphGenericDao, propertyOperation, capabilityTypeOperation, capabilityOperation, derivedFromOperation, operationUtils); } } @@ -95,8 +94,8 @@ public class GroupTypesEndpointTest extends JerseySpringBaseTest { componentsUtils = mock(ComponentsUtils.class); propertyOperation = mock(PropertyOperation.class); capabilityTypeOperation = mock(CapabilityTypeOperation.class); - titanDao = mock(TitanDao.class); - titanGenericDao = mock(TitanGenericDao.class); + janusGraphDao = mock(JanusGraphDao.class); + janusGraphGenericDao = mock(JanusGraphGenericDao.class); userValidations = mock(UserValidations.class); operationUtils = mock(OperationUtils.class); user = mock(User.class); @@ -105,7 +104,7 @@ public class GroupTypesEndpointTest extends JerseySpringBaseTest { @Before public void init() { when(userValidations.validateUserExists(eq(USER_ID), anyString(), anyBoolean())).thenReturn(user); - when(titanGenericDao.getByCriteriaWithPredicate(eq(NodeTypeEnum.GroupType), any(), eq(GroupTypeData.class))).thenReturn(Either.left(buildGroupTypeDataList())); + when(janusGraphGenericDao.getByCriteriaWithPredicate(eq(NodeTypeEnum.GroupType), any(), eq(GroupTypeData.class))).thenReturn(Either.left(buildGroupTypeDataList())); } @Override diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java index d542088763..7ff94c7785 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java @@ -52,7 +52,7 @@ import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.PolicyTargetDTO; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.api.Constants; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadEndpointTest.java index 5eecc77136..4a9cdad2d8 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadEndpointTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadEndpointTest.java @@ -18,9 +18,8 @@ import org.junit.Test; import org.mockito.Mockito; import org.openecomp.sdc.be.components.impl.CommonImportManager; import org.openecomp.sdc.be.components.validation.AccessValidations; -import org.openecomp.sdc.be.dao.titan.HealingTitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.AnnotationTypeDefinition; @@ -56,7 +55,7 @@ public class TypesUploadEndpointTest extends JerseySpringBaseTest { static final String userId = "jh0003"; private static AccessValidations accessValidations; - private static HealingTitanGenericDao titanGenericDao; + private static HealingJanusGraphGenericDao janusGraphGenericDao; private static PropertyOperation propertyOperation; private static ComponentsUtils componentUtils; private static OperationUtils operationUtils; @@ -82,13 +81,13 @@ public class TypesUploadEndpointTest extends JerseySpringBaseTest { @Bean CommonTypeOperations commonTypeOperations() { - return new CommonTypeOperations(titanGenericDao, propertyOperation, operationUtils); + return new CommonTypeOperations(janusGraphGenericDao, propertyOperation, operationUtils); } } @BeforeClass public static void initClass() { - titanGenericDao = mock(HealingTitanGenericDao.class); + janusGraphGenericDao = mock(HealingJanusGraphGenericDao.class); accessValidations = mock(AccessValidations.class); propertyOperation = mock(PropertyOperation.class); componentUtils = Mockito.mock(ComponentsUtils.class); @@ -113,14 +112,16 @@ public class TypesUploadEndpointTest extends JerseySpringBaseTest { @Test public void creatingAnnotationTypeSuccessTest() { doNothing().when(accessValidations).validateUserExists(eq(userId), anyString()); - when(titanGenericDao.createNode(isA(AnnotationTypeData.class), eq(AnnotationTypeData.class))).thenReturn(Either.left(new AnnotationTypeData())); - when(titanGenericDao.getNode(anyString(), eq("org.openecomp.annotations.source.1.0.annotationtype"), eq(AnnotationTypeData.class))).thenReturn(Either.left(new AnnotationTypeData())); - when(titanGenericDao.getByCriteria(eq(NodeTypeEnum.AnnotationType), anyMap(), eq(AnnotationTypeData.class))).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); + when(janusGraphGenericDao.createNode(isA(AnnotationTypeData.class), eq(AnnotationTypeData.class))).thenReturn(Either.left(new AnnotationTypeData())); + when(janusGraphGenericDao.getNode(anyString(), eq("org.openecomp.annotations.source.1.0.annotationtype"), eq(AnnotationTypeData.class))).thenReturn(Either.left(new AnnotationTypeData())); + when(janusGraphGenericDao.getByCriteria(eq(NodeTypeEnum.AnnotationType), anyMap(), eq(AnnotationTypeData.class))).thenReturn(Either.right( + JanusGraphOperationStatus.NOT_FOUND)); when(propertyOperation.addPropertiesToElementType(anyString(), eq(NodeTypeEnum.AnnotationType), anyList())).thenReturn(Either.left(emptyMap())); - when(propertyOperation.fillPropertiesList(anyString(), eq(NodeTypeEnum.AnnotationType), any())).thenReturn(TitanOperationStatus.OK); - when(propertyOperation.getTitanGenericDao()).thenReturn(titanGenericDao); - when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.OK); - when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + when(propertyOperation.fillPropertiesList(anyString(), eq(NodeTypeEnum.AnnotationType), any())).thenReturn( + JanusGraphOperationStatus.OK); + when(propertyOperation.getJanusGraphGenericDao()).thenReturn(janusGraphGenericDao); + when(janusGraphGenericDao.commit()).thenReturn(JanusGraphOperationStatus.OK); + when(janusGraphGenericDao.rollback()).thenReturn(JanusGraphOperationStatus.OK); FileDataBodyPart filePart = new FileDataBodyPart("annotationTypesZip", new File("src/test/resources/types/annotationTypes.zip")); MultiPart multipartEntity = new FormDataMultiPart(); multipartEntity.bodyPart(filePart); @@ -149,14 +150,17 @@ public class TypesUploadEndpointTest extends JerseySpringBaseTest { @Test public void creatingAnnotationTypeFailureTest() { doNothing().when(accessValidations).validateUserExists(eq(userId), anyString()); - when(titanGenericDao.createNode(isA(AnnotationTypeData.class), eq(AnnotationTypeData.class))).thenReturn(Either.left(new AnnotationTypeData())); - when(titanGenericDao.getNode(anyString(), eq("org.openecomp.annotations.source.1.0.annotationtype"), eq(AnnotationTypeData.class))).thenReturn(Either.left(new AnnotationTypeData())); - when(titanGenericDao.getByCriteria(eq(NodeTypeEnum.AnnotationType), anyMap(), eq(AnnotationTypeData.class))).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); - when(propertyOperation.addPropertiesToElementType(anyString(), eq(NodeTypeEnum.AnnotationType), anyList())).thenThrow(new StorageException(TitanOperationStatus.MATCH_NOT_FOUND)); - when(propertyOperation.fillPropertiesList(anyString(), eq(NodeTypeEnum.AnnotationType), any())).thenReturn(TitanOperationStatus.OK); - when(propertyOperation.getTitanGenericDao()).thenReturn(titanGenericDao); - when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.OK); - when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + when(janusGraphGenericDao.createNode(isA(AnnotationTypeData.class), eq(AnnotationTypeData.class))).thenReturn(Either.left(new AnnotationTypeData())); + when(janusGraphGenericDao.getNode(anyString(), eq("org.openecomp.annotations.source.1.0.annotationtype"), eq(AnnotationTypeData.class))).thenReturn(Either.left(new AnnotationTypeData())); + when(janusGraphGenericDao.getByCriteria(eq(NodeTypeEnum.AnnotationType), anyMap(), eq(AnnotationTypeData.class))).thenReturn(Either.right( + JanusGraphOperationStatus.NOT_FOUND)); + when(propertyOperation.addPropertiesToElementType(anyString(), eq(NodeTypeEnum.AnnotationType), anyList())).thenThrow(new StorageException( + JanusGraphOperationStatus.MATCH_NOT_FOUND)); + when(propertyOperation.fillPropertiesList(anyString(), eq(NodeTypeEnum.AnnotationType), any())).thenReturn( + JanusGraphOperationStatus.OK); + when(propertyOperation.getJanusGraphGenericDao()).thenReturn(janusGraphGenericDao); + when(janusGraphGenericDao.commit()).thenReturn(JanusGraphOperationStatus.OK); + when(janusGraphGenericDao.rollback()).thenReturn(JanusGraphOperationStatus.OK); FileDataBodyPart filePart = new FileDataBodyPart("annotationTypesZip", new File("src/test/resources/types/annotationTypes.zip")); MultiPart multipartEntity = new FormDataMultiPart(); multipartEntity.bodyPart(filePart); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverterTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverterTest.java index ff522e15c5..ec06c86abf 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverterTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverterTest.java @@ -35,10 +35,12 @@ import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; +import org.openecomp.sdc.be.tosca.model.ToscaNodeType; +import org.openecomp.sdc.be.tosca.model.ToscaTemplateCapability; import fj.data.Either; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java index 8b1fe5fabb..5b84066f48 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java @@ -50,20 +50,17 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; 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.InterfaceDefinition; 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.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData; @@ -71,7 +68,6 @@ import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo; import org.openecomp.sdc.be.tosca.model.ToscaTemplate; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; -import org.openecomp.sdc.exception.ResponseFormat; import fj.data.Either; import mockit.Deencapsulation; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java index 90dc926acf..0252d5a96c 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java @@ -21,7 +21,7 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.components.BeConfDependentTest; import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; @@ -51,7 +51,7 @@ import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; 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.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; @@ -64,7 +64,6 @@ import org.openecomp.sdc.be.tosca.model.ToscaTemplate; import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate; import org.openecomp.sdc.be.tosca.utils.InputConverter; -import org.yaml.snakeyaml.Yaml; import static org.junit.Assert.assertThat; import static org.hamcrest.CoreMatchers.is; @@ -182,7 +181,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { component = getNewService(); Mockito.when(capabiltyRequirementConvertor.convertRequirements(Mockito.any(Map.class),Mockito.any(Service.class), Mockito.any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); - Mockito.when(dataTypeCache.getAll()).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); + Mockito.when(dataTypeCache.getAll()).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); // default test when component is Service result = testSubject.exportComponent(component); @@ -195,7 +194,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { ((Resource) component).setInterfaces(new HashMap<>()); - Mockito.when(dataTypeCache.getAll()).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); + Mockito.when(dataTypeCache.getAll()).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); Mockito.when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()).thenReturn(Either.left(Collections.emptyMap())); // default test when convertInterfaceNodeType is right result = testSubject.exportComponentInterface(component, false); @@ -450,7 +449,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { Map nodeTypes = new HashMap<>(); Either result; - Mockito.when(dataTypeCache.getAll()).thenReturn(Either.right(TitanOperationStatus.ALREADY_EXIST)); + Mockito.when(dataTypeCache.getAll()).thenReturn(Either.right(JanusGraphOperationStatus.ALREADY_EXIST)); Mockito.when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()) .thenReturn(Either.left(Collections.emptyMap())); // default test diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserBusinessLogicTest.java index b31ed58713..9c34b1d3f0 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserBusinessLogicTest.java @@ -12,13 +12,12 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.api.UserRoleEnum; import org.openecomp.sdc.exception.ResponseFormat; @@ -36,7 +35,7 @@ public class UserBusinessLogicTest { @Mock private ComponentsUtils componentsUtils; @Mock - private TitanGenericDao titanDao; + private JanusGraphGenericDao janusGraphDao; @Before public void setUp() { @@ -339,8 +338,8 @@ public class UserBusinessLogicTest { Mockito.when(userAdminOperation.getUserData(userIdToUpdate, false)).thenReturn(value2); List list = new LinkedList<>(); - list.add(new DetachedEdge("sdas", "fdfs", new HashMap<>(), Pair.with("sadas", "sadasd"), - Pair.with("sadas", "sadasd"))); + list.add(new DetachedEdge("sdas", "fdfs", new HashMap<>(),"sadas","sadasd", + "sadas","sadasd" )); Either, StorageOperationStatus> value3 = Either.left(list); Mockito.when(userAdminOperation.getUserPendingTasksList(Mockito.any(), Mockito.any())).thenReturn(value3); @@ -657,7 +656,7 @@ public class UserBusinessLogicTest { Mockito.when(userAdminOperation.getUserData("mockDU", false)).thenReturn(value2); LinkedList a = new LinkedList<>(); a.add(new DetachedEdge(userUniuqeIdToDeactive, userUniuqeIdToDeactive, new HashMap<>(), - Pair.with("dsfds", "dsfds"), Pair.with("dsfds", "dsfds"))); + "dsfds","dsfds", "dsfds", "dsfds")); Either, StorageOperationStatus> value3 = Either.left(a); Mockito.when(userAdminOperation.getUserPendingTasksList(Mockito.any(), Mockito.any())).thenReturn(value3); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java index 900fdc569a..091e15661c 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java @@ -28,8 +28,8 @@ import org.mockito.Mockito; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; import org.openecomp.sdc.be.dao.impl.ESCatalogDAO; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.impl.ExternalConfiguration; @@ -48,17 +48,17 @@ import static org.mockito.Mockito.when; public class SdncTransactionTest { private static ESCatalogDAO esCatalogDao = Mockito.mock(ESCatalogDAO.class); - private static TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + private static JanusGraphGenericDao janusGraphGenericDao = Mockito.mock(JanusGraphGenericDao.class); private static final Logger log = Mockito.spy(Logger.getLogger(SdncTransactionTest.class)); private static int transactionId = 0; private static ConfigurationManager configurationManager; public enum TestAction { - TitanAction, Rollback, GeneralAction + JanusGraphAction, Rollback, GeneralAction } public enum TestResponse { - TitanResponseSuccess, GeneralSuccess + JanusGraphResponseSuccess, GeneralSuccess } @BeforeClass @@ -75,22 +75,24 @@ public class SdncTransactionTest { public void beforeTest() { reset(log); reset(esCatalogDao); - reset(titanGenericDao); + reset(janusGraphGenericDao); } @Test - public void testInvokeTitanAction() { + public void testInvokeJanusGraphAction() { int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, + janusGraphGenericDao); - doBasicTitanAction(transactionId, tx, false, true); + doBasicJanusGraphAction(transactionId, tx, false, true); assertSame(tx.getStatus(), TransactionStatusEnum.OPEN); } @Test public void testInvokeESAction() { int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, + janusGraphGenericDao); doESAddArtifactAction(transactionId, tx, true, true); assertSame(tx.getStatus(), TransactionStatusEnum.OPEN); @@ -99,7 +101,8 @@ public class SdncTransactionTest { @Test public void testfinishTransaction() { int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, + janusGraphGenericDao); doFinishTransaction(transactionId, tx, true); assertSame(tx.getStatus(), TransactionStatusEnum.CLOSED); } @@ -107,7 +110,8 @@ public class SdncTransactionTest { @Test public void testFinishOnClosedTransaction() { int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, + janusGraphGenericDao); doFinishTransaction(transactionId, tx, true); TransactionCodeEnum finishTransaction = tx.finishTransaction(); @@ -120,30 +124,33 @@ public class SdncTransactionTest { @Test public void testCallingLastActionTwice() { int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); - doBasicTitanAction(transactionId, tx, true, true); - Either doBasicTitanAction = doBasicTitanAction(transactionId, tx, true, false); - assertTrue(doBasicTitanAction.isRight()); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, + janusGraphGenericDao); + doBasicJanusGraphAction(transactionId, tx, true, true); + Either doBasicJanusGraphAction = doBasicJanusGraphAction(transactionId, tx, true, false); + assertTrue(doBasicJanusGraphAction.isRight()); assertNotSame(tx.getStatus(), TransactionStatusEnum.OPEN); - verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, DBTypeEnum.JANUSGRAPH + .name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); } @Test public void testActionOnClosedTransaction() { int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, + janusGraphGenericDao); doFinishTransaction(transactionId, tx, true); Either eitherESResult = tx.invokeESAction(false, ESActionTypeEnum.ADD_ARTIFACT, createDummyArtifactData()); assertTrue(eitherESResult.isRight()); assertSame(eitherESResult.right().value(), TransactionCodeEnum.TRANSACTION_CLOSED); - Either eitherTitanResult = tx.invokeTitanAction(false, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess)); - assertTrue(eitherTitanResult.isRight()); - assertSame(eitherTitanResult.right().value(), TransactionCodeEnum.TRANSACTION_CLOSED); + Either eitherJanusGraphResult = tx.invokeJanusGraphAction(false, createBasicAction(TestAction.JanusGraphAction, TestResponse.JanusGraphResponseSuccess)); + assertTrue(eitherJanusGraphResult.isRight()); + assertSame(eitherJanusGraphResult.right().value(), TransactionCodeEnum.TRANSACTION_CLOSED); - Either eitherGeneralDBAction = tx.invokeGeneralDBAction(true, DBTypeEnum.TITAN, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess), - createBasicAction(TestAction.Rollback, TestResponse.TitanResponseSuccess)); + Either eitherGeneralDBAction = tx.invokeGeneralDBAction(true, DBTypeEnum.JANUSGRAPH, createBasicAction(TestAction.JanusGraphAction, TestResponse.JanusGraphResponseSuccess), + createBasicAction(TestAction.Rollback, TestResponse.JanusGraphResponseSuccess)); assertTrue(eitherGeneralDBAction.isRight()); assertSame(eitherGeneralDBAction.right().value(), TransactionCodeEnum.TRANSACTION_CLOSED); @@ -155,9 +162,10 @@ public class SdncTransactionTest { @Test public void testBasicHappyScenario() { int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, + janusGraphGenericDao); - doBasicTitanAction(transactionId, tx, false, true); + doBasicJanusGraphAction(transactionId, tx, false, true); assertSame(tx.getStatus(), TransactionStatusEnum.OPEN); doESAddArtifactAction(transactionId, tx, true, true); @@ -172,23 +180,27 @@ public class SdncTransactionTest { @Test public void testRollbackSucceededOnAction() { int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, + janusGraphGenericDao); doESAddArtifactAction(transactionId, tx, false, true); - when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + when(janusGraphGenericDao.rollback()).thenReturn(JanusGraphOperationStatus.OK); String crushMessage = "DB Crush Simulation"; - Either eitherTransactionResult = tx.invokeTitanAction(false, createCrushingAction(TestAction.TitanAction, crushMessage)); + Either eitherTransactionResult = tx.invokeJanusGraphAction(false, createCrushingAction(TestAction.JanusGraphAction, crushMessage)); assertTrue(eitherTransactionResult.isRight()); assertSame(eitherTransactionResult.right().value(), TransactionCodeEnum.ROLLBACK_SUCCESS); assertSame(tx.getStatus(), TransactionStatusEnum.CLOSED); - verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.TITAN.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.JANUSGRAPH + .name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.JANUSGRAPH + .name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.JANUSGRAPH + .name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); @@ -197,35 +209,40 @@ public class SdncTransactionTest { @Test public void testRollbackFailedOnAction() { int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, + janusGraphGenericDao); doESAddArtifactAction(transactionId, tx, false, true); - when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.NOT_CONNECTED); + when(janusGraphGenericDao.rollback()).thenReturn(JanusGraphOperationStatus.NOT_CONNECTED); String crushMessage = "DB Crush Simulation"; - Either eitherTransactionResult = tx.invokeTitanAction(false, createCrushingAction(TestAction.TitanAction, crushMessage)); + Either eitherTransactionResult = tx.invokeJanusGraphAction(false, createCrushingAction(TestAction.JanusGraphAction, crushMessage)); assertTrue(eitherTransactionResult.isRight()); assertSame(tx.getStatus(), TransactionStatusEnum.FAILED_ROLLBACK); assertSame(eitherTransactionResult.right().value(), TransactionCodeEnum.ROLLBACK_FAILED); - verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.TITAN.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.JANUSGRAPH + .name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.JANUSGRAPH + .name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.JANUSGRAPH + .name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); } @Test public void testRollbackSucceededOnCommit() { int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, + janusGraphGenericDao); doESAddArtifactAction(transactionId, tx, false, true); - doBasicTitanAction(transactionId, tx, true, true); + doBasicJanusGraphAction(transactionId, tx, true, true); - when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.GENERAL_ERROR); - when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + when(janusGraphGenericDao.commit()).thenReturn(JanusGraphOperationStatus.GENERAL_ERROR); + when(janusGraphGenericDao.rollback()).thenReturn(JanusGraphOperationStatus.OK); // finishTransaction TransactionCodeEnum transactionCode = tx.finishTransaction(); assertSame(transactionCode, TransactionCodeEnum.ROLLBACK_SUCCESS); @@ -234,8 +251,10 @@ public class SdncTransactionTest { verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.JANUSGRAPH + .name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.JANUSGRAPH + .name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); @@ -244,12 +263,13 @@ public class SdncTransactionTest { @Test public void testRollbackFailedOnCommit() { int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, + janusGraphGenericDao); doESAddArtifactAction(transactionId, tx, false, true); - doBasicTitanAction(transactionId, tx, true, true); + doBasicJanusGraphAction(transactionId, tx, true, true); - when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.GENERAL_ERROR); - when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + when(janusGraphGenericDao.commit()).thenReturn(JanusGraphOperationStatus.GENERAL_ERROR); + when(janusGraphGenericDao.rollback()).thenReturn(JanusGraphOperationStatus.OK); String esError = "No Connection to Es"; Mockito.doThrow(new RuntimeException(esError)).when(esCatalogDao).deleteArtifact(Mockito.anyString()); // finishTransaction @@ -260,15 +280,18 @@ public class SdncTransactionTest { verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.JANUSGRAPH + .name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.JANUSGRAPH + .name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); } @Test public void testInvokeGeneralAction() { - when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + when(janusGraphGenericDao.rollback()).thenReturn(JanusGraphOperationStatus.OK); int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, + janusGraphGenericDao); IDBAction generalAction = createBasicAction(TestAction.GeneralAction, TestResponse.GeneralSuccess); IDBAction rollbackAction = createBasicAction(TestAction.Rollback, TestResponse.GeneralSuccess); String crushMessage = "No DB Connection"; @@ -294,30 +317,31 @@ public class SdncTransactionTest { } - private Either doBasicTitanAction(int transactionId, TransactionSdncImpl tx, boolean isLastAction, boolean isVerifyAction) { - // Add Titan Action - Either eitherTitanResult = tx.invokeTitanAction(isLastAction, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess)); + private Either doBasicJanusGraphAction(int transactionId, TransactionSdncImpl tx, boolean isLastAction, boolean isVerifyAction) { + // Add JanusGraph Action + Either eitherJanusGraphResult = tx.invokeJanusGraphAction(isLastAction, createBasicAction(TestAction.JanusGraphAction, TestResponse.JanusGraphResponseSuccess)); if (isVerifyAction) { - // Check Titan Action - assertTrue(eitherTitanResult.isLeft()); - assertSame(eitherTitanResult.left().value(), TestResponse.TitanResponseSuccess); - verify(log).debug(TestAction.TitanAction.name()); - verify(log).debug(LogMessages.INVOKE_ACTION, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + // Check JanusGraph Action + assertTrue(eitherJanusGraphResult.isLeft()); + assertSame(eitherJanusGraphResult.left().value(), TestResponse.JanusGraphResponseSuccess); + verify(log).debug(TestAction.JanusGraphAction.name()); + verify(log).debug(LogMessages.INVOKE_ACTION, transactionId, DBTypeEnum.JANUSGRAPH.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); verifyNoErrorsInLog(); verifyNoInfoInLog(); } - return eitherTitanResult; + return eitherJanusGraphResult; } private TransactionCodeEnum doFinishTransaction(int transactionId, TransactionSdncImpl tx, boolean isVerifyAction) { // Prerequisite finishTransaction - when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.OK); + when(janusGraphGenericDao.commit()).thenReturn(JanusGraphOperationStatus.OK); // finishTransaction TransactionCodeEnum transactionCode = tx.finishTransaction(); if (isVerifyAction) { // Check finishTransaction verify(log).debug(LogMessages.COMMIT_ACTION_ALL_DB, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log).debug(LogMessages.COMMIT_ACTION_SPECIFIC_DB, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).debug(LogMessages.COMMIT_ACTION_SPECIFIC_DB, transactionId, DBTypeEnum.JANUSGRAPH + .name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); assertSame(transactionCode, TransactionCodeEnum.SUCCESS); } return transactionCode; @@ -332,7 +356,7 @@ public class SdncTransactionTest { Either eitherEsAction = tx.invokeESAction(isLastAction, ESActionTypeEnum.ADD_ARTIFACT, createDummyArtifactData()); if (isVerifyAction) { - // Check Titan Action + // Check JanusGraph Action assertTrue(eitherEsAction.isLeft()); assertSame(eitherEsAction.left().value(), DBActionCodeEnum.SUCCESS); verify(log).debug(LogMessages.INVOKE_ACTION, transactionId, DBTypeEnum.ELASTIC_SEARCH.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); diff --git a/catalog-be/src/test/resources/config/catalog-be/configuration.yaml b/catalog-be/src/test/resources/config/catalog-be/configuration.yaml index e8bebc8471..803805edf1 100644 --- a/catalog-be/src/test/resources/config/catalog-be/configuration.yaml +++ b/catalog-be/src/test/resources/config/catalog-be/configuration.yaml @@ -26,15 +26,15 @@ released: 2012-11-30 toscaConformanceLevel: 8.0 minToscaConformanceLevel: 3.0 -titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties -titanInMemoryGraph: false -titanLockTimeout: 1800 +janusGraphCfgFile: /home/vagrant/catalog-be/config/catalog-be/janusgraph.properties +janusGraphInMemoryGraph: false +janusGraphLockTimeout: 1800 -# The interval to try and reconnect to titan DB when it is down during ASDC startup: -titanReconnectIntervalInSeconds: 3 +# The interval to try and reconnect to janusgraph DB when it is down during ASDC startup: +janusGraphReconnectIntervalInSeconds: 3 -# The read timeout towards Titan DB when health check is invoked: -titanHealthCheckReadTimeout: 1 +# The read timeout towards JanusGraph DB when health check is invoked: +janusGraphHealthCheckReadTimeout: 1 # The interval to try and reconnect to Elasticsearch when it is down during ASDC startup: esReconnectIntervalInSeconds: 3 diff --git a/catalog-be/src/test/resources/paths/path-context.xml b/catalog-be/src/test/resources/paths/path-context.xml index b9415bfbfa..8f6dea21a7 100644 --- a/catalog-be/src/test/resources/paths/path-context.xml +++ b/catalog-be/src/test/resources/paths/path-context.xml @@ -38,7 +38,7 @@ Modifications copyright (c) 2018 Nokia org.openecomp.sdc.be.dao.neo4j, org.openecomp.sdc.be.model.operations.impl, org.openecomp.sdc.be.model.cache, - org.openecomp.sdc.be.dao.titan, + org.openecomp.sdc.be.dao.janusgraph, org.openecomp.sdc.be.user, org.openecomp.sdc.be.impl, org.openecomp.sdc.be.auditing.impl, @@ -51,8 +51,8 @@ Modifications copyright (c) 2018 Nokia org.openecomp.sdc.be.switchover.detector, org.openecomp.sdc.be.tosca, org.openecomp.sdc.be.model.operations.impl, - org.openecomp.sdc.be.model.jsontitan.operations, - org.openecomp.sdc.be.model.jsontitan.utils, + org.openecomp.sdc.be.model.jsonjanusgraph.operations, + org.openecomp.sdc.be.model.jsonjanusgraph.utils, org.openecomp.sdc.be.components.csar, org.openecomp.sdc.be.datamodel.utils, org.openecomp.sdc.be.model.utils, @@ -79,7 +79,7 @@ Modifications copyright (c) 2018 Nokia - + diff --git a/catalog-dao/pom.xml b/catalog-dao/pom.xml index ee2da543c8..3e04560aa6 100644 --- a/catalog-dao/pom.xml +++ b/catalog-dao/pom.xml @@ -230,11 +230,10 @@ Modifications copyright (c) 2018 Nokia test - - com.thinkaurelius.titan - titan-core - ${titan.version} + org.janusgraph + janusgraph-core + ${janusgraph.version} provided @@ -257,9 +256,9 @@ Modifications copyright (c) 2018 Nokia - org.onap.sdc.sdc-titan-cassandra - sdc-titan-cassandra - ${sdc.titan.version} + org.janusgraph + janusgraph-cassandra + ${janusgraph.version} provided @@ -275,7 +274,6 @@ Modifications copyright (c) 2018 Nokia ${lang3.version} provided - diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/DAOJanusGraphStrategy.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/DAOJanusGraphStrategy.java new file mode 100644 index 0000000000..1a96ebf87b --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/DAOJanusGraphStrategy.java @@ -0,0 +1,32 @@ +/*- + * ============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.dao; + +import org.openecomp.sdc.be.config.ConfigurationManager; + +public class DAOJanusGraphStrategy implements JanusGraphClientStrategy { + + @Override + public String getConfigFile() { + return ConfigurationManager.getConfigurationManager().getConfiguration().getJanusGraphCfgFile(); + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/DAOTitanStrategy.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/DAOTitanStrategy.java deleted file mode 100644 index 2452245616..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/DAOTitanStrategy.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.dao; - -import org.openecomp.sdc.be.config.ConfigurationManager; - -public class DAOTitanStrategy implements TitanClientStrategy { - - @Override - public String getConfigFile() { - return ConfigurationManager.getConfigurationManager().getConfiguration().getTitanCfgFile(); - } - -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/JanusGraphClientStrategy.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/JanusGraphClientStrategy.java new file mode 100644 index 0000000000..14e12e9b04 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/JanusGraphClientStrategy.java @@ -0,0 +1,27 @@ +/*- + * ============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.dao; + +public interface JanusGraphClientStrategy { + + String getConfigFile(); + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/TitanClientStrategy.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/TitanClientStrategy.java deleted file mode 100644 index 36aaec8684..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/TitanClientStrategy.java +++ /dev/null @@ -1,27 +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.dao; - -public interface TitanClientStrategy { - - String getConfigFile(); - -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java index 5af12a8af1..53d71fe3cf 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java @@ -120,7 +120,7 @@ public class SdcSchemaBuilder { Map>> cassndraMetadata = parseKeyspaceMetadata(keyspacesMetadateFromCassandra); log.info("Cassandra Metadata: {}" ,cassndraMetadata); cassndraMetadata.forEach((k, v) -> { - if (AuditingTypesConstants.TITAN_KEYSPACE.equals(k)) { + if (AuditingTypesConstants.janusGraph_KEYSPACE.equals(k)) { // session.execute("") } else if (AuditingTypesConstants.ARTIFACT_KEYSPACE.equals(k)) { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/DAOSpringConfig.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/DAOSpringConfig.java index 99acb3b62b..e40b5aa237 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/DAOSpringConfig.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/DAOSpringConfig.java @@ -26,7 +26,7 @@ import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; @Configuration -@Import({TitanSpringConfig.class}) +@Import({JanusGraphSpringConfig.class}) @ComponentScan({ "org.openecomp.sdc.be.dao.cassandra", "org.openecomp.sdc.be.dao.neo4j", diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/JanusGraphSpringConfig.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/JanusGraphSpringConfig.java new file mode 100644 index 0000000000..d30caf1845 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/JanusGraphSpringConfig.java @@ -0,0 +1,54 @@ +package org.openecomp.sdc.be.dao.config; + +import org.openecomp.sdc.be.dao.DAOJanusGraphStrategy; +import org.openecomp.sdc.be.dao.JanusGraphClientStrategy; +import org.openecomp.sdc.be.dao.impl.HealingPipelineDao; +import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; +import org.openecomp.sdc.be.dao.janusgraph.transactions.SimpleJanusGraphTransactionManager; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@ComponentScan({ + "org.openecomp.sdc.be.dao.jsongraph", +}) +@EnableTransactionManagement +public class JanusGraphSpringConfig { + + @Bean(name = "janusgraph-generic-dao") + @Primary + public HealingJanusGraphGenericDao janusGraphGenericDao(@Qualifier("janusgraph-client") JanusGraphClient janusGraphClient) { + return new HealingJanusGraphGenericDao(janusGraphClient); + } + + @Bean(name = "janusgraph-client", initMethod = "createGraph") + @Primary + public JanusGraphClient janusGraphClient(@Qualifier("dao-client-strategy") + JanusGraphClientStrategy janusGraphClientStrategy) { + return new JanusGraphClient(janusGraphClientStrategy); + } + + @Bean(name = "dao-client-strategy") + public JanusGraphClientStrategy janusGraphClientStrategy() { + return new DAOJanusGraphStrategy(); + } + + @Bean + public PlatformTransactionManager txManager() { + return new SimpleJanusGraphTransactionManager(janusGraphClient(janusGraphClientStrategy())); + } + + @Bean(name = "healingPipelineDao") + public HealingPipelineDao healingPipeline(){ + HealingPipelineDao healingPipelineDao = new HealingPipelineDao(); + healingPipelineDao.setHealVersion(1); + healingPipelineDao.initHealVersion(); + return healingPipelineDao; + } +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/TitanSpringConfig.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/TitanSpringConfig.java deleted file mode 100644 index 34a860ddd2..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/TitanSpringConfig.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.openecomp.sdc.be.dao.config; - -import org.openecomp.sdc.be.dao.DAOTitanStrategy; -import org.openecomp.sdc.be.dao.TitanClientStrategy; -import org.openecomp.sdc.be.dao.impl.HealingPipelineDao; -import org.openecomp.sdc.be.dao.titan.HealingTitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanGraphClient; -import org.openecomp.sdc.be.dao.titan.transactions.SimpleTitanTransactionManager; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -@Configuration -@ComponentScan({ - "org.openecomp.sdc.be.dao.jsongraph", -}) -@EnableTransactionManagement -public class TitanSpringConfig { - - @Bean(name = "titan-generic-dao") - @Primary - public HealingTitanGenericDao titanGenericDao(@Qualifier("titan-client") TitanGraphClient titanGraphClient) { - return new HealingTitanGenericDao(titanGraphClient); - } - - @Bean(name = "titan-client", initMethod = "createGraph") - @Primary - public TitanGraphClient titanGraphClient(@Qualifier("dao-client-strategy") TitanClientStrategy titanClientStrategy) { - return new TitanGraphClient(titanClientStrategy); - } - - @Bean(name = "dao-client-strategy") - public TitanClientStrategy titanClientStrategy() { - return new DAOTitanStrategy(); - } - - @Bean - public PlatformTransactionManager txManager() { - return new SimpleTitanTransactionManager(titanGraphClient(titanClientStrategy())); - } - - @Bean(name = "healingPipelineDao") - public HealingPipelineDao healingPipeline(){ - HealingPipelineDao healingPipelineDao = new HealingPipelineDao(); - healingPipelineDao.setHealVersion(1); - healingPipelineDao.initHealVersion(); - return healingPipelineDao; - } -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/HealingPipelineDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/HealingPipelineDao.java index 5b219b2371..f757b58455 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/HealingPipelineDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/HealingPipelineDao.java @@ -20,7 +20,7 @@ import static java.util.stream.Collectors.joining; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphVertex; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -33,7 +33,7 @@ import org.openecomp.sdc.be.dao.graph.datatype.GraphElement; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.impl.heal.HealGraphDao; import org.openecomp.sdc.be.dao.impl.heal.HealNodeGraphDao; -import org.openecomp.sdc.be.dao.impl.heal.HealTitanGraphDao; +import org.openecomp.sdc.be.dao.impl.heal.HealJanusGraphDao; import org.openecomp.sdc.be.dao.impl.heal.HealVertexGraphDao; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.heal.Heal; @@ -58,7 +58,7 @@ public class HealingPipelineDao { private HealGraphDao healNodeGraphDao; private HealGraphDao healVertexGraphDao; - private HealGraphDao healTitanVertexGraphDao; + private HealGraphDao healJanusGraphVertexGraphDao; public HealingPipelineDao() { healingPipeline = ImmutableListMultimap.of(); @@ -74,7 +74,7 @@ public class HealingPipelineDao { public void initGraphHealers() { healNodeGraphDao = new HealNodeGraphDao(this); healVertexGraphDao = new HealVertexGraphDao(this); - healTitanVertexGraphDao = new HealTitanGraphDao(this); + healJanusGraphVertexGraphDao = new HealJanusGraphDao(this); } @@ -85,8 +85,8 @@ public class HealingPipelineDao { if (graphNode instanceof GraphElement) { return healNodeGraphDao; } - if (graphNode instanceof TitanVertex) { - return healTitanVertexGraphDao; + if (graphNode instanceof JanusGraphVertex) { + return healJanusGraphVertexGraphDao; } return null; @@ -133,7 +133,7 @@ public class HealingPipelineDao { graphVertex.addMetadataProperty(GraphPropertyEnum.HEALING_VERSION, currentHealVersion.getVersion()); } - public void setHealingVersion(TitanVertex graphVertex) { + public void setHealingVersion(JanusGraphVertex graphVertex) { graphVertex.property(GraphPropertyEnum.HEALING_VERSION.getProperty(), currentHealVersion.getVersion()); } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/heal/HealJanusGraphDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/heal/HealJanusGraphDao.java new file mode 100644 index 0000000000..76be4a6e12 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/heal/HealJanusGraphDao.java @@ -0,0 +1,38 @@ +package org.openecomp.sdc.be.dao.impl.heal; + +import org.janusgraph.core.JanusGraphVertex; +import org.openecomp.sdc.be.dao.impl.HealingPipelineDao; +import org.openecomp.sdc.be.dao.jsongraph.heal.Heal; +import org.openecomp.sdc.be.dao.jsongraph.heal.HealConstants; +import org.openecomp.sdc.be.dao.jsongraph.heal.HealVersion; +import org.openecomp.sdc.be.dao.jsongraph.heal.HealVersionBuilder; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; + +public class HealJanusGraphDao implements HealGraphDao { + + private HealingPipelineDao healingPipelineDao; + + public HealJanusGraphDao(HealingPipelineDao healingPipelineDao) { + this.healingPipelineDao = healingPipelineDao; + } + + @Override + public JanusGraphVertex performGraphReadHealing(JanusGraphVertex childVertex, GraphEdgeLabels graphEdgeLabels) { + final Integer healingVersionInt = (Integer) childVertex.property(GraphPropertyEnum.HEALING_VERSION.getProperty()).orElse(HealConstants.DEFAULT_HEAL_VERSION); + HealVersion healingVersion = HealVersionBuilder.build(healingVersionInt); + healingPipelineDao.getHealersForVertex(graphEdgeLabels.name(), healingVersion).forEach(heal -> healGraphVertex(childVertex, heal)); + childVertex.property(GraphPropertyEnum.HEALING_VERSION.getProperty(), healingPipelineDao.getCurrentHealVersion().getVersion()); + return childVertex; + } + + + private JanusGraphVertex healGraphVertex(JanusGraphVertex childVertex, Heal heal) { + heal.healData(childVertex); + final HealVersion healVersion = heal.fromVersion(); + HealVersion newerVersion = HealVersionBuilder.build(healVersion.getVersion() + 1); + childVertex.property(GraphPropertyEnum.HEALING_VERSION.getProperty(), newerVersion); + heal.healData(childVertex); + return childVertex; + } +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/heal/HealNodeGraphDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/heal/HealNodeGraphDao.java index 2fc5c8fc5d..9bc75a0ba1 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/heal/HealNodeGraphDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/heal/HealNodeGraphDao.java @@ -20,12 +20,12 @@ public class HealNodeGraphDao implements HealGraphDao { public GraphNode performGraphReadHealing(GraphNode childVertex, GraphEdge graphEdge) { Integer healingVersionInt = childVertex.getHealingVersion(); HealVersion healingVersion = HealVersionBuilder.build(healingVersionInt); - healingPipelineDao.getHealersForVertex(graphEdge.getEdgeType().getProperty(), healingVersion).forEach(heal -> healTitanVertex(childVertex, heal)); + healingPipelineDao.getHealersForVertex(graphEdge.getEdgeType().getProperty(), healingVersion).forEach(heal -> healJanusGraphVertex(childVertex, heal)); childVertex.setHealingVersion(healingPipelineDao.getCurrentHealVersion().getVersion()); return childVertex; } - private GraphNode healTitanVertex(GraphNode childVertex, Heal heal) { + private GraphNode healJanusGraphVertex(GraphNode childVertex, Heal heal) { heal.healData(childVertex); final HealVersion healVersion = heal.fromVersion(); HealVersion newerVersion = HealVersionBuilder.build(healVersion.getVersion() + 1); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/heal/HealTitanGraphDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/heal/HealTitanGraphDao.java deleted file mode 100644 index 1e33c61b9f..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/heal/HealTitanGraphDao.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.openecomp.sdc.be.dao.impl.heal; - -import com.thinkaurelius.titan.core.TitanVertex; -import org.openecomp.sdc.be.dao.impl.HealingPipelineDao; -import org.openecomp.sdc.be.dao.jsongraph.heal.Heal; -import org.openecomp.sdc.be.dao.jsongraph.heal.HealConstants; -import org.openecomp.sdc.be.dao.jsongraph.heal.HealVersion; -import org.openecomp.sdc.be.dao.jsongraph.heal.HealVersionBuilder; -import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; - -public class HealTitanGraphDao implements HealGraphDao { - - private HealingPipelineDao healingPipelineDao; - - public HealTitanGraphDao(HealingPipelineDao healingPipelineDao) { - this.healingPipelineDao = healingPipelineDao; - } - - @Override - public TitanVertex performGraphReadHealing(TitanVertex childVertex, GraphEdgeLabels graphEdgeLabels) { - final Integer healingVersionInt = (Integer) childVertex.property(GraphPropertyEnum.HEALING_VERSION.getProperty()).orElse(HealConstants.DEFAULT_HEAL_VERSION); - HealVersion healingVersion = HealVersionBuilder.build(healingVersionInt); - healingPipelineDao.getHealersForVertex(graphEdgeLabels.name(), healingVersion).forEach(heal -> healGraphVertex(childVertex, heal)); - childVertex.property(GraphPropertyEnum.HEALING_VERSION.getProperty(), healingPipelineDao.getCurrentHealVersion().getVersion()); - return childVertex; - } - - - private TitanVertex healGraphVertex(TitanVertex childVertex, Heal heal) { - heal.healData(childVertex); - final HealVersion healVersion = heal.fromVersion(); - HealVersion newerVersion = HealVersionBuilder.build(healVersion.getVersion() + 1); - childVertex.property(GraphPropertyEnum.HEALING_VERSION.getProperty(), newerVersion); - heal.healData(childVertex); - return childVertex; - } -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/HealingJanusGraphGenericDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/HealingJanusGraphGenericDao.java new file mode 100644 index 0000000000..f8ab531f04 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/HealingJanusGraphGenericDao.java @@ -0,0 +1,126 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * 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. + */ +package org.openecomp.sdc.be.dao.janusgraph; + +import org.janusgraph.core.JanusGraphVertex; +import fj.data.Either; +import java.util.List; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.dao.impl.HealingPipelineDao; +import org.openecomp.sdc.be.dao.jsongraph.heal.HealConstants; +import org.openecomp.sdc.be.dao.jsongraph.heal.HealVersionBuilder; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component("janusgraph-generic-dao") +public class HealingJanusGraphGenericDao extends JanusGraphGenericDao { + + @Autowired + private HealingPipelineDao healingPipelineDao; + + public HealingJanusGraphGenericDao(JanusGraphClient janusGraphClient) { + super(janusGraphClient); + } + + @Override + public ImmutablePair getChildVertex(JanusGraphVertex childVertex, GraphEdgeLabels edgeType) { + ImmutablePair childVertexEdgeImmutablePair = super.getChildVertex(childVertex, edgeType); + final JanusGraphVertex graphVertex = childVertexEdgeImmutablePair.left; + healingPipelineDao.performGraphReadHealing(graphVertex, edgeType); + healingPipelineDao.setHealingVersion(graphVertex); + return childVertexEdgeImmutablePair; + } + + @Override + public Either>, JanusGraphOperationStatus> getChildrenNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz, boolean withEdges) { + Either>, JanusGraphOperationStatus> either = super.getChildrenNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz, withEdges); + if (either.isRight()) { + return either; + } + List> list = either.left().value(); + list.forEach(this::transformPair); + return either; + } + + @Override + public Either, JanusGraphOperationStatus> getChild(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz) { + Either, JanusGraphOperationStatus> eitherChild = super.getChild(key, uniqueId, edgeType, nodeTypeEnum, clazz); + if (eitherChild.isRight()) { + return eitherChild; + } + ImmutablePair pair = eitherChild.left().value(); + GraphNode graphNode = pair.left; + GraphEdge graphEdge = pair.right; + healingPipelineDao.performGraphReadHealing(graphNode, graphEdge); + healingPipelineDao.setHealingVersion(graphNode); + return eitherChild; + } + + private void transformPair(ImmutablePair either) { + GraphEdge edgeType = either.right; + GraphNode childVertex = either.left; + Integer healingVersioInt = childVertex.getHealingVersion(); + HealVersionBuilder.build(healingVersioInt); + healingPipelineDao.performGraphReadHealing(childVertex, edgeType); + healingPipelineDao.setHealingVersion(childVertex); + } + + @Override + public Either>, JanusGraphOperationStatus> getChildrenVertecies(String key, String uniqueId, GraphEdgeLabels edgeType) { + Either>, JanusGraphOperationStatus> either = super.getChildrenVertecies(key, uniqueId, edgeType); + if (either.isRight()) { + return either; + } + List> list = either.left().value(); + list.forEach(this::transformVertexPair); + return either; + } + + private void transformVertexPair(ImmutablePair either) { + String edgeType = either.right.label(); + JanusGraphVertex childVertex = either.left; + VertexProperty healingVersionProperty = childVertex.property(GraphPropertyEnum.HEALING_VERSION.getProperty()); + Integer healingVersioInt = healingVersionProperty.orElse(HealConstants.DEFAULT_HEAL_VERSION); + HealVersionBuilder.build(healingVersioInt); + healingPipelineDao.performGraphReadHealing(childVertex, edgeType); + healingPipelineDao.setHealingVersion(childVertex); + } + + @Override + public Either updateNode(GraphNode node, Class clazz) { + healingPipelineDao.setHealingVersion(node); + return super.updateNode(node, clazz); + } + + @Override + public JanusGraphOperationStatus updateVertex(GraphNode node, Vertex vertex) { + healingPipelineDao.setHealingVersion(node); + return super.updateVertex(node, vertex); + } + + + public void setHealingPipelineDao(HealingPipelineDao healingPipelineDao) { + this.healingPipelineDao = healingPipelineDao; + } +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphClient.java new file mode 100644 index 0000000000..5be907cc86 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphClient.java @@ -0,0 +1,412 @@ +/*- + * ============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.dao.janusgraph; + +import org.janusgraph.core.*; +import org.janusgraph.core.schema.ConsistencyModifier; +import org.janusgraph.core.schema.JanusGraphIndex; +import org.janusgraph.core.schema.JanusGraphManagement; +import org.janusgraph.diskstorage.BackendException; +import org.janusgraph.diskstorage.ResourceUnavailableException; +import org.janusgraph.diskstorage.locking.PermanentLockingException; +import org.janusgraph.graphdb.database.idassigner.IDPoolExhaustedException; +import fj.data.Either; +import org.apache.commons.configuration.BaseConfiguration; +import org.apache.tinkerpop.gremlin.structure.T; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.DAOJanusGraphStrategy; +import org.openecomp.sdc.be.dao.JanusGraphClientStrategy; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.concurrent.*; + + +@Component("janusgraph-client") +public class JanusGraphClient { + private static Logger logger = LoggerFactory.getLogger(JanusGraphClient.class.getName()); + private static Logger healthLogger = LoggerFactory.getLogger("janusgraph.healthcheck"); + + private static final String HEALTH_CHECK = GraphPropertiesDictionary.HEALTH_CHECK.getProperty(); + private static final String OK = "GOOD"; + + public JanusGraphClient() { + } + + private class HealthCheckTask implements Callable { + @Override + public Vertex call() { + + JanusGraphVertex v = (JanusGraphVertex) graph.query().has(HEALTH_CHECK, OK).vertices().iterator().next(); + JanusGraphVertexProperty property = v.property("healthcheck", OK + "_" + System.currentTimeMillis()); + healthLogger.trace("Health Check Node Found...{}", v.property(HEALTH_CHECK)); + graph.tx().commit(); + + return v; + } + } + + private class HealthCheckScheduledTask implements Runnable { + @Override + public void run() { + healthLogger.trace("Executing janusGraph Health Check Task - Start"); + boolean healthStatus = isGraphOpen(); + healthLogger.trace("Executing janusGraph Health Check Task - Status = {}", healthStatus); + if (healthStatus != lastHealthState) { + logger.trace("janusGraph Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus); + lastHealthState = healthStatus; + logAlarm(); + } + } + } + + private class ReconnectTask implements Runnable { + @Override + public void run() { + logger.trace("Trying to reconnect to JanusGraph..."); + if (graph == null) { + createGraph(janusGraphCfgFile); + } + } + } + + private JanusGraph graph; + + // Health Check Variables + + /** + * This executor will execute the health check task on a callable task that can be executed with a timeout. + */ + ExecutorService healthCheckExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "JanusGraph-Health-Check-Thread"); + } + }); + private long healthCheckReadTimeout = 2; + HealthCheckTask healthCallableTask = new HealthCheckTask(); + HealthCheckScheduledTask healthCheckScheduledTask = new HealthCheckScheduledTask(); + boolean lastHealthState = false; + + // Reconnection variables + private ScheduledExecutorService reconnectScheduler = null; + private ScheduledExecutorService healthCheckScheduler = null; + private Runnable reconnectTask = null; + private long reconnectInterval = 3; + @SuppressWarnings("rawtypes") + private Future reconnectFuture; + + private String janusGraphCfgFile = null; + JanusGraphClientStrategy janusGraphClientStrategy; + + public JanusGraphClient(JanusGraphClientStrategy janusGraphClientStrategy) { + super(); + this.janusGraphClientStrategy = janusGraphClientStrategy; + + // Initialize a single threaded scheduler for health-check + this.healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "JanusGraph-Health-Check-Task"); + } + }); + + healthCheckReadTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getJanusGraphHealthCheckReadTimeout(2); + reconnectInterval = ConfigurationManager.getConfigurationManager().getConfiguration().getJanusGraphReconnectIntervalInSeconds(3); + + logger.info("** JanusGraphClient created"); + } + + @PostConstruct + public JanusGraphOperationStatus createGraph() { + + logger.info("** createGraph started **"); + + if (ConfigurationManager.getConfigurationManager().getConfiguration().getJanusGraphInMemoryGraph()) { + BaseConfiguration conf = new BaseConfiguration(); + conf.setProperty("storage.backend", "inmemory"); + graph = JanusGraphFactory.open(conf); + createJanusGraphSchema(); + logger.info("** in memory graph created"); + return JanusGraphOperationStatus.OK; + } else { + this.janusGraphCfgFile = janusGraphClientStrategy.getConfigFile(); + if (janusGraphCfgFile == null || janusGraphCfgFile.isEmpty()) { + janusGraphCfgFile = "config/janusgraph.properties"; + } + + // yavivi + // In case connection failed on init time, schedule a reconnect task + // in the BG + JanusGraphOperationStatus status = createGraph(janusGraphCfgFile); + logger.debug("Create JanusGraph graph status {}", status); + if (status != JanusGraphOperationStatus.OK) { + this.startReconnectTask(); + } + + return status; + } + } + + private void startHealthCheckTask() { + this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS); + } + + /** + * This method will be invoked ONLY on init time in case JanusGraph storage is down. + */ + private void startReconnectTask() { + this.reconnectTask = new ReconnectTask(); + // Initialize a single threaded scheduler + this.reconnectScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "JanusGraph-Reconnect-Task"); + } + }); + + logger.info("Scheduling reconnect task {} with interval of {} seconds", reconnectTask, reconnectInterval); + reconnectFuture = this.reconnectScheduler.scheduleAtFixedRate(this.reconnectTask, 0, this.reconnectInterval, TimeUnit.SECONDS); + } + + public void cleanupGraph() { + if (graph != null) { + // graph.shutdown(); + graph.close(); + try { + JanusGraphFactory.drop(graph); + } catch (BackendException e) { + e.printStackTrace(); + } + } + } + + private boolean graphInitialized(){ + JanusGraphManagement graphMgmt = graph.openManagement(); + return graphMgmt.containsPropertyKey(HEALTH_CHECK) && graphMgmt.containsGraphIndex(HEALTH_CHECK); + } + + + public JanusGraphOperationStatus createGraph(String janusGraphCfgFile) { + logger.info("** open graph with {} started", janusGraphCfgFile); + try { + logger.info("openGraph : try to load file {}", janusGraphCfgFile); + graph = JanusGraphFactory.open(janusGraphCfgFile); + if (graph.isClosed() || !graphInitialized()) { + logger.error("janusgraph graph was not initialized"); + return JanusGraphOperationStatus.NOT_CREATED; + } + + } catch (Exception e) { + this.graph = null; + logger.info("createGraph : failed to open JanusGraph graph with configuration file: {}", janusGraphCfgFile); + logger.debug("createGraph : failed with exception.", e); + return JanusGraphOperationStatus.NOT_CONNECTED; + } + + logger.info("** JanusGraph graph created "); + + // Do some post creation actions + this.onGraphOpened(); + + return JanusGraphOperationStatus.OK; + } + + private void onGraphOpened() { + // if a reconnect task is running, cancel it. + if (this.reconnectFuture != null) { + logger.info("** Cancelling JanusGraph reconnect task"); + reconnectFuture.cancel(true); + } + + // create health-check node + if (!graph.query().has(HEALTH_CHECK, OK).vertices().iterator().hasNext()) { + logger.trace("Healthcheck Singleton node does not exist, Creating healthcheck node..."); + Vertex healthCheckNode = graph.addVertex(); + healthCheckNode.property(HEALTH_CHECK, OK); + logger.trace("Healthcheck node created successfully. ID={}", healthCheckNode.property(T.id.getAccessor())); + graph.tx().commit(); + } else { + logger.trace("Skipping Healthcheck Singleton node creation. Already exist..."); + } + this.startHealthCheckTask(); + } + + + public Either getGraph() { + if (graph != null) { + return Either.left(graph); + } else { + return Either.right(JanusGraphOperationStatus.NOT_CREATED); + } + } + + public JanusGraphOperationStatus commit() { + if (graph != null) { + try { + graph.tx().commit(); + return JanusGraphOperationStatus.OK; + } catch (Exception e) { + return handleJanusGraphException(e); + } + } else { + return JanusGraphOperationStatus.NOT_CREATED; + } + } + + public JanusGraphOperationStatus rollback() { + if (graph != null) { + try { + // graph.rollback(); + graph.tx().rollback(); + return JanusGraphOperationStatus.OK; + } catch (Exception e) { + return handleJanusGraphException(e); + } + } else { + return JanusGraphOperationStatus.NOT_CREATED; + } + } + + public static JanusGraphOperationStatus handleJanusGraphException(Exception e) { + if (e instanceof JanusGraphConfigurationException) { + return JanusGraphOperationStatus.JANUSGRAPH_CONFIGURATION; + } + if (e instanceof SchemaViolationException) { + return JanusGraphOperationStatus.JANUSGRAPH_SCHEMA_VIOLATION; + } + if (e instanceof PermanentLockingException) { + return JanusGraphOperationStatus.JANUSGRAPH_SCHEMA_VIOLATION; + } + if (e instanceof IDPoolExhaustedException) { + return JanusGraphOperationStatus.GENERAL_ERROR; + } + if (e instanceof InvalidElementException) { + return JanusGraphOperationStatus.INVALID_ELEMENT; + } + if (e instanceof InvalidIDException) { + return JanusGraphOperationStatus.INVALID_ID; + } + if (e instanceof QueryException) { + return JanusGraphOperationStatus.INVALID_QUERY; + } + if (e instanceof ResourceUnavailableException) { + return JanusGraphOperationStatus.RESOURCE_UNAVAILABLE; + } + if (e instanceof IllegalArgumentException) { + // TODO check the error message?? + return JanusGraphOperationStatus.ILLEGAL_ARGUMENT; + } + + return JanusGraphOperationStatus.GENERAL_ERROR; + } + + public boolean getHealth() { + return this.lastHealthState; + } + + private boolean isGraphOpen() { + healthLogger.trace("Invoking JanusGraph health check ..."); + Vertex v = null; + if (graph != null) { + try { + Future future = healthCheckExecutor.submit(healthCallableTask); + v = future.get(this.healthCheckReadTimeout, TimeUnit.SECONDS); + healthLogger.trace("Health Check Node Found... {}", v.property(HEALTH_CHECK)); + graph.tx().commit(); + } catch (Exception e) { + String message = e.getMessage(); + if (message == null) { + message = e.getClass().getName(); + } + logger.error("JanusGraph Health Check Failed. {}", message); + return false; + } + return true; + } else { + return false; + } + } + + + public static void main(String[] args) throws InterruptedException { + JanusGraphClient client = new JanusGraphClient(new DAOJanusGraphStrategy()); + client.createGraph(); + + while (true) { + boolean health = client.isGraphOpen(); + System.err.println("health=" + health); + Thread.sleep(2000); + } + + } + + + private static final String JANUSGRAPH_HEALTH_CHECK = "janusgraphHealthCheck"; + + private void logAlarm() { + if (lastHealthState) { + BeEcompErrorManager.getInstance().logBeHealthCheckJanusGraphRecovery(JANUSGRAPH_HEALTH_CHECK); + } else { + BeEcompErrorManager.getInstance().logBeHealthCheckJanusGraphError(JANUSGRAPH_HEALTH_CHECK); + } + } + + private void createJanusGraphSchema() { + + JanusGraphManagement graphMgt = graph.openManagement(); + JanusGraphIndex index = null; + for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) { + PropertyKey propKey = null; + if (!graphMgt.containsPropertyKey(prop.getProperty())) { + Class clazz = prop.getClazz(); + if (!clazz.isAssignableFrom(ArrayList.class) && !clazz.isAssignableFrom(HashMap.class)) { + propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); + } + } else { + propKey = graphMgt.getPropertyKey(prop.getProperty()); + } + if (prop.isIndexed()) { + if (!graphMgt.containsGraphIndex(prop.getProperty())) { + if (prop.isUnique()) { + index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex(); + // Ensures only one name per vertex + graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); + // Ensures name uniqueness in the graph + graphMgt.setConsistency(index, ConsistencyModifier.LOCK); + + } else { + graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex(); + } + } + } + } + graphMgt.commit(); + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphGenericDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphGenericDao.java new file mode 100644 index 0000000000..591d7f32d7 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphGenericDao.java @@ -0,0 +1,1770 @@ +/*- + * ============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.dao.janusgraph; + +import org.janusgraph.core.PropertyKey; +import org.janusgraph.core.JanusGraphEdge; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphQuery; +import org.janusgraph.core.JanusGraphVertex; +import org.janusgraph.core.JanusGraphVertexQuery; +import org.janusgraph.graphdb.query.JanusGraphPredicate; +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.Map.Entry; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.ImmutableTriple; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Element; +import org.apache.tinkerpop.gremlin.structure.Property; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.util.ElementHelper; +import org.openecomp.sdc.be.config.ConfigurationManager; +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.GraphPropertiesDictionary; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.resources.data.GraphNodeLock; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.beans.factory.annotation.Qualifier; + +public class JanusGraphGenericDao { + + private static final String FAILED_TO_RETRIEVE_GRAPH_STATUS_IS = "Failed to retrieve graph. status is {}"; + private static final String NO_EDGES_IN_GRAPH_FOR_CRITERIA = "No edges in graph for criteria"; + private static final String FAILED_TO_CREATE_EDGE_FROM_TO = "Failed to create edge from [{}] to [{}]"; + private JanusGraphClient janusGraphClient; + private static Logger log = Logger.getLogger(JanusGraphGenericDao.class.getName()); + private static final String LOCK_NODE_PREFIX = "lock_"; + + public JanusGraphGenericDao(@Qualifier("janusgraph-client") JanusGraphClient janusGraphClient) { + this.janusGraphClient = janusGraphClient; + log.info("** JanusGraphGenericDao created"); + } + + public JanusGraphOperationStatus commit() { + log.debug("doing commit."); + return janusGraphClient.commit(); + } + + public JanusGraphOperationStatus rollback() { + log.error("Going to execute rollback on graph."); + return janusGraphClient.rollback(); + } + + public void handleTransactionCommitRollback(boolean inTransaction, Either result) { + if (!inTransaction) { + if (result == null || result.isRight()) { + rollback(); + } else { + commit(); + } + } + } + + public Either getGraph() { + return janusGraphClient.getGraph(); + } + + // For healthCheck + public boolean isGraphOpen() { + return janusGraphClient.getHealth(); + } + + /** + * + * @param node + * @param clazz + * @return + */ + public Either createNode(T node, Class clazz) { + log.debug("try to create node for ID [{}]", node.getKeyValueId()); + Either graph = janusGraphClient.getGraph(); + if (graph.isLeft()) { + T newNode; + try { + JanusGraph tGraph = graph.left().value(); + + Vertex vertex = tGraph.addVertex(); + + vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), node.getLabel()); + + Map properties = node.toGraphMap(); + if (properties != null) { + setProperties(vertex, properties); + } + Map newProps = getProperties(vertex); + newNode = GraphElementFactory.createElement(node.getLabel(), GraphElementTypeEnum.Node, newProps, clazz); + log.debug("created node for props : {}", newProps); + log.debug("Node was created for ID [{}]", node.getKeyValueId()); + return Either.left(newNode); + + } catch (Exception e) { + log.debug("Failed to create Node for ID [{}]", node.getKeyValueId(), e); + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + + } else { + log.debug("Failed to create Node for ID [{}] {}", node.getKeyValueId(), graph.right().value()); + return Either.right(graph.right().value()); + } + } + + public Either createNode(GraphNode node) { + log.debug("try to create node for ID [{}]", node.getKeyValueId()); + Either graph = janusGraphClient.getGraph(); + if (graph.isLeft()) { + try { + JanusGraph tGraph = graph.left().value(); + + JanusGraphVertex vertex = tGraph.addVertex(); + + vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), node.getLabel()); + + Map properties = node.toGraphMap(); + if (properties != null) { + setProperties(vertex, properties); + } + log.debug("Node was created for ID [{}]", node.getKeyValueId()); + return Either.left(vertex); + + } catch (Exception e) { + log.debug("Failed to create Node for ID [{}]", node.getKeyValueId(), e); + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + + } else { + log.debug("Failed to create Node for ID [{}] {}", node.getKeyValueId(), graph.right().value()); + return Either.right(graph.right().value()); + } + } + + /** + * + * @param relation + * @return + */ + public Either createRelation(GraphRelation relation) { + log.debug("try to create relation from [{}] to [{}] ", relation.getFrom(), relation.getTo()); + + RelationEndPoint from = relation.getFrom(); + RelationEndPoint to = relation.getTo(); + ImmutablePair fromKeyId = new ImmutablePair<>(from.getIdName(), from.getIdValue()); + ImmutablePair toKeyId = new ImmutablePair<>(to.getIdName(), to.getIdValue()); + + return createEdge(relation.getType(), fromKeyId, toKeyId, from.getLabel().getName(), to.getLabel().getName(), relation.toGraphMap()); + + } + + private Either createEdge(String type, ImmutablePair from, ImmutablePair to, String fromLabel, String toLabel, Map properties) { + Either graph = janusGraphClient.getGraph(); + + if (graph.isLeft()) { + try { + Either fromV = getVertexByPropertyAndLabel(from.getKey(), from.getValue(), fromLabel); + if (fromV.isRight()) { + JanusGraphOperationStatus error = fromV.right().value(); + if (JanusGraphOperationStatus.NOT_FOUND.equals(error)) { + return Either.right(JanusGraphOperationStatus.INVALID_ID); + } else { + return Either.right(error); + } + } + Either toV = getVertexByPropertyAndLabel(to.getKey(), to.getValue(), toLabel); + if (toV.isRight()) { + JanusGraphOperationStatus error = toV.right().value(); + if (JanusGraphOperationStatus.NOT_FOUND.equals(error)) { + return Either.right(JanusGraphOperationStatus.INVALID_ID); + } else { + return Either.right(error); + } + } + + Vertex fromVertex = fromV.left().value(); + Vertex toVertex = toV.left().value(); + Edge edge = fromVertex.addEdge(type, toVertex); + + if (properties != null) { + + setProperties(edge, properties); + } + + Vertex vertexOut = edge.outVertex(); + Vertex vertexIn = edge.inVertex(); + + GraphNode nodeOut = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(vertexOut), GraphNode.class); + GraphNode nodeIn = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(vertexIn), GraphNode.class); + + GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeOut, nodeIn); + + return Either.left(newRelation); + } catch (Exception e) { + log.debug(FAILED_TO_CREATE_EDGE_FROM_TO, from, to, e); + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + } else { + log.debug("Failed to create edge from [{}] to [{}] {}", from, to, graph.right().value()); + return Either.right(graph.right().value()); + } + } + + public JanusGraphOperationStatus createEdge(Vertex vertexOut, Vertex vertexIn, GraphEdgeLabels type, Map properties) { + try { + Edge edge = addEdge(vertexOut, vertexIn, type, properties); + } catch (Exception e) { + log.debug(FAILED_TO_CREATE_EDGE_FROM_TO, vertexOut, vertexIn, e); + return JanusGraphClient.handleJanusGraphException(e); + } + return JanusGraphOperationStatus.OK; + + } + + private Edge addEdge(Vertex vertexOut, Vertex vertexIn, GraphEdgeLabels type, Map properties) { + Edge edge = vertexOut.addEdge(type.getProperty(), vertexIn); + + if (properties != null) { + + setProperties(edge, properties); + } + return edge; + } + + /** + * creates an identical edge in the graph + * @param edge + * @return the copy operation status + */ + public Either copyEdge(Vertex out, Vertex in, Edge edge) { + GraphEdgeLabels byName = GraphEdgeLabels.getByName(edge.label()); + return this.saveEdge(out, in, byName, edgePropertiesToMap(edge)); + } + + private Map edgePropertiesToMap(Edge edge) { + Iterable> propertiesIterable = edge::properties; + return StreamSupport.stream(propertiesIterable.spliterator(), false).collect(Collectors.toMap(Property::key, Property::value)); + } + + public Either saveEdge(Vertex vertexOut, Vertex vertexIn, GraphEdgeLabels type, Map properties) { + try { + Edge edge = addEdge(vertexOut, vertexIn, type, properties); + return Either.left(edge); + } catch (Exception e) { + log.debug(FAILED_TO_CREATE_EDGE_FROM_TO, vertexOut, vertexIn, e); + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + + } + + public JanusGraphOperationStatus createEdge(JanusGraphVertex vertexOut, GraphNode to, GraphEdgeLabels type, Map properties) { + + JanusGraphVertex vertexIn; + Either toV = getVertexByPropertyAndLabel(to.getUniqueIdKey(), to.getUniqueId(), to.getLabel()); + if (toV.isRight()) { + JanusGraphOperationStatus error = toV.right().value(); + if (JanusGraphOperationStatus.NOT_FOUND.equals(error)) { + return JanusGraphOperationStatus.INVALID_ID; + } else { + return error; + } + } + vertexIn = (JanusGraphVertex) toV.left().value(); + return createEdge(vertexOut, vertexIn, type, properties); + } + + /** + * + * @param from + * @param to + * @param label + * @param properties + * @return + */ + public Either createRelation(GraphNode from, GraphNode to, GraphEdgeLabels label, Map properties) { + log.debug("try to create relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); + return createEdge(label.getProperty(), from.getKeyValueId(), to.getKeyValueId(), from.getLabel(), to.getLabel(), properties); + } + + public Either replaceRelationLabel(GraphNode from, GraphNode to, GraphEdgeLabels label, GraphEdgeLabels newLabel) { + + log.debug("try to replace relation {} to {} from [{}] to [{}]", label.name(), newLabel.name(), from.getKeyValueId(), to.getKeyValueId()); + Either getRelationResult = getRelation(from, to, label); + if (getRelationResult.isRight()) { + return getRelationResult; + } + + GraphRelation origRelation = getRelationResult.left().value(); + Either createRelationResult = createRelation(from, to, newLabel, origRelation.toGraphMap()); + if (createRelationResult.isRight()) { + return createRelationResult; + } + + Either deleteRelationResult = deleteRelation(origRelation); + if (deleteRelationResult.isRight()) { + return deleteRelationResult; + } + return Either.left(createRelationResult.left().value()); + } + + /** + * + * @param keyName + * @param keyValue + * @param clazz + * @return + */ + public Either getNode(String keyName, Object keyValue, Class clazz) { + + log.debug("Try to get node for key [{}] with value [{}] ", keyName, keyValue); + + Either vertexByProperty = getVertexByProperty(keyName, keyValue); + + if (vertexByProperty.isLeft()) { + try { + Vertex vertex = vertexByProperty.left().value(); + Map properties = getProperties(vertex); + T node = GraphElementFactory.createElement((String) properties.get(GraphPropertiesDictionary.LABEL.getProperty()), GraphElementTypeEnum.Node, properties, clazz); + return Either.left(node); + } catch (Exception e) { + log.debug("Failed to get node for key [{}] with value [{}] ", keyName, keyValue, e); + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + } else { + log.debug("Failed to get node for key [{}] with value [{}] ", keyName, keyValue, vertexByProperty.right().value()); + return Either.right(vertexByProperty.right().value()); + } + } + + /** + * + * @param from + * @param to + * @param label + * @return + */ + public Either getRelation(GraphNode from, GraphNode to, GraphEdgeLabels label) { + log.debug("try to get relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); + + Either edge = getEdgeByNodes(from, to, label); + + if (edge.isLeft()) { + try { + Map properties = getProperties(edge.left().value()); + GraphRelation relation = GraphElementFactory.createRelation(label.getProperty(), properties, from, to); + return Either.left(relation); + } catch (Exception e) { + log.debug("Failed to get get relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId(), e); + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + } else { + log.debug("Failed to get get relation from [{}] to [{}] {}", from.getKeyValueId(), to.getKeyValueId(), edge.right().value()); + return Either.right(edge.right().value()); + } + } + + public Either getEdgeByNodes(GraphNode from, GraphNode to, GraphEdgeLabels label) { + ImmutablePair keyValueIdFrom = from.getKeyValueId(); + ImmutablePair keyValueIdTo = to.getKeyValueId(); + + return getEdgeByVerticies(keyValueIdFrom.getKey(), keyValueIdFrom.getValue(), keyValueIdTo.getKey(), keyValueIdTo.getValue(), label.getProperty()); + } + + public Either deleteIncomingRelationByCriteria(GraphNode to, GraphEdgeLabels label, Map props) { + + Either edgeByCriteria = getIncomingEdgeByCriteria(to, label, props); + if (edgeByCriteria.isLeft()) { + Either graph = getGraph(); + if (graph.isLeft()) { + Edge edge = edgeByCriteria.left().value(); + log.debug("delete edge {} to {} ", label.getProperty(), to.getUniqueId()); + edge.remove(); + Map properties = getProperties(edge); + Vertex fromVertex = edge.outVertex(); + String fromLabel = fromVertex.value(GraphPropertiesDictionary.LABEL.getProperty()); + GraphNode nodeFrom = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(fromVertex), GraphNode.class); + GraphRelation relation = GraphElementFactory.createRelation(label.getProperty(), properties, nodeFrom, to); + return Either.left(relation); + } else { + log.debug("failed to get graph"); + return Either.right(graph.right().value()); + } + + } else { + log.debug("failed to find edge {} to {}", label.getProperty(), to.getUniqueId()); + return Either.right(edgeByCriteria.right().value()); + } + + } + + public Either getIncomingRelationByCriteria(GraphNode to, GraphEdgeLabels label, Map props) { + + Either edgeByCriteria = getIncomingEdgeByCriteria(to, label, props); + if (edgeByCriteria.isLeft()) { + Either graph = getGraph(); + if (graph.isLeft()) { + Edge edge = edgeByCriteria.left().value(); + Map properties = getProperties(edge); + Vertex fromVertex = edge.outVertex(); + String fromLabel = fromVertex.value(GraphPropertiesDictionary.LABEL.getProperty()); + GraphNode nodeFrom = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(fromVertex), GraphNode.class); + GraphRelation relation = GraphElementFactory.createRelation(label.getProperty(), properties, nodeFrom, to); + return Either.left(relation); + } else { + log.debug("failed to get graph"); + return Either.right(graph.right().value()); + } + + } else { + log.debug("failed to find edge {} to {}", label.getProperty(), to.getUniqueId()); + return Either.right(edgeByCriteria.right().value()); + } + + } + + public Either getIncomingEdgeByCriteria(GraphNode to, GraphEdgeLabels label, Map props) { + + ImmutablePair keyValueIdTo = to.getKeyValueId(); + + Either vertexFrom = getVertexByProperty(keyValueIdTo.getKey(), keyValueIdTo.getValue()); + if (vertexFrom.isRight()) { + return Either.right(vertexFrom.right().value()); + } + Vertex vertex = vertexFrom.left().value(); + JanusGraphVertex janusGraphVertex = (JanusGraphVertex) vertex; + JanusGraphVertexQuery query = janusGraphVertex.query(); + query = query.labels(label.getProperty()); + + if (props != null && !props.isEmpty()) { + for (Map.Entry entry : props.entrySet()) { + query = query.has(entry.getKey(), entry.getValue()); + } + } + Edge matchingEdge = null; + Iterable edges = query.edges(); + if (edges == null) { + log.debug(NO_EDGES_IN_GRAPH_FOR_CRITERIA); + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + Iterator eIter = edges.iterator(); + if (eIter.hasNext()) { + matchingEdge = eIter.next(); + } + + if (matchingEdge == null) { + log.debug(NO_EDGES_IN_GRAPH_FOR_CRITERIA); + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + return Either.left(matchingEdge); + } + + public Either getEdgeByVerticies(String keyNameFrom, Object keyValueFrom, String keyNameTo, Object keyValueTo, String label) { + Either graph = janusGraphClient.getGraph(); + + if (graph.isLeft()) { + try { + Either vertexFrom = getVertexByProperty(keyNameFrom, keyValueFrom); + if (vertexFrom.isRight()) { + return Either.right(vertexFrom.right().value()); + } + Iterable edges = vertexFrom.left().value().query().labels(label).edges(); + Iterator eIter = edges.iterator(); + while (eIter.hasNext()) { + Edge edge = eIter.next(); + Vertex vertexIn = edge.inVertex(); + if (vertexIn.value(keyNameTo) != null && vertexIn.value(keyNameTo).equals(keyValueTo) && label.equals(edge.label())) { + return Either.left(edge); + } + } + log.debug("No relation in graph from [{}={}] to [{}={}]", keyNameFrom, keyValueFrom, keyNameTo, keyValueTo); + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } catch (Exception e) { + log.debug("Failed to get get relation from [{}={}] to [{}={}]", keyNameFrom, keyValueFrom, keyNameTo, keyValueTo, e); + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + } else { + return Either.right(graph.right().value()); + } + } + + public Either, JanusGraphOperationStatus> getEdgesForNode(GraphNode node, Direction requestedDirection) { + + Either, JanusGraphOperationStatus> result; + + ImmutablePair keyValueId = node.getKeyValueId(); + Either eitherVertex = getVertexByProperty(keyValueId.getKey(), keyValueId.getValue()); + + if (eitherVertex.isLeft()) { + List edges = prepareEdgesList(eitherVertex.left().value(), requestedDirection); + + result = Either.left(edges); + } else { + result = Either.right(eitherVertex.right().value()); + } + return result; + } + + private List prepareEdgesList(Vertex vertex, Direction requestedDirection) { + List edges = new ArrayList<>(); + Iterator edgesItr = ((JanusGraphVertex) vertex).query().edges().iterator(); + while (edgesItr.hasNext()) { + Edge edge = edgesItr.next(); + Direction currEdgeDirection = getEdgeDirection(vertex, edge); + if (currEdgeDirection == requestedDirection || requestedDirection == Direction.BOTH) { + edges.add(edge); + } + + } + return edges; + } + + private Direction getEdgeDirection(Vertex vertex, Edge edge) { + Direction result; + Vertex vertexOut = edge.outVertex(); + if (vertexOut.equals(vertex)) { + result = Direction.OUT; + } else { + result = Direction.IN; + + } + return result; + } + + /** + * + * @param from + * @param to + * @param label + * @param properties + * @return + */ + public Either updateRelation(GraphNode from, GraphNode to, GraphEdgeLabels label, Map properties) { + log.debug("try to update relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); + return updateEdge(label.getProperty(), from.getKeyValueId(), to.getKeyValueId(), from.getLabel(), to.getLabel(), properties); + } + + private Either updateEdge(String type, ImmutablePair from, ImmutablePair to, String fromLabel, String toLabel, Map properties) { + + Either edgeS = getEdgeByVerticies(from.getKey(), from.getValue(), to.getKey(), to.getValue(), type); + if (edgeS.isLeft()) { + + try { + Edge edge = edgeS.left().value(); + if (properties != null) { + setProperties(edge, properties); + } + + Vertex vertexOut = edge.outVertex(); + Vertex vertexIn = edge.inVertex(); + + GraphNode nodeOut = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(vertexOut), GraphNode.class); + GraphNode nodeIn = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(vertexIn), GraphNode.class); + + GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeOut, nodeIn); + if (log.isDebugEnabled()) { + log.debug("Relation was updated from [{}] to [{}] ", from, to); + } + return Either.left(newRelation); + } catch (Exception e) { + if (log.isDebugEnabled()) { + log.debug("Failed to update relation from [{}] to [{}] ", from, to, e); + } + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + } else { + if (log.isDebugEnabled()) { + log.debug("Failed to update relation from [{}] to [{}] {}", from, to, edgeS.right().value()); + } + return Either.right(edgeS.right().value()); + } + } + + /** + * + * @param relation + * @return + */ + public Either updateRelation(GraphRelation relation) { + log.debug("try to update relation from [{}] to [{}]", relation.getFrom(), relation.getTo()); + RelationEndPoint from = relation.getFrom(); + RelationEndPoint to = relation.getTo(); + ImmutablePair fromKeyId = new ImmutablePair<>(from.getIdName(), from.getIdValue()); + ImmutablePair toKeyId = new ImmutablePair<>(to.getIdName(), to.getIdValue()); + + return updateEdge(relation.getType(), fromKeyId, toKeyId, from.getLabel().getName(), to.getLabel().getName(), relation.toGraphMap()); + + } + + private Either getVertexByPropertyAndLabel(String name, Object value, String label) { + + Either graph = janusGraphClient.getGraph(); + if (graph.isLeft()) { + try { + JanusGraph tGraph = graph.left().value(); + + @SuppressWarnings("unchecked") + Iterable vertecies = tGraph.query().has(name, value).has(GraphPropertiesDictionary.LABEL.getProperty(), label).vertices(); + + java.util.Iterator iterator = vertecies.iterator(); + if (iterator.hasNext()) { + Vertex vertex = iterator.next(); + return Either.left(vertex); + } + if (log.isDebugEnabled()) { + log.debug("No vertex in graph for key =" + name + " and value = " + value + " label = " + label); + } + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } catch (Exception e) { + if (log.isDebugEnabled()) { + log.debug("Failed to get vertex in graph for key ={} and value = {} label = {}",name,value,label); + } + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + + } else { + if (log.isDebugEnabled()) { + log.debug("No vertex in graph for key ={} and value = {} label = {} error : {}",name,value,label,graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + public Either getVertexByProperty(String name, Object value) { + + Either graph = janusGraphClient.getGraph(); + if (value == null) { + if (log.isDebugEnabled()) { + log.debug("No vertex in graph for key = {} and value = {}", name, value); + } + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + if (graph.isLeft()) { + try { + JanusGraph tGraph = graph.left().value(); + + @SuppressWarnings("unchecked") + Iterable vertecies = tGraph.query().has(name, value).vertices(); + + java.util.Iterator iterator = vertecies.iterator(); + if (iterator.hasNext()) { + JanusGraphVertex vertex = iterator.next(); + return Either.left(vertex); + } else { + if (log.isDebugEnabled()) { + log.debug("No vertex in graph for key ={} and value = {}", name, value); + } + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + } catch (Exception e) { + if (log.isDebugEnabled()) { + log.debug("Failed to get vertex in graph for key = {} and value = ", name, value); + } + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + } else { + if (log.isDebugEnabled()) { + log.debug("No vertex in graph for key = {} and value = {} error : {}", name, value, graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + public Either, JanusGraphOperationStatus> getByCriteria(NodeTypeEnum type, Map hasProps, Map hasNotProps, Class clazz) { + Either graph = janusGraphClient.getGraph(); + if (graph.isLeft()) { + try { + JanusGraph tGraph = graph.left().value(); + + JanusGraphQuery query = tGraph.query(); + query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), type.getName()); + + if (hasProps != null && !hasProps.isEmpty()) { + for (Map.Entry entry : hasProps.entrySet()) { + query = query.has(entry.getKey(), entry.getValue()); + } + } + if (hasNotProps != null && !hasNotProps.isEmpty()) { + for (Map.Entry entry : hasNotProps.entrySet()) { + query = query.hasNot(entry.getKey(), entry.getValue()); + } + } + Iterable vertices = query.vertices(); + if (vertices == null) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + Iterator iterator = vertices.iterator(); + List result = new ArrayList<>(); + + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); + + Map newProp = getProperties(vertex); + + T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node, newProp, clazz); + result.add(element); + } + if (log.isDebugEnabled()) { + log.debug("Number of fetced nodes in graph for criteria : from type = {} and properties has = {}, properties hasNot = {} is {}", type, hasProps, hasNotProps, result.size()); + } + if (result.size() == 0) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + return Either.left(result); + } catch (Exception e) { + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type = {}", type, e); + } + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + + } else { + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type ={} error : {}", type, graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + public Either, JanusGraphOperationStatus> getByCriteria(NodeTypeEnum type, Class clazz, List> props) { + Either graph = janusGraphClient.getGraph(); + if (graph.isLeft()) { + try { + JanusGraph tGraph = graph.left().value(); + + JanusGraphQuery query = tGraph.query(); + query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), type.getName()); + for (ImmutableTriple prop : props) { + if (QueryType.HAS.equals(prop.getLeft())) { + query = query.has(prop.getMiddle(), prop.getRight()); + } else { + query = query.hasNot(prop.getMiddle(), prop.getRight()); + } + } + Iterable vertices = query.vertices(); + if (vertices == null) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + Iterator iterator = vertices.iterator(); + List result = new ArrayList<>(); + + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); + + Map newProp = getProperties(vertex); + + T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node, newProp, clazz); + result.add(element); + } + if (result.size() == 0) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + return Either.left(result); + } catch (Exception e) { + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type = {}", type, e); + } + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + + } else { + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type ={} error : {}", type, graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + public Either, JanusGraphOperationStatus> getByCriteria(NodeTypeEnum type, Map props, Class clazz) { + Either graph = janusGraphClient.getGraph(); + if (graph.isLeft()) { + try { + JanusGraph tGraph = graph.left().value(); + + JanusGraphQuery query = tGraph.query(); + query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), type.getName()); + + if (props != null && !props.isEmpty()) { + for (Map.Entry entry : props.entrySet()) { + query = query.has(entry.getKey(), entry.getValue()); + } + } + Iterable vertices = query.vertices(); + if (vertices == null) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + Iterator iterator = vertices.iterator(); + List result = new ArrayList<>(); + + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); + + Map newProp = getProperties(vertex); + + T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node, newProp, clazz); + result.add(element); + } + if (log.isDebugEnabled()) { + log.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size()); + } + if (result.size() == 0) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + return Either.left(result); + } catch (Exception e) { + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); + } + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + + } else { + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + public Either, JanusGraphOperationStatus> getByCriteriaWithPredicate(NodeTypeEnum type, Map> props, Class clazz) { + Either graph = janusGraphClient.getGraph(); + if (graph.isLeft()) { + try { + JanusGraph tGraph = graph.left().value(); + + JanusGraphQuery query = tGraph.query(); + query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), type.getName()); + + if (props != null && !props.isEmpty()) { + JanusGraphPredicate predicate = null; + Object object = null; + for (Map.Entry> entry : props.entrySet()) { + predicate = entry.getValue().getKey(); + object = entry.getValue().getValue(); + query = query.has(entry.getKey(), predicate, object); + } + } + Iterable vertices = query.vertices(); + if (vertices == null) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + Iterator iterator = vertices.iterator(); + List result = new ArrayList<>(); + + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); + + Map newProp = getProperties(vertex); + T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node, newProp, clazz); + result.add(element); + } + if (result.size() == 0) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + if (log.isDebugEnabled()) { + log.debug("No nodes in graph for criteria : from type = {} and properties = {}", type, props); + } + return Either.left(result); + } catch (Exception e) { + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); + } + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + + } else { + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type = {} and properties = {} error : {}", type, props, graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + public Either, JanusGraphOperationStatus> getAll(NodeTypeEnum type, Class clazz) { + return getByCriteria(type, null, clazz); + } + + /** + * + * @param node + * @param clazz + * @return + */ + public Either updateNode(GraphNode node, Class clazz) { + log.debug("Try to update node for {}", node.getKeyValueId()); + + ImmutablePair keyValueId = node.getKeyValueId(); + Either vertexByProperty = getVertexByPropertyAndLabel(keyValueId.getKey(), keyValueId.getValue(), node.getLabel()); + + if (vertexByProperty.isLeft()) { + try { + Vertex vertex = vertexByProperty.left().value(); + + Map mapProps = node.toGraphMap(); + + for (Map.Entry entry : mapProps.entrySet()) { + if (!entry.getKey().equals(node.getUniqueIdKey())) { + vertex.property(entry.getKey(), entry.getValue()); + } + } + + Either vertexByPropertyAndLabel = getVertexByPropertyAndLabel(keyValueId.getKey(), keyValueId.getValue(), node.getLabel()); + if (vertexByPropertyAndLabel.isRight()) { + return Either.right(vertexByPropertyAndLabel.right().value()); + } else { + Map newProp = getProperties(vertexByPropertyAndLabel.left().value()); + T updateNode = GraphElementFactory.createElement(node.getLabel(), GraphElementTypeEnum.Node, newProp, clazz); + return Either.left(updateNode); + } + } catch (Exception e) { + if (log.isDebugEnabled()) { + log.debug("Failed to update node for {}", node.getKeyValueId(), e); + } + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + } else { + if (log.isDebugEnabled()) { + log.debug("Failed to update node for {} error :{}", node.getKeyValueId(), vertexByProperty.right().value()); + } + return Either.right(vertexByProperty.right().value()); + } + + } + + public JanusGraphOperationStatus updateVertex(GraphNode node, Vertex vertex) { + log.debug("Try to update node for {}", node.getKeyValueId()); + try { + + Map mapProps = node.toGraphMap(); + + for (Map.Entry entry : mapProps.entrySet()) { + if (!entry.getKey().equals(node.getUniqueIdKey())) { + vertex.property(entry.getKey(), entry.getValue()); + } + } + + } catch (Exception e) { + if (log.isDebugEnabled()) { + log.debug("Failed to update node for {}", node.getKeyValueId(), e); + } + return JanusGraphClient.handleJanusGraphException(e); + } + return JanusGraphOperationStatus.OK; + + } + + /** + * + * @param node + * @param clazz + * @return + */ + public Either deleteNode(GraphNode node, Class clazz) { + log.debug("Try to delete node for {}", node.getKeyValueId()); + ImmutablePair keyValueId = node.getKeyValueId(); + return deleteNode(keyValueId.getKey(), keyValueId.getValue(), clazz); + } + + /** + * + * @param keyName + * @param keyValue + * @param clazz + * @return + */ + public Either deleteNode(String keyName, Object keyValue, Class clazz) { + Either vertexByProperty = getVertexByProperty(keyName, keyValue); + + if (vertexByProperty.isLeft()) { + try { + Vertex vertex = vertexByProperty.left().value(); + + Map properties = getProperties(vertex); + if (properties != null) { + String label = (String) properties.get(GraphPropertiesDictionary.LABEL.getProperty()); + + T node = GraphElementFactory.createElement(label, GraphElementTypeEnum.Node, properties, clazz); + if (node != null) { + Either graph = janusGraphClient.getGraph(); + if (graph.isLeft()) { + JanusGraph tGraph = graph.left().value(); + vertex.remove(); + } else { + return Either.right(graph.right().value()); + } + return Either.left(node); + } else { + if (log.isDebugEnabled()) { + log.debug("Failed to delete node for {} = {} Missing label property on node", keyName, keyValue); + } + return Either.right(JanusGraphOperationStatus.MISSING_NODE_LABEL); + } + } else { + if (log.isDebugEnabled()) { + log.debug("Failed to delete node for {} = {} Missing label property on node", keyName, keyValue); + } + return Either.right(JanusGraphOperationStatus.MISSING_NODE_LABEL); + } + } catch (Exception e) { + if (log.isDebugEnabled()) { + log.debug("Failed to delete node for {} = {}", keyName, keyValue, e); + } + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + + } else { + return Either.right(vertexByProperty.right().value()); + } + } + + public Either deleteRelation(GraphRelation relation) { + log.debug("try to delete relation from [{}] to [{}]", relation.getFrom(), relation.getTo()); + RelationEndPoint from = relation.getFrom(); + RelationEndPoint to = relation.getTo(); + ImmutablePair fromKeyId = new ImmutablePair<>(from.getIdName(), from.getIdValue()); + ImmutablePair toKeyId = new ImmutablePair<>(to.getIdName(), to.getIdValue()); + + return deleteEdge(relation.getType(), fromKeyId, toKeyId, from.getLabel().getName(), to.getLabel().getName()); + + } + + public Either isRelationExist(GraphNode from, GraphNode to, GraphEdgeLabels edgeLabel) { + return getEdgeByNodes(from, to, edgeLabel) + .left() + .map(edge -> true) + .right() + .bind(err -> err == JanusGraphOperationStatus.NOT_FOUND ? Either.left(false): Either.right(err)); + } + + public Either deleteRelation(GraphNode from, GraphNode to, GraphEdgeLabels label) { + log.debug("try to delete relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); + return deleteEdge(label.getProperty(), from.getKeyValueId(), to.getKeyValueId(), from.getLabel(), to.getLabel()); + } + + private Either deleteEdge(String type, ImmutablePair fromKeyId, ImmutablePair toKeyId, String fromLabel, String toLabel) { + Either edgeS = getEdgeByVerticies(fromKeyId.getKey(), fromKeyId.getValue(), toKeyId.getKey(), toKeyId.getValue(), type); + if (edgeS.isLeft()) { + try { + Edge edge = edgeS.left().value(); + + Vertex vertexOut = edge.outVertex(); + Vertex vertexIn = edge.inVertex(); + + GraphNode nodeOut = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(vertexOut), GraphNode.class); + GraphNode nodeIn = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(vertexIn), GraphNode.class); + + GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeOut, nodeIn); + + Either graph = janusGraphClient.getGraph(); + + if (graph.isLeft()) { + edge.remove(); + ; + } else { + if (log.isDebugEnabled()) { + log.debug("Failed to delete relation {} from {} to {} error : {}",type,fromKeyId,toKeyId,graph.right().value()); + } + return Either.right(graph.right().value()); + } + return Either.left(newRelation); + } catch (Exception e) { + if (log.isDebugEnabled()) { + log.debug("Failed to delete relation {} from {} to {}", type, fromKeyId, toKeyId, e); + } + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + } else { + if (log.isDebugEnabled()) { + log.debug("Failed to delete relation {} from {} to {} error : {}", type, fromKeyId, toKeyId, edgeS.right().value()); + } + return Either.right(edgeS.right().value()); + } + } + + public void setJanusGraphClient(JanusGraphClient janusGraphClient) { + this.janusGraphClient = janusGraphClient; + } + + public Either deleteIncomingRelation(GraphRelation relation) { + + RelationEndPoint to = relation.getTo(); + ImmutablePair toKeyId = new ImmutablePair<>(to.getIdName(), to.getIdValue()); + + return deleteIncomingEdge(relation.getType(), toKeyId); + + } + + private Either deleteIncomingEdge(String type, ImmutablePair toKeyId) { + + Either graph = janusGraphClient.getGraph(); + + if (graph.isLeft()) { + Either rootVertexResult = getVertexByProperty(toKeyId.getKey(), toKeyId.getValue()); + if (rootVertexResult.isLeft()) { + Vertex rootVertex = rootVertexResult.left().value(); + Iterator edgesIterator = rootVertex.edges(Direction.IN, type); + if (edgesIterator != null) { + + Edge edge = null; + + if (edgesIterator.hasNext()) { + edge = edgesIterator.next(); + if (edgesIterator.hasNext()) { + return Either.right(JanusGraphOperationStatus.MULTIPLE_EDGES_WITH_SAME_LABEL); + } + } else { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + log.debug("Find the tail vertex of the edge of type {} to vertex {}", type, toKeyId); + Vertex vertexOut = edge.outVertex(); + String fromLabel = vertexOut.value(GraphPropertiesDictionary.LABEL.getProperty()); + String toLabel = rootVertex.value(GraphPropertiesDictionary.LABEL.getProperty()); + log.debug("The label of the outgoing vertex is {}", fromLabel); + GraphNode nodeOut = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(vertexOut), GraphNode.class); + + GraphNode nodeIn = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(rootVertex), GraphNode.class); + + GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeOut, nodeIn); + + edge.remove(); + + return Either.left(newRelation); + + } else { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + } else { + return Either.right(graph.right().value()); + } + + } else { + return Either.right(graph.right().value()); + } + + } + + public Either deleteOutgoingRelation(GraphRelation relation) { + + RelationEndPoint from = relation.getFrom(); + ImmutablePair fromKeyId = new ImmutablePair<>(from.getIdName(), from.getIdValue()); + + return deleteOutgoingEdge(relation.getType(), fromKeyId); + + } + + private Either deleteOutgoingEdge(String type, ImmutablePair toKeyId) { + + Either graph = janusGraphClient.getGraph(); + + if (graph.isLeft()) { + Either rootVertexResult = getVertexByProperty(toKeyId.getKey(), toKeyId.getValue()); + if (rootVertexResult.isLeft()) { + Vertex rootVertex = rootVertexResult.left().value(); + Iterator edgesIterator = rootVertex.edges(Direction.OUT, type); + if (edgesIterator != null) { + + Edge edge = null; + + if (edgesIterator.hasNext()) { + edge = edgesIterator.next(); + if (edgesIterator.hasNext()) { + return Either.right(JanusGraphOperationStatus.MULTIPLE_EDGES_WITH_SAME_LABEL); + } + } else { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + log.debug("Find the tail vertex of the edge of type {} to vertex ", type, toKeyId); + Vertex vertexIn = edge.inVertex(); + String toLabel = vertexIn.value(GraphPropertiesDictionary.LABEL.getProperty()); + String fromLabel = rootVertex.value(GraphPropertiesDictionary.LABEL.getProperty()); + log.debug("The label of the tail vertex is {}", toLabel); + GraphNode nodeFrom = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(rootVertex), GraphNode.class); + + GraphNode nodeTo = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(vertexIn), GraphNode.class); + + GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeFrom, nodeTo); + + edge.remove(); + + return Either.left(newRelation); + + } else { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + } else { + return Either.right(graph.right().value()); + } + + } else { + return Either.right(graph.right().value()); + } + } + + /** + * + * @param id + * @return + */ + + public JanusGraphOperationStatus lockElement(String id, NodeTypeEnum type) { + + StringBuffer lockId = new StringBuffer(LOCK_NODE_PREFIX); + lockId.append(type.getName()).append("_").append(id); + return lockNode(lockId.toString()); + } + + public JanusGraphOperationStatus lockElement(GraphNode node) { + + StringBuffer lockId = createLockElementId(node); + + return lockNode(lockId.toString()); + } + + private JanusGraphOperationStatus lockNode(String lockId) { + JanusGraphOperationStatus status = JanusGraphOperationStatus.OK; + + GraphNodeLock lockNode = new GraphNodeLock(lockId); + + Either lockNodeNew = createNode(lockNode, GraphNodeLock.class); + if (lockNodeNew.isLeft()) { + log.debug("before commit, Lock node created for {}", lockId); + return janusGraphClient.commit(); + } else { + Either graph = janusGraphClient.getGraph(); + if (graph.isLeft()) { + JanusGraph tGraph = graph.left().value(); + Either vertex = getVertexByProperty(lockNode.getUniqueIdKey(), lockNode.getUniqueId()); + if (vertex.isLeft()) { + status = relockNode(lockNode, lockNodeNew, tGraph, vertex); + } else { + status = vertex.right().value(); + } + } else { + status = graph.right().value(); + } + } + return status; + } + + private JanusGraphOperationStatus relockNode(GraphNodeLock lockNode, Either lockNodeNew, JanusGraph tGraph, Either vertex) { + JanusGraphOperationStatus status = JanusGraphOperationStatus.OK; + Long time = vertex.left().value().value(GraphPropertiesDictionary.CREATION_DATE.getProperty()); + Long lockTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getJanusGraphLockTimeout(); + if (time + lockTimeout * 1000 < System.currentTimeMillis()) { + log.debug("Found not released lock node with id {}", lockNode.getUniqueId()); + vertex.left().value().remove(); + lockNodeNew = createNode(lockNode, GraphNodeLock.class); + if (lockNodeNew.isLeft()) { + log.debug("Lock node created for {}", lockNode.getUniqueIdKey()); + return janusGraphClient.commit(); + } else { + log.debug("Failed Lock node for {} . Commit transacton for deleted previous vertex .", lockNode.getUniqueIdKey()); + janusGraphClient.commit(); + status = checkLockError(lockNode.getUniqueIdKey(), lockNodeNew); + } + } else { + log.debug("Failed Lock node for {} rollback transacton", lockNode.getUniqueIdKey()); + janusGraphClient.rollback(); + status = checkLockError(lockNode.getUniqueIdKey(), lockNodeNew); + } + return status; + } + + public Either>, JanusGraphOperationStatus> getChildrenNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz, boolean withEdges) { + + List> immutablePairs = new ArrayList<>(); + + Either graphRes = janusGraphClient.getGraph(); + if (graphRes.isRight()) { + log.error(FAILED_TO_RETRIEVE_GRAPH_STATUS_IS, graphRes); + return Either.right(graphRes.right().value()); + } + + JanusGraph janusGraph = graphRes.left().value(); + @SuppressWarnings("unchecked") + Iterable vertices = janusGraph.query().has(key, uniqueId).vertices(); + if (vertices == null || !vertices.iterator().hasNext()) { + return Either.right(JanusGraphOperationStatus.INVALID_ID); + } + + Vertex rootVertex = vertices.iterator().next(); + + Iterator edgesCreatorIterator = rootVertex.edges(Direction.OUT, edgeType.getProperty()); + if (edgesCreatorIterator != null) { + while (edgesCreatorIterator.hasNext()) { + Edge edge = edgesCreatorIterator.next(); + GraphEdge graphEdge = null; + + if (withEdges) { + Map edgeProps = getProperties(edge); + GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label()); + graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps); + } + + Vertex outgoingVertex = edge.inVertex(); + Map properties = getProperties(outgoingVertex); + T data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz); + + ImmutablePair immutablePair = new ImmutablePair<>(clazz.cast(data), graphEdge); + immutablePairs.add(immutablePair); + } + } + + if (immutablePairs.isEmpty()) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + return Either.left(immutablePairs); + + } + + public Either>, JanusGraphOperationStatus> getChildrenVertecies(String key, String uniqueId, GraphEdgeLabels edgeType) { + + List> immutablePairs = new ArrayList<>(); + + Either graphRes = janusGraphClient.getGraph(); + if (graphRes.isRight()) { + log.error(FAILED_TO_RETRIEVE_GRAPH_STATUS_IS, graphRes); + return Either.right(graphRes.right().value()); + } + + JanusGraph janusGraph = graphRes.left().value(); + @SuppressWarnings("unchecked") + Iterable vertices = janusGraph.query().has(key, uniqueId).vertices(); + if (vertices == null || !vertices.iterator().hasNext()) { + return Either.right(JanusGraphOperationStatus.INVALID_ID); + } + + Vertex rootVertex = vertices.iterator().next(); + + Iterator edgesCreatorIterator = rootVertex.edges(Direction.OUT, edgeType.getProperty()); + if (edgesCreatorIterator != null) { + while (edgesCreatorIterator.hasNext()) { + Edge edge = edgesCreatorIterator.next(); + JanusGraphVertex vertex = (JanusGraphVertex) edge.inVertex(); + + ImmutablePair immutablePair = new ImmutablePair<>(vertex, edge); + immutablePairs.add(immutablePair); + } + } + if (immutablePairs.isEmpty()) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + return Either.left(immutablePairs); + + } + + public Either>, JanusGraphOperationStatus> getChildrenNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz) { + return this.getChildrenNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz, true); + } + + private JanusGraphOperationStatus checkLockError(String lockId, Either lockNodeNew) { + JanusGraphOperationStatus status; + JanusGraphOperationStatus error = lockNodeNew.right().value(); + log.debug("Failed to Lock node for {} error = {}", lockId, error); + if (error.equals(JanusGraphOperationStatus.JANUSGRAPH_SCHEMA_VIOLATION) || error.equals( + JanusGraphOperationStatus.ILLEGAL_ARGUMENT)) { + status = JanusGraphOperationStatus.ALREADY_LOCKED; + } else { + status = error; + } + return status; + } + + /** + * + * @param node + * @return + */ + public JanusGraphOperationStatus releaseElement(GraphNode node) { + StringBuffer lockId = createLockElementId(node); + + return unlockNode(lockId); + } + + private JanusGraphOperationStatus unlockNode(StringBuffer lockId) { + GraphNodeLock lockNode = new GraphNodeLock(lockId.toString()); + + Either lockNodeNew = deleteNode(lockNode, GraphNodeLock.class); + if (lockNodeNew.isLeft()) { + log.debug("Lock node released for lock id = {}", lockId); + return janusGraphClient.commit(); + } else { + janusGraphClient.rollback(); + JanusGraphOperationStatus error = lockNodeNew.right().value(); + log.debug("Failed to Release node for lock id {} error = {}", lockId, error); + return error; + } + } + + public JanusGraphOperationStatus releaseElement(String id, NodeTypeEnum type) { + StringBuffer lockId = new StringBuffer(LOCK_NODE_PREFIX); + lockId.append(type.getName()).append("_").append(id); + return unlockNode(lockId); + } + + private StringBuffer createLockElementId(GraphNode node) { + StringBuffer lockId = new StringBuffer(LOCK_NODE_PREFIX); + lockId.append(node.getLabel()).append("_").append(node.getUniqueId()); + return lockId; + } + + public Either, JanusGraphOperationStatus> getChild(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz) { + + Either>, JanusGraphOperationStatus> childrenNodes = getChildrenNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz); + + if (childrenNodes.isRight()) { + return Either.right(childrenNodes.right().value()); + } + + List> value = childrenNodes.left().value(); + + if (value.size() > 1) { + return Either.right(JanusGraphOperationStatus.MULTIPLE_CHILDS_WITH_SAME_EDGE); + } + + return Either.left(value.get(0)); + + } + + public ImmutablePair getChildVertex(JanusGraphVertex vertex, GraphEdgeLabels edgeType) { + + ImmutablePair pair = null; + Iterator edges = vertex.edges(Direction.OUT, edgeType.getProperty()); + if (edges.hasNext()) { + // get only first edge + Edge edge = edges.next(); + pair = new ImmutablePair<>((JanusGraphVertex) edge.inVertex(), edge); + } + return pair; + } + + public Either>, JanusGraphOperationStatus> getParentNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz) { + + List> immutablePairs = new ArrayList<>(); + + T data = null; + GraphEdge graphEdge = null; + + Either graphRes = janusGraphClient.getGraph(); + if (graphRes.isRight()) { + log.error(FAILED_TO_RETRIEVE_GRAPH_STATUS_IS, graphRes); + return Either.right(graphRes.right().value()); + } + + JanusGraph janusGraph = graphRes.left().value(); + @SuppressWarnings("unchecked") + Iterable vertices = janusGraph.query().has(key, uniqueId).vertices(); + if (vertices == null || !vertices.iterator().hasNext()) { + return Either.right(JanusGraphOperationStatus.INVALID_ID); + } + + Vertex rootVertex = vertices.iterator().next(); + + Iterator edgesCreatorIterator = rootVertex.edges(Direction.IN, edgeType.name()); + if (edgesCreatorIterator != null) { + while (edgesCreatorIterator.hasNext()) { + Edge edge = edgesCreatorIterator.next(); + Map edgeProps = getProperties(edge); + GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label()); + graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps); + + Vertex outgoingVertex = edge.outVertex(); + Map properties = getProperties(outgoingVertex); + data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz); + + ImmutablePair immutablePair = new ImmutablePair<>(clazz.cast(data), graphEdge); + immutablePairs.add(immutablePair); + } + } + + if (immutablePairs.isEmpty()) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + return Either.left(immutablePairs); + + } + + public Either, JanusGraphOperationStatus> getParentNode(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz) { + + Either>, JanusGraphOperationStatus> parentNodesRes = this.getParentNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz); + + if (parentNodesRes.isRight()) { + log.debug("failed to get edge key:{} uniqueId:{} edgeType {} nodeTypeEnum: {}, reason:{}", key, uniqueId, edgeType, nodeTypeEnum, parentNodesRes.right().value()); + return Either.right(parentNodesRes.right().value()); + } + + List> value = parentNodesRes.left().value(); + + if (value.size() > 1) { + return Either.right(JanusGraphOperationStatus.MULTIPLE_CHILDS_WITH_SAME_EDGE); + } + + return Either.left(value.get(0)); + } + + public Either, JanusGraphOperationStatus> getChildByEdgeCriteria(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz, Map edgeProperties) { + + Either outgoingEdgeByCriteria = getOutgoingEdgeByCriteria(key, uniqueId, edgeType, edgeProperties); + if (outgoingEdgeByCriteria.isRight()) { + JanusGraphOperationStatus status = outgoingEdgeByCriteria.right().value(); + log.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}" + uniqueId, edgeType, edgeProperties); + return Either.right(status); + } + + Edge edge = outgoingEdgeByCriteria.left().value(); + Map edgeProps = getProperties(edge); + GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label()); + GraphEdge graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps); + + Vertex outgoingVertex = edge.inVertex(); + Map properties = getProperties(outgoingVertex); + T data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz); + + ImmutablePair immutablePair = new ImmutablePair<>(clazz.cast(data), graphEdge); + + return Either.left(immutablePair); + } + + public Either, JanusGraphOperationStatus> getChildByEdgeCriteria(JanusGraphVertex vertex, GraphEdgeLabels edgeType, Map edgeProperties) { + + Either outgoingEdgeByCriteria = getOutgoingEdgeByCriteria(vertex, edgeType, edgeProperties); + if (outgoingEdgeByCriteria.isRight()) { + JanusGraphOperationStatus status = outgoingEdgeByCriteria.right().value(); + log.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}", vertex, edgeType, edgeProperties); + return Either.right(status); + } + Edge edge = outgoingEdgeByCriteria.left().value(); + + JanusGraphVertex outgoingVertex = (JanusGraphVertex) edge.inVertex(); + + ImmutablePair immutablePair = new ImmutablePair<>(outgoingVertex, edge); + + return Either.left(immutablePair); + } + + public Either getOutgoingEdgeByCriteria(String key, String value, GraphEdgeLabels label, Map props) { + + Either vertexFrom = getVertexByProperty(key, value); + if (vertexFrom.isRight()) { + JanusGraphOperationStatus status = vertexFrom.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + return Either.right(JanusGraphOperationStatus.INVALID_ID); + } + return Either.right(status); + } + + return getOutgoingEdgeByCriteria(vertexFrom.left().value(), label, props); + } + + public Either getOutgoingEdgeByCriteria(JanusGraphVertex vertex, GraphEdgeLabels label, Map props) { + + JanusGraphVertexQuery query = vertex.query(); + query = query.direction(Direction.OUT).labels(label.getProperty()); + + if (props != null && !props.isEmpty()) { + for (Map.Entry entry : props.entrySet()) { + query = query.has(entry.getKey(), entry.getValue()); + } + } + Edge matchingEdge = null; + Iterable edges = query.edges(); + if (edges == null) { + log.debug(NO_EDGES_IN_GRAPH_FOR_CRITERIA); + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + Iterator eIter = edges.iterator(); + if (eIter.hasNext()) { + matchingEdge = eIter.next(); + } + + if (matchingEdge == null) { + log.debug(NO_EDGES_IN_GRAPH_FOR_CRITERIA); + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + return Either.left(matchingEdge); + } + + public Either>, JanusGraphOperationStatus> deleteChildrenNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz) { + + List> result = new ArrayList<>(); + + Either>, JanusGraphOperationStatus> childrenNodesRes = getChildrenNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz); + + if (childrenNodesRes.isRight()) { + JanusGraphOperationStatus status = childrenNodesRes.right().value(); + return Either.right(status); + } + + List> list = childrenNodesRes.left().value(); + for (ImmutablePair pair : list) { + T node = pair.getKey(); + Either deleteNodeRes = this.deleteNode(node, clazz); + if (deleteNodeRes.isRight()) { + JanusGraphOperationStatus status = deleteNodeRes.right().value(); + log.error("Failed to delete node {} . status is {}", node, status); + return Either.right(status); + } + ImmutablePair deletedPair = new ImmutablePair<>(node, pair.getValue()); + result.add(deletedPair); + } + + return Either.left(result); + + } + + public void setProperties(Element element, Map properties) { + + if (properties != null && !properties.isEmpty()) { + + Object[] propertyKeyValues = new Object[properties.size() * 2]; + int i = 0; + for (Entry entry : properties.entrySet()) { + propertyKeyValues[i++] = entry.getKey(); + propertyKeyValues[i++] = entry.getValue(); + } + + ElementHelper.attachProperties(element, propertyKeyValues); + + } + + } + + public Map getProperties(Element element) { + + Map result = new HashMap<>(); + + if (element != null && element.keys() != null && element.keys().size() > 0) { + Map propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()])); + + for (Entry entry : propertyMap.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue().value(); + + result.put(key, value); + } + } + return result; + } + + public Object getProperty(JanusGraphVertex vertex, String key) { + PropertyKey propertyKey = janusGraphClient.getGraph().left().value().getPropertyKey(key); + return vertex.valueOrNull(propertyKey); + } + + public Object getProperty(Edge edge, String key) { + Object value = null; + Property property = edge.property(key); + if (property != null) { + return property.orElse(null); + } + return value; + } + + public Either>, JanusGraphOperationStatus> getChildrenByEdgeCriteria(Vertex vertex, String vertexUniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz, + Map edgeProperties) { + + List> result = new ArrayList<>(); + + Either, JanusGraphOperationStatus> outgoingEdgeByCriteria = getOutgoingEdgesByCriteria(vertex, edgeType, edgeProperties); + if (outgoingEdgeByCriteria.isRight()) { + JanusGraphOperationStatus status = outgoingEdgeByCriteria.right().value(); + log.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}", vertexUniqueId, edgeType, edgeProperties); + return Either.right(status); + } + + List edges = outgoingEdgeByCriteria.left().value(); + if (edges != null) { + for (Edge edge : edges) { + Map edgeProps = getProperties(edge); + GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label()); + GraphEdge graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps); + + Vertex outgoingVertex = edge.inVertex(); + Map properties = getProperties(outgoingVertex); + T data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz); + + ImmutablePair immutablePair = new ImmutablePair<>(clazz.cast(data), graphEdge); + result.add(immutablePair); + } + } + + return Either.left(result); + } + + public Either, JanusGraphOperationStatus> getOutgoingEdgesByCriteria(Vertex vertexFrom, GraphEdgeLabels label, Map props) { + + List edgesResult = new ArrayList<>(); + + JanusGraphVertex janusGraphVertex = (JanusGraphVertex) vertexFrom; + JanusGraphVertexQuery query = janusGraphVertex.query(); + + query = query.direction(Direction.OUT).labels(label.getProperty()); + + if (props != null && !props.isEmpty()) { + for (Map.Entry entry : props.entrySet()) { + query = query.has(entry.getKey(), entry.getValue()); + } + } + + Iterable edges = query.edges(); + Iterator eIter = edges.iterator(); + if (edges == null || !eIter.hasNext()) { + log.debug("No edges found in graph for criteria (label = {} properties={})", label.getProperty(), props); + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + while (eIter.hasNext()) { + Edge edge = eIter.next(); + edgesResult.add(edge); + } + + if (edgesResult.isEmpty()) { + log.debug("No edges found in graph for criteria (label = {} properties={})", label.getProperty(), props); + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + return Either.left(edgesResult); + + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphOperationStatus.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphOperationStatus.java new file mode 100644 index 0000000000..a4ebcf79e0 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphOperationStatus.java @@ -0,0 +1,26 @@ +/*- + * ============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.dao.janusgraph; + +public enum JanusGraphOperationStatus { + OK, NOT_CONNECTED, NOT_CREATED, INDEX_CANNOT_BE_CHANGED, NOT_FOUND, MISSING_UNIQUE_ID, MISSING_NODE_LABEL, MULTIPLE_EDGES_WITH_SAME_LABEL, CANNOT_DELETE_NON_LEAF_NODE, MULTIPLE_NODES_WITH_SAME_ID, GRAPH_IS_NOT_AVAILABLE, JANUSGRAPH_CONFIGURATION, JANUSGRAPH_SCHEMA_VIOLATION, INVALID_ELEMENT, INVALID_QUERY, INVALID_ID, RESOURCE_UNAVAILABLE, ILLEGAL_ARGUMENT, ALREADY_LOCKED, ALREADY_EXIST, MULTIPLE_CHILDS_WITH_SAME_EDGE, GENERAL_ERROR, MATCH_NOT_FOUND, INVALID_TYPE, PROPERTY_NAME_ALREADY_EXISTS, INVALID_PROPERTY, + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphUtils.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphUtils.java new file mode 100644 index 0000000000..fd9856b373 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphUtils.java @@ -0,0 +1,27 @@ +package org.openecomp.sdc.be.dao.janusgraph; + +import org.janusgraph.graphdb.query.JanusGraphPredicate; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import static org.janusgraph.core.attribute.Contain.NOT_IN; +import static java.util.Collections.emptyMap; +import static org.apache.commons.collections.CollectionUtils.isEmpty; + +public class JanusGraphUtils { + + private JanusGraphUtils() { + } + + public static Map> buildNotInPredicate(String propKey, Collection notInCollection) { + if (isEmpty(notInCollection)) { + return emptyMap(); + } + Map> predicateCriteria = new HashMap<>(); + predicateCriteria.put(propKey, new HashMap.SimpleEntry<>(NOT_IN, notInCollection)); + return predicateCriteria; + } +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/QueryType.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/QueryType.java new file mode 100644 index 0000000000..fc2f2d0643 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/QueryType.java @@ -0,0 +1,28 @@ +/*- + * ============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.dao.janusgraph; + +/** + * Created by mlando on 9/21/2016. + */ +public enum QueryType { + HAS, HAS_NOT +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/transactions/SimpleJanusGraphTransactionManager.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/transactions/SimpleJanusGraphTransactionManager.java new file mode 100644 index 0000000000..8c67254da8 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/janusgraph/transactions/SimpleJanusGraphTransactionManager.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.be.dao.janusgraph.transactions; + +import org.janusgraph.core.JanusGraphException; +import org.janusgraph.core.JanusGraph; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.stereotype.Component; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.TransactionSystemException; +import org.springframework.transaction.support.SimpleTransactionStatus; + +import javax.annotation.PostConstruct; + +/** + * Simple transaction manager for the janusgraph database. + * This manager does not deal with transactions propagation and relies on the fact that transactions are automatically created with the first operation on the graph + */ +@Component +public class SimpleJanusGraphTransactionManager implements PlatformTransactionManager { + + private static final Logger log = Logger.getLogger(SimpleJanusGraphTransactionManager.class.getName()); + private final JanusGraphClient janusGraphClient; + private JanusGraph janusGraph; + + public SimpleJanusGraphTransactionManager(JanusGraphClient janusGraphClient) { + this.janusGraphClient = janusGraphClient; + } + + @PostConstruct + public void onInit() { + janusGraph = janusGraphClient.getGraph().left().on(this::onFailingToStartJanusGraph); + } + + @Override + public TransactionStatus getTransaction(TransactionDefinition transactionDefinition) { + log.debug("#getTransaction - returning simple transaction status"); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus transactionStatus) { + log.debug("#commit - committing transaction"); + try { + janusGraph.tx().commit(); + } catch (JanusGraphException e) { + log.debug("#commit - failed to commit transaction", e); + throw new TransactionSystemException("failed to commit transaction", e); + } + } + + @Override + public void rollback(TransactionStatus transactionStatus) { + log.debug("#rollback - committing transaction"); + try { + janusGraph.tx().rollback(); + } catch (JanusGraphException e) { + log.debug("#rollback - failed to rollback transaction", e); + throw new TransactionSystemException("failed to rollback transaction", e); + } + } + + private JanusGraph onFailingToStartJanusGraph(JanusGraphOperationStatus err) { + log.debug("#onFailingToStartJanusGraph - could not open janusgraph client"); + throw new IllegalStateException("janusgraph could not be initialized: " + err); + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertex.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertex.java index 74852944d0..2db22a72b0 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertex.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertex.java @@ -20,7 +20,7 @@ package org.openecomp.sdc.be.dao.jsongraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphVertex; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; @@ -37,7 +37,7 @@ import java.util.Map.Entry; public class GraphVertex { private String uniqueId; - private TitanVertex vertex; + private JanusGraphVertex vertex; private VertexTypeEnum label; private Map json; @@ -70,11 +70,11 @@ public class GraphVertex { this.json = json; } - public TitanVertex getVertex() { + public JanusGraphVertex getVertex() { return vertex; } - public void setVertex(TitanVertex vertex) { + public void setVertex(JanusGraphVertex vertex) { this.vertex = vertex; } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/HealingJanusGraphDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/HealingJanusGraphDao.java new file mode 100644 index 0000000000..c2ef659c65 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/HealingJanusGraphDao.java @@ -0,0 +1,64 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * 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. + */ + +package org.openecomp.sdc.be.dao.jsongraph; + +import fj.data.Either; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import org.openecomp.sdc.be.dao.impl.HealingPipelineDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component("janusgraph-dao") +public class HealingJanusGraphDao extends JanusGraphDao { + + + @Autowired + private HealingPipelineDao healingPipelineDao; + + + public HealingJanusGraphDao(JanusGraphClient janusGraphClient) { + super(janusGraphClient); + } + + @Override + public Either, JanusGraphOperationStatus> getChildrenVertecies(GraphVertex parentVertex, + EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + Either, JanusGraphOperationStatus> childrenVertecies = + super.getChildrenVertecies(parentVertex, edgeLabel, parseFlag); + return Either.iif(childrenVertecies.isRight(), () -> childrenVertecies.right().value(), + () -> childrenVertecies.left().value().stream() + .map(graphVertex -> transformVertex(graphVertex, edgeLabel)) + .collect(Collectors.toList())); + } + + private GraphVertex transformVertex(GraphVertex graphVertex, EdgeLabelEnum edgeLabelEnum) { + Optional optional = healingPipelineDao.performGraphReadHealing(graphVertex, edgeLabelEnum); + return optional.orElse(graphVertex); + } + + + public void setHealingPipelineDao(HealingPipelineDao healingPipelineDao) { + this.healingPipelineDao = healingPipelineDao; + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/HealingTitanDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/HealingTitanDao.java deleted file mode 100644 index fb6b9d8fa3..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/HealingTitanDao.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright © 2016-2018 European Support Limited - * - * 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. - */ - -package org.openecomp.sdc.be.dao.jsongraph; - -import fj.data.Either; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; -import org.openecomp.sdc.be.dao.impl.HealingPipelineDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.titan.TitanGraphClient; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component("titan-dao") -public class HealingTitanDao extends TitanDao { - - - @Autowired - private HealingPipelineDao healingPipelineDao; - - - public HealingTitanDao(TitanGraphClient titanClient) { - super(titanClient); - } - - @Override - public Either, TitanOperationStatus> getChildrenVertecies(GraphVertex parentVertex, - EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - Either, TitanOperationStatus> childrenVertecies = - super.getChildrenVertecies(parentVertex, edgeLabel, parseFlag); - return Either.iif(childrenVertecies.isRight(), () -> childrenVertecies.right().value(), - () -> childrenVertecies.left().value().stream() - .map(graphVertex -> transformVertex(graphVertex, edgeLabel)) - .collect(Collectors.toList())); - } - - private GraphVertex transformVertex(GraphVertex graphVertex, EdgeLabelEnum edgeLabelEnum) { - Optional optional = healingPipelineDao.performGraphReadHealing(graphVertex, edgeLabelEnum); - return optional.orElse(graphVertex); - } - - - public void setHealingPipelineDao(HealingPipelineDao healingPipelineDao) { - this.healingPipelineDao = healingPipelineDao; - } - -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/JanusGraphDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/JanusGraphDao.java new file mode 100644 index 0000000000..5917b14fd3 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/JanusGraphDao.java @@ -0,0 +1,1077 @@ +/*- + * ============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.dao.jsongraph; + +import org.janusgraph.core.*; +import fj.data.Either; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.tinkerpop.gremlin.structure.*; +import org.apache.tinkerpop.gremlin.structure.util.ElementHelper; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.beans.factory.annotation.Qualifier; + +import java.io.IOException; +import java.util.*; +import java.util.Map.Entry; + +import static org.apache.commons.collections.CollectionUtils.isEmpty; + + +public class JanusGraphDao { + JanusGraphClient janusGraphClient; + + private static Logger logger = Logger.getLogger(JanusGraphDao.class.getName()); + + public JanusGraphDao(@Qualifier("janusgraph-client") JanusGraphClient janusGraphClient) { + this.janusGraphClient = janusGraphClient; + logger.info("** JanusGraphDao created"); + } + + public JanusGraphOperationStatus commit() { + logger.debug("#commit - The operation succeeded. Doing commit..."); + return janusGraphClient.commit(); + } + + public JanusGraphOperationStatus rollback() { + logger.debug("#rollback - The operation failed. Doing rollback..."); + return janusGraphClient.rollback(); + } + + public Either getGraph() { + return janusGraphClient.getGraph(); + } + + /** + * + * @param graphVertex + * @return + */ + public Either createVertex(GraphVertex graphVertex) { + logger.trace("try to create vertex for ID [{}]", graphVertex.getUniqueId()); + Either graph = janusGraphClient.getGraph(); + if (graph.isLeft()) { + try { + JanusGraph tGraph = graph.left().value(); + + JanusGraphVertex vertex = tGraph.addVertex(); + + setVertexProperties(vertex, graphVertex); + + graphVertex.setVertex(vertex); + + return Either.left(graphVertex); + + } catch (Exception e) { + logger.debug("Failed to create Node for ID [{}]", graphVertex.getUniqueId(), e); + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + } else { + logger.debug("Failed to create vertex for ID [{}] {}", graphVertex.getUniqueId(), graph.right().value()); + return Either.right(graph.right().value()); + } + } + + /** + * + * @param name + * @param value + * @param label + * @return + */ + public Either getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, VertexTypeEnum label) { + return getVertexByPropertyAndLabel(name, value, label, JsonParseFlagEnum.ParseAll); + } + + public Either getVertexByLabel(VertexTypeEnum label) { + return janusGraphClient.getGraph().left().map(graph -> graph.query().has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices()).left().bind(janusGraphVertices -> getFirstFoundVertex(JsonParseFlagEnum.NoParse, janusGraphVertices)); + } + + private Either getFirstFoundVertex(JsonParseFlagEnum parseFlag, Iterable vertices) { + Iterator iterator = vertices.iterator(); + if (iterator.hasNext()) { + JanusGraphVertex vertex = iterator.next(); + GraphVertex graphVertex = createAndFill(vertex, parseFlag); + + return Either.left(graphVertex); + } + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + /** + * + * @param name + * @param value + * @param label + * @param parseFlag + * @return + */ + public Either getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, VertexTypeEnum label, JsonParseFlagEnum parseFlag) { + + Either graph = janusGraphClient.getGraph(); + if (graph.isLeft()) { + try { + JanusGraph tGraph = graph.left().value(); + + @SuppressWarnings("unchecked") + Iterable vertecies = tGraph.query().has(name.getProperty(), value).has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices(); + + java.util.Iterator iterator = vertecies.iterator(); + if (iterator.hasNext()) { + JanusGraphVertex vertex = iterator.next(); + GraphVertex graphVertex = createAndFill(vertex, parseFlag); + + return Either.left(graphVertex); + } + if (logger.isDebugEnabled()) { + logger.debug("No vertex in graph for key = {} and value = {} label = {}" + name, value, label); + } + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed to get vertex in graph for key ={} and value = {} label = {}", name, value, label); + } + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + + } else { + if (logger.isDebugEnabled()) { + logger.debug("No vertex in graph for key ={} and value = {} label = {} error :{}", name, value, label, graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + /** + * + * @param id + * @return + */ + public Either getVertexById(String id) { + return getVertexById(id, JsonParseFlagEnum.ParseAll); + } + + /** + * + * @param id + * @param parseFlag + * @return + */ + public Either getVertexById(String id, JsonParseFlagEnum parseFlag) { + + Either graph = janusGraphClient.getGraph(); + if (id == null) { + if (logger.isDebugEnabled()) { + logger.debug("No vertex in graph for id = {} ", id); + } + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + if (graph.isLeft()) { + try { + JanusGraph tGraph = graph.left().value(); + + @SuppressWarnings("unchecked") + Iterable vertecies = tGraph.query().has(GraphPropertyEnum.UNIQUE_ID.getProperty(), id).vertices(); + + java.util.Iterator iterator = vertecies.iterator(); + if (iterator.hasNext()) { + JanusGraphVertex vertex = iterator.next(); + GraphVertex graphVertex = createAndFill(vertex, parseFlag); + return Either.left(graphVertex); + } else { + if (logger.isDebugEnabled()) { + logger.debug("No vertex in graph for id = {}", id); + } + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed to get vertex in graph for id {} ", id); + } + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + } else { + if (logger.isDebugEnabled()) { + logger.debug("No vertex in graph for id {} error : {}", id, graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + private void setVertexProperties(JanusGraphVertex vertex, GraphVertex graphVertex) throws IOException { + + if (graphVertex.getMetadataProperties() != null) { + for (Map.Entry entry : graphVertex.getMetadataProperties().entrySet()) { + if (entry.getValue() != null) { + vertex.property(entry.getKey().getProperty(), entry.getValue()); + } + } + } + vertex.property(GraphPropertyEnum.LABEL.getProperty(), graphVertex.getLabel().getName()); + + Map json = graphVertex.getJson(); + if (json != null) { + String jsonStr = JsonParserUtils.toJson(json); + vertex.property(GraphPropertyEnum.JSON.getProperty(), jsonStr); + + } + Map jsonMetadata = graphVertex.getMetadataJson(); + if (jsonMetadata != null) { + String jsonMetadataStr = JsonParserUtils.toJson(jsonMetadata); + vertex.property(GraphPropertyEnum.METADATA.getProperty(), jsonMetadataStr); + } + } + + public void setVertexProperties(Vertex vertex, Map properties) { + for (Map.Entry entry : properties.entrySet()) { + if (entry.getValue() != null) { + vertex.property(entry.getKey(), entry.getValue()); + } + } + } + + private GraphVertex createAndFill(JanusGraphVertex vertex, JsonParseFlagEnum parseFlag) { + GraphVertex graphVertex = new GraphVertex(); + graphVertex.setVertex(vertex); + parseVertexProperties(graphVertex, parseFlag); + return graphVertex; + } + + public void parseVertexProperties(GraphVertex graphVertex, JsonParseFlagEnum parseFlag) { + JanusGraphVertex vertex = graphVertex.getVertex(); + Map properties = getVertexProperties(vertex); + VertexTypeEnum label = VertexTypeEnum.getByName((String) (properties.get(GraphPropertyEnum.LABEL))); + for (Map.Entry entry : properties.entrySet()) { + GraphPropertyEnum key = entry.getKey(); + switch (key) { + case UNIQUE_ID: + graphVertex.setUniqueId((String) entry.getValue()); + break; + case LABEL: + graphVertex.setLabel(VertexTypeEnum.getByName((String) entry.getValue())); + break; + case COMPONENT_TYPE: + String type = (String) entry.getValue(); + if (type != null) { + graphVertex.setType(ComponentTypeEnum.valueOf(type)); + } + break; + case JSON: + if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseJson) { + String json = (String) entry.getValue(); + Map jsonObj = JsonParserUtils.toMap(json, label.getClassOfJson()); + graphVertex.setJson(jsonObj); + } + break; + case METADATA: + if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseMetadata) { + String json = (String) entry.getValue(); + Map metadatObj = JsonParserUtils.toMap(json); + graphVertex.setMetadataJson(metadatObj); + } + break; + default: + graphVertex.addMetadataProperty(key, entry.getValue()); + break; + } + } + } + + public JanusGraphOperationStatus createEdge(GraphVertex from, GraphVertex to, EdgeLabelEnum label, Map properties) { + return createEdge(from.getVertex(), to.getVertex(), label, properties); + } + + public JanusGraphOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Map properties) { + if (logger.isTraceEnabled()) { + logger.trace("Try to connect {} with {} label {} properties {}", + from == null ? "NULL" : from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), + to == null ? "NULL" : to.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), label, properties); + } + if (from == null || to == null) { + logger.trace("No JanusGraph vertex for id from {} or id to {}", + from == null ? "NULL" : from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), + to == null ? "NULL" : to.property(GraphPropertyEnum.UNIQUE_ID.getProperty())); + return JanusGraphOperationStatus.NOT_FOUND; + } + Edge edge = from.addEdge(label.name(), to); + JanusGraphOperationStatus status; + try { + setEdgeProperties(edge, properties); + status = JanusGraphOperationStatus.OK; + } catch (IOException e) { + logger.debug("Failed to set properties on edge properties [{}]", properties, e); + status = JanusGraphOperationStatus.GENERAL_ERROR; + } + return status; + } + + public Map getVertexProperties(Element element) { + + Map result = new HashMap<>(); + + if (element != null && element.keys() != null && element.keys().size() > 0) { + Map propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()])); + + for (Entry entry : propertyMap.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue().value(); + + GraphPropertyEnum valueOf = GraphPropertyEnum.getByProperty(key); + if (valueOf != null) { + result.put(valueOf, value); + } + } + } + return result; + } + + public Map getEdgeProperties(Element element) { + + Map result = new HashMap<>(); + + if (element != null && element.keys() != null && element.keys().size() > 0) { + Map propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()])); + + for (Entry entry : propertyMap.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue().value(); + + EdgePropertyEnum valueOf = EdgePropertyEnum.getByProperty(key); + if (valueOf != null) { + if (valueOf == EdgePropertyEnum.INSTANCES) { + List list = JsonParserUtils.toList((String) value, String.class); + result.put(valueOf, list); + } else { + result.put(valueOf, value); + } + } + } + } + return result; + } + + public void setEdgeProperties(Element element, Map properties) throws IOException { + + if (properties != null && !properties.isEmpty()) { + + Object[] propertyKeyValues = new Object[properties.size() * 2]; + int i = 0; + for (Entry entry : properties.entrySet()) { + propertyKeyValues[i++] = entry.getKey().getProperty(); + Object value = entry.getValue(); + if (entry.getKey() == EdgePropertyEnum.INSTANCES) { + String jsonStr = JsonParserUtils.toJson(value); + propertyKeyValues[i++] = jsonStr; + } else { + propertyKeyValues[i++] = entry.getValue(); + } + } + ElementHelper.attachProperties(element, propertyKeyValues); + } + } + + public Either, JanusGraphOperationStatus> getByCriteria(VertexTypeEnum type, Map props) { + return getByCriteria(type, props, JsonParseFlagEnum.ParseAll); + } + + public Either, JanusGraphOperationStatus> getByCriteria(VertexTypeEnum type, Map props, JsonParseFlagEnum parseFlag) { + Either graph = janusGraphClient.getGraph(); + if (graph.isLeft()) { + try { + JanusGraph tGraph = graph.left().value(); + + JanusGraphQuery query = tGraph.query(); + if (type != null) { + query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName()); + } + + if (props != null && !props.isEmpty()) { + for (Map.Entry entry : props.entrySet()) { + query = query.has(entry.getKey().getProperty(), entry.getValue()); + } + } + Iterable vertices = query.vertices(); + if (vertices == null) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + Iterator iterator = vertices.iterator(); + List result = new ArrayList<>(); + + while (iterator.hasNext()) { + JanusGraphVertex vertex = iterator.next(); + + Map newProp = getVertexProperties(vertex); + GraphVertex graphVertex = createAndFill(vertex, parseFlag); + + result.add(graphVertex); + } + if (logger.isDebugEnabled()) { + logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size()); + } + if (result.size() == 0) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + return Either.left(result); + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); + } + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + + } else { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + public Either, JanusGraphOperationStatus> getByCriteria(VertexTypeEnum type, Map props, Map hasNotProps, JsonParseFlagEnum parseFlag) { + Either graph = janusGraphClient.getGraph(); + if (graph.isLeft()) { + try { + JanusGraph tGraph = graph.left().value(); + + JanusGraphQuery query = tGraph.query(); + if (type != null) { + query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName()); + } + + if (props != null && !props.isEmpty()) { + for (Map.Entry entry : props.entrySet()) { + query = query.has(entry.getKey().getProperty(), entry.getValue()); + } + } + if (hasNotProps != null && !hasNotProps.isEmpty()) { + for (Map.Entry entry : hasNotProps.entrySet()) { + if (entry.getValue() instanceof List) { + buildMultipleNegateQueryFromList(entry, query); + } else { + query = query.hasNot(entry.getKey().getProperty(), entry.getValue()); + } + } + } + Iterable vertices = query.vertices(); + if (vertices == null) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + Iterator iterator = vertices.iterator(); + List result = new ArrayList<>(); + + while (iterator.hasNext()) { + JanusGraphVertex vertex = iterator.next(); + + Map newProp = getVertexProperties(vertex); + GraphVertex graphVertex = createAndFill(vertex, parseFlag); + + result.add(graphVertex); + } + if (logger.isDebugEnabled()) { + logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size()); + } + if (result.size() == 0) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + + return Either.left(result); + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); + } + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + + } else { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + public Either, JanusGraphOperationStatus> getCatalogOrArchiveVerticies(boolean isCatalog) { + Either graph = janusGraphClient.getGraph(); + if (graph.isLeft()) { + try { + JanusGraph tGraph = graph.left().value(); + + String name = isCatalog ? VertexTypeEnum.CATALOG_ROOT.getName() : VertexTypeEnum.ARCHIVE_ROOT.getName(); + Iterable vCatalogIter = tGraph.query().has(GraphPropertyEnum.LABEL.getProperty(), name).vertices(); + if (vCatalogIter == null) { + logger.debug("Failed to fetch catalog vertex"); + return Either.right(JanusGraphOperationStatus.GENERAL_ERROR); + } + JanusGraphVertex catalogV = vCatalogIter.iterator().next(); + if (catalogV == null) { + logger.debug("Failed to fetch catalog vertex"); + return Either.right(JanusGraphOperationStatus.GENERAL_ERROR); + } + String edgeLabel = isCatalog ? EdgeLabelEnum.CATALOG_ELEMENT.name() : EdgeLabelEnum.ARCHIVE_ELEMENT.name(); + Iterator vertices = catalogV.vertices(Direction.OUT, edgeLabel); + + return Either.left(vertices); + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria: ", e); + } + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + + } else { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria : ", graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + private void buildMultipleNegateQueryFromList(Map.Entry entry, JanusGraphQuery query) { + List negateList = (List) entry.getValue(); + for (Object listItem : negateList) { + query.hasNot(entry.getKey().getProperty(), listItem); + } + } + + /** + * + * @param parentVertex + * @param edgeLabel + * @param parseFlag + * @return + */ + public Either getChildVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + Either, JanusGraphOperationStatus> childrenVertecies = getChildrenVertecies(parentVertex, edgeLabel, parseFlag); + if (childrenVertecies.isRight()) { + return Either.right(childrenVertecies.right().value()); + } + return Either.left(childrenVertecies.left().value().get(0)); + } + + /** + * + * @param parentVertex + * @param edgeLabel + * @param parseFlag + * @return + */ + public Either getChildVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + Either, JanusGraphOperationStatus> childrenVertecies = getChildrenVertecies(parentVertex, edgeLabel, parseFlag); + if (childrenVertecies.isRight()) { + return Either.right(childrenVertecies.right().value()); + } + return Either.left(childrenVertecies.left().value().get(0)); + } + + public Either getParentVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + Either, JanusGraphOperationStatus> childrenVertecies = getParentVertecies(parentVertex, edgeLabel, parseFlag); + if (childrenVertecies.isRight()) { + return Either.right(childrenVertecies.right().value()); + } + if (isEmpty(childrenVertecies.left().value())){ + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + return Either.left(childrenVertecies.left().value().get(0)); + } + + public Either getParentVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + Either, JanusGraphOperationStatus> childrenVertecies = getParentVertecies(parentVertex, edgeLabel, parseFlag); + if (childrenVertecies.isRight() ) { + return Either.right(childrenVertecies.right().value()); + } + if (isEmpty(childrenVertecies.left().value())){ + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + return Either.left(childrenVertecies.left().value().get(0)); + } + + /** + * + * @param parentVertex + * @param edgeLabel + * @param parseFlag + * @return + */ + public Either, JanusGraphOperationStatus> getChildrenVertecies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.OUT); + } + + public Either, JanusGraphOperationStatus> getParentVertecies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.IN); + } + + public Either, JanusGraphOperationStatus> getParentVertecies(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.IN); + } + + private Either, JanusGraphOperationStatus> getAdjacentVerticies(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag, Direction direction) { + List list = new ArrayList<>(); + try { + Either graphRes = janusGraphClient.getGraph(); + if (graphRes.isRight()) { + logger.error("Failed to retrieve graph. status is {}", graphRes); + return Either.right(graphRes.right().value()); + } + Iterator edgesCreatorIterator = parentVertex.edges(direction, edgeLabel.name()); + if (edgesCreatorIterator != null) { + while (edgesCreatorIterator.hasNext()) { + Edge edge = edgesCreatorIterator.next(); + JanusGraphVertex vertex; + if (direction == Direction.IN) { + vertex = (JanusGraphVertex) edge.outVertex(); + } else { + vertex = (JanusGraphVertex) edge.inVertex(); + } + // GraphVertex graphVertex = createAndFill(vertex, parseFlag); + + list.add(vertex); + } + } + if (list.isEmpty()) { + return Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + } catch (Exception e) { + logger.error("Failed to perform graph operation ", e); + Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + + return Either.left(list); + } + + /** + * + * @param parentVertex + * @param edgeLabel + * @param parseFlag + * @return + */ + public Either, JanusGraphOperationStatus> getChildrenVertecies(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.OUT); + } + + private Either, JanusGraphOperationStatus> getAdjacentVerticies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag, Direction direction) { + List list = new ArrayList<>(); + + Either, JanusGraphOperationStatus> adjacentVerticies = getAdjacentVerticies(parentVertex.getVertex(), edgeLabel, parseFlag, direction); + if (adjacentVerticies.isRight()) { + return Either.right(adjacentVerticies.right().value()); + } + adjacentVerticies.left().value().stream().forEach(vertex -> { + list.add(createAndFill((JanusGraphVertex) vertex, parseFlag)); + }); + + return Either.left(list); + } + + /** + * Searches Edge by received label and criteria + * + * @param vertex + * @param label + * @param properties + * @return found edge or JanusGraphOperationStatus + */ + public Either getBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, Map properties) { + + Either result = null; + Edge matchingEdge = null; + String notFoundMsg = "No edges in graph for criteria"; + try { + JanusGraphVertexQuery query = vertex.getVertex().query().labels(label.name()); + + if (properties != null && !properties.isEmpty()) { + for (Map.Entry entry : properties.entrySet()) { + query = query.has(entry.getKey().getProperty(), entry.getValue()); + } + } + + Iterable edges = query.edges(); + if (edges == null) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg); + result = Either.right(JanusGraphOperationStatus.NOT_FOUND); + } else { + Iterator eIter = edges.iterator(); + if (eIter.hasNext()) { + matchingEdge = eIter.next(); + } else { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg); + result = Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + } + if (result == null) { + result = Either.left(matchingEdge); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during getting edge by criteria for component with id {}. {}", vertex.getUniqueId(), e); + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + return result; + } + + public Either getEdgeByChildrenVertexProperties(GraphVertex vertex, EdgeLabelEnum label, Map properties) { + Either result = null; + Edge matchingEdge = null; + String notFoundMsg = "No edges in graph for criteria"; + try { + + Iterator edges = vertex.getVertex().edges(Direction.OUT, label.name()); + while (edges.hasNext()) { + matchingEdge = edges.next(); + Vertex childV = matchingEdge.inVertex(); + Map vertexProperties = getVertexProperties(childV); + Optional> findNotMatch = properties.entrySet().stream().filter(e -> vertexProperties.get(e.getKey()) == null || !vertexProperties.get(e.getKey()).equals(e.getValue())).findFirst(); + if (!findNotMatch.isPresent()) { + result = Either.left(matchingEdge); + } + } + if (result == null) { + //no match + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg); + result = Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during getting edge by criteria for component with id {}. {}", vertex.getUniqueId(), e); + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + return result; + } + + /** + * Deletes Edge by received label and criteria + * + * @param vertex + * @param label + * @param properties + * @return + */ + public Either deleteBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, Map properties) { + Either result = null; + try { + result = getBelongingEdgeByCriteria(vertex, label, properties); + if (result.isLeft()) { + Edge edge = result.left().value(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to delete an edge with the label {} belonging to the vertex {} ", label.name(), vertex.getUniqueId()); + edge.remove(); + result = Either.left(edge); + } else { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find an edge with the label {} belonging to the vertex {} ", label.name(), vertex.getUniqueId()); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge by criteria for the component with id {}. {}", vertex == null ? "NULL" : vertex.getUniqueId(), e); + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + return result; + } + + @SuppressWarnings("unchecked") + /** + * Deletes an edge between vertices fromVertex and toVertex according to received label + * + * @param fromVertex + * @param toVertex + * @param label + * @return + */ + + public Either deleteEdge(GraphVertex fromVertex, GraphVertex toVertex, EdgeLabelEnum label) { + return deleteEdge(fromVertex.getVertex(), toVertex.getVertex(), label, fromVertex.getUniqueId(), toVertex.getUniqueId(), false); + } + + public Either deleteAllEdges(GraphVertex fromVertex, GraphVertex toVertex, EdgeLabelEnum label) { + return deleteEdge(fromVertex.getVertex(), toVertex.getVertex(), label, fromVertex.getUniqueId(), toVertex.getUniqueId(), true); + } + + public Either deleteEdge(JanusGraphVertex fromVertex, JanusGraphVertex toVertex, EdgeLabelEnum label, String uniqueIdFrom, String uniqueIdTo, boolean deleteAll) { + Either result = null; + try { + Iterable edges = fromVertex.query().labels(label.name()).edges(); + Iterator eIter = edges.iterator(); + while (eIter.hasNext()) { + Edge edge = eIter.next(); + String currVertexUniqueId = edge.inVertex().value(GraphPropertyEnum.UNIQUE_ID.getProperty()); + if (currVertexUniqueId != null && currVertexUniqueId.equals(uniqueIdTo)) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to delete an edge with the label {} between vertices {} and {}. ", label.name(), uniqueIdFrom, uniqueIdTo); + edge.remove(); + result = Either.left(edge); + if (!deleteAll) { + break; + } + } + } + if (result == null) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete an edge with the label {} between vertices {} and {}. ", label.name(), uniqueIdFrom, uniqueIdTo); + result = Either.right(JanusGraphOperationStatus.NOT_FOUND); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge with the label {} between vertices {} and {}. {}", label.name(), uniqueIdFrom, uniqueIdTo, e); + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + return result; + } + + public JanusGraphOperationStatus deleteEdgeByDirection(GraphVertex fromVertex, Direction direction, EdgeLabelEnum label) { + try { + Iterator edges = fromVertex.getVertex().edges(direction, label.name()); + + while (edges.hasNext()) { + Edge edge = edges.next(); + edge.remove(); + } + } catch (Exception e) { + logger.debug("Failed to remove from vertex {} edges {} by direction {} ", fromVertex.getUniqueId(), label, direction, e); + return JanusGraphClient.handleJanusGraphException(e); + } + return JanusGraphOperationStatus.OK; + } + + /** + * Updates vertex properties. Note that graphVertex argument should contain updated data + * + * @param graphVertex + * @return + */ + public Either updateVertex(GraphVertex graphVertex) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId()); + try { + graphVertex.updateMetadataJsonWithCurrentMetadataProperties(); + setVertexProperties(graphVertex.getVertex(), graphVertex); + + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId(), e); + return Either.right(JanusGraphClient.handleJanusGraphException(e)); + } + return Either.left(graphVertex); + } + + /** + * Fetches vertices by uniqueId according to received parse flag + * + * @param verticesToGet + * @return + */ + public Either, JanusGraphOperationStatus> getVerticesByUniqueIdAndParseFlag(Map> verticesToGet) { + + Either, JanusGraphOperationStatus> result = null; + Map vertices = new HashMap<>(); + JanusGraphOperationStatus titatStatus; + Either getVertexRes = null; + for (Map.Entry> entry : verticesToGet.entrySet()) { + if (entry.getValue().getKey() == GraphPropertyEnum.UNIQUE_ID) { + getVertexRes = getVertexById(entry.getKey(), entry.getValue().getValue()); + } else if (entry.getValue().getKey() == GraphPropertyEnum.USERID) { + getVertexRes = getVertexByPropertyAndLabel(entry.getValue().getKey(), entry.getKey(), VertexTypeEnum.USER, entry.getValue().getValue()); + } + if (getVertexRes == null) { + titatStatus = JanusGraphOperationStatus.ILLEGAL_ARGUMENT; + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Invalid vertex type label {} has been received. ", entry.getValue().getKey(), titatStatus); + return Either.right(titatStatus); + } + if (getVertexRes.isRight()) { + titatStatus = getVertexRes.right().value(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get vertex by id {} . Status is {}. ", entry.getKey(), titatStatus); + result = Either.right(titatStatus); + break; + } else { + vertices.put(entry.getKey(), getVertexRes.left().value()); + } + } + if (result == null) { + result = Either.left(vertices); + } + return result; + } + + /** + * Creates edge between "from" and "to" vertices with specified label and properties extracted from received edge + * + * @param from + * @param to + * @param label + * @param edgeToCopy + * @return + */ + public JanusGraphOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Edge edgeToCopy) { + return createEdge(from, to, label, getEdgeProperties(edgeToCopy)); + } + + public JanusGraphOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, Edge prevEdge, EdgeLabelEnum prevLabel, EdgeLabelEnum newLabel) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, fromVertex!=null ? fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()) : "NULL", + toVertex!=null ? toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()) : "NULL"); + + JanusGraphOperationStatus result = createEdge(fromVertex, toVertex, newLabel, prevEdge); + if (result == JanusGraphOperationStatus.OK) { + prevEdge.remove(); + } + return result; + } + + /** + * Replaces previous label of edge with new label + * + * @param fromVertex + * @param toVertex + * @param prevLabel + * @param newLabel + * @return + */ + public JanusGraphOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, EdgeLabelEnum prevLabel, EdgeLabelEnum newLabel) { + + JanusGraphOperationStatus result = null; + Iterator prevEdgeIter = toVertex.edges(Direction.IN, prevLabel.name()); + if (prevEdgeIter == null || !prevEdgeIter.hasNext()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), + toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty())); + result = JanusGraphOperationStatus.NOT_FOUND; + } + if (result == null) { + result = replaceEdgeLabel(fromVertex, toVertex, prevEdgeIter.next(), prevLabel, newLabel); + } + return result; + } + + /** + * Updates metadata properties of vertex on graph. Json metadata property of the vertex will be updated with received properties too. + * + * + * @param vertex + * @param properties + * @return + */ + public JanusGraphOperationStatus updateVertexMetadataPropertiesWithJson(Vertex vertex, Map properties) { + try { + if (!MapUtils.isEmpty(properties)) { + String jsonMetadataStr = (String) vertex.property(GraphPropertyEnum.METADATA.getProperty()).value(); + Map jsonMetadataMap = JsonParserUtils.toMap(jsonMetadataStr); + for (Map.Entry property : properties.entrySet()) { + vertex.property(property.getKey().getProperty(), property.getValue()); + jsonMetadataMap.put(property.getKey().getProperty(), property.getValue()); + } + vertex.property(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.toJson(jsonMetadataMap)); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occurred during update vertex metadata properties with json{}. {}", vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), e.getMessage()); + return JanusGraphClient.handleJanusGraphException(e); + } + return JanusGraphOperationStatus.OK; + } + + public JanusGraphOperationStatus disassociateAndDeleteLast(GraphVertex vertex, Direction direction, EdgeLabelEnum label) { + try { + Iterator edges = vertex.getVertex().edges(direction, label.name()); + + while (edges.hasNext()) { + Edge edge = edges.next(); + Vertex secondVertex; + Direction reverseDirection; + if (direction == Direction.IN) { + secondVertex = edge.outVertex(); + reverseDirection = Direction.OUT; + } else { + secondVertex = edge.inVertex(); + reverseDirection = Direction.IN; + } + edge.remove(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Edge {} with direction {} was removed from {}", label.name(), direction, vertex.getVertex()); + + Iterator restOfEdges = secondVertex.edges(reverseDirection, label.name()); + if (!restOfEdges.hasNext()) { + secondVertex.remove(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "This was last edge . Vertex {} was removed ", vertex.getUniqueId()); + } + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge with the label {} direction {} from vertex {}. {}", label.name(), direction, vertex.getUniqueId(), e); + return JanusGraphClient.handleJanusGraphException(e); + } + return JanusGraphOperationStatus.OK; + } + + public Object getProperty(JanusGraphVertex vertex, String key) { + PropertyKey propertyKey = janusGraphClient.getGraph().left().value().getPropertyKey(key); + return vertex.valueOrNull(propertyKey); + } + + public Object getProperty(Edge edge, EdgePropertyEnum key) { + Object value = null; + try { + Property property = edge.property(key.getProperty()); + if (property != null) { + value = property.orElse(null); + if (value != null && key == EdgePropertyEnum.INSTANCES) { + return JsonParserUtils.toList((String) value, String.class); + } + return value; + } + } catch (Exception e) { + + } + return value; + } + + /** + * + * @param vertexA + * @param vertexB + * @param label + * @param direction + * @return + */ + public JanusGraphOperationStatus moveEdge(GraphVertex vertexA, GraphVertex vertexB, EdgeLabelEnum label, Direction direction) { + JanusGraphOperationStatus result = deleteEdgeByDirection(vertexA, direction, label); + if (result != JanusGraphOperationStatus.OK) { + logger.error("Failed to diassociate {} from element {}. error {} ", label, vertexA.getUniqueId(), result); + return result; + } + JanusGraphOperationStatus createRelation; + if (direction == Direction.IN) { + createRelation = createEdge(vertexB, vertexA, label, null); + } else { + createRelation = createEdge(vertexA, vertexB, label, null); + } + if (createRelation != JanusGraphOperationStatus.OK) { + return createRelation; + } + return JanusGraphOperationStatus.OK; + } + + public Either getBelongingEdgeByCriteria(String parentId, EdgeLabelEnum label, Map properties) { + Either getVertexRes = getVertexById(parentId, JsonParseFlagEnum.NoParse); + if (getVertexRes.isRight()) { + return Either.right(getVertexRes.right().value()); + } + return getBelongingEdgeByCriteria(getVertexRes.left().value(), label, properties); + } +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java deleted file mode 100644 index a31900acce..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java +++ /dev/null @@ -1,1078 +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.dao.jsongraph; - -import com.thinkaurelius.titan.core.*; -import fj.data.Either; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.tinkerpop.gremlin.structure.*; -import org.apache.tinkerpop.gremlin.structure.util.ElementHelper; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; -import org.openecomp.sdc.be.dao.titan.TitanGraphClient; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; - -import java.io.IOException; -import java.util.*; -import java.util.Map.Entry; - -import static org.apache.commons.collections.CollectionUtils.isEmpty; - - -public class TitanDao { - TitanGraphClient titanClient; - - private static Logger logger = Logger.getLogger(TitanDao.class.getName()); - - public TitanDao(@Qualifier("titan-client") TitanGraphClient titanClient) { - this.titanClient = titanClient; - logger.info("** TitanDao created"); - } - - public TitanOperationStatus commit() { - logger.debug("#commit - The operation succeeded. Doing commit..."); - return titanClient.commit(); - } - - public TitanOperationStatus rollback() { - logger.debug("#rollback - The operation failed. Doing rollback..."); - return titanClient.rollback(); - } - - public Either getGraph() { - return titanClient.getGraph(); - } - - /** - * - * @param graphVertex - * @return - */ - public Either createVertex(GraphVertex graphVertex) { - logger.trace("try to create vertex for ID [{}]", graphVertex.getUniqueId()); - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - TitanVertex vertex = tGraph.addVertex(); - - setVertexProperties(vertex, graphVertex); - - graphVertex.setVertex(vertex); - - return Either.left(graphVertex); - - } catch (Exception e) { - logger.debug("Failed to create Node for ID [{}]", graphVertex.getUniqueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - } else { - logger.debug("Failed to create vertex for ID [{}] {}", graphVertex.getUniqueId(), graph.right().value()); - return Either.right(graph.right().value()); - } - } - - /** - * - * @param name - * @param value - * @param label - * @return - */ - public Either getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, VertexTypeEnum label) { - return getVertexByPropertyAndLabel(name, value, label, JsonParseFlagEnum.ParseAll); - } - - public Either getVertexByLabel(VertexTypeEnum label) { - return titanClient.getGraph().left().map(graph -> graph.query().has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices()).left().bind(titanVertices -> getFirstFoundVertex(JsonParseFlagEnum.NoParse, titanVertices)); - } - - private Either getFirstFoundVertex(JsonParseFlagEnum parseFlag, Iterable vertices) { - Iterator iterator = vertices.iterator(); - if (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - GraphVertex graphVertex = createAndFill(vertex, parseFlag); - - return Either.left(graphVertex); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - /** - * - * @param name - * @param value - * @param label - * @param parseFlag - * @return - */ - public Either getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, VertexTypeEnum label, JsonParseFlagEnum parseFlag) { - - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - @SuppressWarnings("unchecked") - Iterable vertecies = tGraph.query().has(name.getProperty(), value).has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices(); - - java.util.Iterator iterator = vertecies.iterator(); - if (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - GraphVertex graphVertex = createAndFill(vertex, parseFlag); - - return Either.left(graphVertex); - } - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for key = {} and value = {} label = {}" + name, value, label); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed to get vertex in graph for key ={} and value = {} label = {}", name, value, label); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for key ={} and value = {} label = {} error :{}", name, value, label, graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - /** - * - * @param id - * @return - */ - public Either getVertexById(String id) { - return getVertexById(id, JsonParseFlagEnum.ParseAll); - } - - /** - * - * @param id - * @param parseFlag - * @return - */ - public Either getVertexById(String id, JsonParseFlagEnum parseFlag) { - - Either graph = titanClient.getGraph(); - if (id == null) { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for id = {} ", id); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - @SuppressWarnings("unchecked") - Iterable vertecies = tGraph.query().has(GraphPropertyEnum.UNIQUE_ID.getProperty(), id).vertices(); - - java.util.Iterator iterator = vertecies.iterator(); - if (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - GraphVertex graphVertex = createAndFill(vertex, parseFlag); - return Either.left(graphVertex); - } else { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for id = {}", id); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed to get vertex in graph for id {} ", id); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - } else { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for id {} error : {}", id, graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - private void setVertexProperties(TitanVertex vertex, GraphVertex graphVertex) throws IOException { - - if (graphVertex.getMetadataProperties() != null) { - for (Map.Entry entry : graphVertex.getMetadataProperties().entrySet()) { - if (entry.getValue() != null) { - vertex.property(entry.getKey().getProperty(), entry.getValue()); - } - } - } - vertex.property(GraphPropertyEnum.LABEL.getProperty(), graphVertex.getLabel().getName()); - - Map json = graphVertex.getJson(); - if (json != null) { - String jsonStr = JsonParserUtils.toJson(json); - vertex.property(GraphPropertyEnum.JSON.getProperty(), jsonStr); - - } - Map jsonMetadata = graphVertex.getMetadataJson(); - if (jsonMetadata != null) { - String jsonMetadataStr = JsonParserUtils.toJson(jsonMetadata); - vertex.property(GraphPropertyEnum.METADATA.getProperty(), jsonMetadataStr); - } - } - - public void setVertexProperties(Vertex vertex, Map properties) { - for (Map.Entry entry : properties.entrySet()) { - if (entry.getValue() != null) { - vertex.property(entry.getKey(), entry.getValue()); - } - } - } - - private GraphVertex createAndFill(TitanVertex vertex, JsonParseFlagEnum parseFlag) { - GraphVertex graphVertex = new GraphVertex(); - graphVertex.setVertex(vertex); - parseVertexProperties(graphVertex, parseFlag); - return graphVertex; - } - - public void parseVertexProperties(GraphVertex graphVertex, JsonParseFlagEnum parseFlag) { - TitanVertex vertex = graphVertex.getVertex(); - Map properties = getVertexProperties(vertex); - VertexTypeEnum label = VertexTypeEnum.getByName((String) (properties.get(GraphPropertyEnum.LABEL))); - for (Map.Entry entry : properties.entrySet()) { - GraphPropertyEnum key = entry.getKey(); - switch (key) { - case UNIQUE_ID: - graphVertex.setUniqueId((String) entry.getValue()); - break; - case LABEL: - graphVertex.setLabel(VertexTypeEnum.getByName((String) entry.getValue())); - break; - case COMPONENT_TYPE: - String type = (String) entry.getValue(); - if (type != null) { - graphVertex.setType(ComponentTypeEnum.valueOf(type)); - } - break; - case JSON: - if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseJson) { - String json = (String) entry.getValue(); - Map jsonObj = JsonParserUtils.toMap(json, label.getClassOfJson()); - graphVertex.setJson(jsonObj); - } - break; - case METADATA: - if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseMetadata) { - String json = (String) entry.getValue(); - Map metadatObj = JsonParserUtils.toMap(json); - graphVertex.setMetadataJson(metadatObj); - } - break; - default: - graphVertex.addMetadataProperty(key, entry.getValue()); - break; - } - } - } - - public TitanOperationStatus createEdge(GraphVertex from, GraphVertex to, EdgeLabelEnum label, Map properties) { - return createEdge(from.getVertex(), to.getVertex(), label, properties); - } - - public TitanOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Map properties) { - if (logger.isTraceEnabled()) { - logger.trace("Try to connect {} with {} label {} properties {}", - from == null ? "NULL" : from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), - to == null ? "NULL" : to.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), label, properties); - } - if (from == null || to == null) { - logger.trace("No Titan vertex for id from {} or id to {}", - from == null ? "NULL" : from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), - to == null ? "NULL" : to.property(GraphPropertyEnum.UNIQUE_ID.getProperty())); - return TitanOperationStatus.NOT_FOUND; - } - Edge edge = from.addEdge(label.name(), to); - TitanOperationStatus status; - try { - setEdgeProperties(edge, properties); - status = TitanOperationStatus.OK; - } catch (IOException e) { - logger.debug("Failed to set properties on edge properties [{}]", properties, e); - status = TitanOperationStatus.GENERAL_ERROR; - } - return status; - } - - public Map getVertexProperties(Element element) { - - Map result = new HashMap<>(); - - if (element != null && element.keys() != null && element.keys().size() > 0) { - Map propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()])); - - for (Entry entry : propertyMap.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue().value(); - - GraphPropertyEnum valueOf = GraphPropertyEnum.getByProperty(key); - if (valueOf != null) { - result.put(valueOf, value); - } - } - } - return result; - } - - public Map getEdgeProperties(Element element) { - - Map result = new HashMap<>(); - - if (element != null && element.keys() != null && element.keys().size() > 0) { - Map propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()])); - - for (Entry entry : propertyMap.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue().value(); - - EdgePropertyEnum valueOf = EdgePropertyEnum.getByProperty(key); - if (valueOf != null) { - if (valueOf == EdgePropertyEnum.INSTANCES) { - List list = JsonParserUtils.toList((String) value, String.class); - result.put(valueOf, list); - } else { - result.put(valueOf, value); - } - } - } - } - return result; - } - - public void setEdgeProperties(Element element, Map properties) throws IOException { - - if (properties != null && !properties.isEmpty()) { - - Object[] propertyKeyValues = new Object[properties.size() * 2]; - int i = 0; - for (Entry entry : properties.entrySet()) { - propertyKeyValues[i++] = entry.getKey().getProperty(); - Object value = entry.getValue(); - if (entry.getKey() == EdgePropertyEnum.INSTANCES) { - String jsonStr = JsonParserUtils.toJson(value); - propertyKeyValues[i++] = jsonStr; - } else { - propertyKeyValues[i++] = entry.getValue(); - } - } - ElementHelper.attachProperties(element, propertyKeyValues); - } - } - - public Either, TitanOperationStatus> getByCriteria(VertexTypeEnum type, Map props) { - return getByCriteria(type, props, JsonParseFlagEnum.ParseAll); - } - - public Either, TitanOperationStatus> getByCriteria(VertexTypeEnum type, Map props, JsonParseFlagEnum parseFlag) { - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - TitanGraphQuery query = tGraph.query(); - if (type != null) { - query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName()); - } - - if (props != null && !props.isEmpty()) { - for (Map.Entry entry : props.entrySet()) { - query = query.has(entry.getKey().getProperty(), entry.getValue()); - } - } - Iterable vertices = query.vertices(); - if (vertices == null) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - Iterator iterator = vertices.iterator(); - List result = new ArrayList<>(); - - while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - - Map newProp = getVertexProperties(vertex); - GraphVertex graphVertex = createAndFill(vertex, parseFlag); - - result.add(graphVertex); - } - if (logger.isDebugEnabled()) { - logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size()); - } - if (result.size() == 0) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - return Either.left(result); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - public Either, TitanOperationStatus> getByCriteria(VertexTypeEnum type, Map props, Map hasNotProps, JsonParseFlagEnum parseFlag) { - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - TitanGraphQuery query = tGraph.query(); - if (type != null) { - query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName()); - } - - if (props != null && !props.isEmpty()) { - for (Map.Entry entry : props.entrySet()) { - query = query.has(entry.getKey().getProperty(), entry.getValue()); - } - } - if (hasNotProps != null && !hasNotProps.isEmpty()) { - for (Map.Entry entry : hasNotProps.entrySet()) { - if (entry.getValue() instanceof List) { - buildMultipleNegateQueryFromList(entry, query); - } else { - query = query.hasNot(entry.getKey().getProperty(), entry.getValue()); - } - } - } - Iterable vertices = query.vertices(); - if (vertices == null) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - Iterator iterator = vertices.iterator(); - List result = new ArrayList<>(); - - while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - - Map newProp = getVertexProperties(vertex); - GraphVertex graphVertex = createAndFill(vertex, parseFlag); - - result.add(graphVertex); - } - if (logger.isDebugEnabled()) { - logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size()); - } - if (result.size() == 0) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - return Either.left(result); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - public Either, TitanOperationStatus> getCatalogOrArchiveVerticies(boolean isCatalog) { - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - String name = isCatalog ? VertexTypeEnum.CATALOG_ROOT.getName() : VertexTypeEnum.ARCHIVE_ROOT.getName(); - Iterable vCatalogIter = tGraph.query().has(GraphPropertyEnum.LABEL.getProperty(), name).vertices(); - if (vCatalogIter == null) { - logger.debug("Failed to fetch catalog vertex"); - return Either.right(TitanOperationStatus.GENERAL_ERROR); - } - TitanVertex catalogV = vCatalogIter.iterator().next(); - if (catalogV == null) { - logger.debug("Failed to fetch catalog vertex"); - return Either.right(TitanOperationStatus.GENERAL_ERROR); - } - String edgeLabel = isCatalog ? EdgeLabelEnum.CATALOG_ELEMENT.name() : EdgeLabelEnum.ARCHIVE_ELEMENT.name(); - Iterator vertices = catalogV.vertices(Direction.OUT, edgeLabel); - - return Either.left(vertices); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria: ", e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria : ", graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - private void buildMultipleNegateQueryFromList(Map.Entry entry, TitanGraphQuery query) { - List negateList = (List) entry.getValue(); - for (Object listItem : negateList) { - query.hasNot(entry.getKey().getProperty(), listItem); - } - } - - /** - * - * @param parentVertex - * @param edgeLabel - * @param parseFlag - * @return - */ - public Either getChildVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - Either, TitanOperationStatus> childrenVertecies = getChildrenVertecies(parentVertex, edgeLabel, parseFlag); - if (childrenVertecies.isRight()) { - return Either.right(childrenVertecies.right().value()); - } - return Either.left(childrenVertecies.left().value().get(0)); - } - - /** - * - * @param parentVertex - * @param edgeLabel - * @param parseFlag - * @return - */ - public Either getChildVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - Either, TitanOperationStatus> childrenVertecies = getChildrenVertecies(parentVertex, edgeLabel, parseFlag); - if (childrenVertecies.isRight()) { - return Either.right(childrenVertecies.right().value()); - } - return Either.left(childrenVertecies.left().value().get(0)); - } - - public Either getParentVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - Either, TitanOperationStatus> childrenVertecies = getParentVertecies(parentVertex, edgeLabel, parseFlag); - if (childrenVertecies.isRight()) { - return Either.right(childrenVertecies.right().value()); - } - if (isEmpty(childrenVertecies.left().value())){ - return Either.right(TitanOperationStatus.NOT_FOUND); - } - return Either.left(childrenVertecies.left().value().get(0)); - } - - public Either getParentVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - Either, TitanOperationStatus> childrenVertecies = getParentVertecies(parentVertex, edgeLabel, parseFlag); - if (childrenVertecies.isRight() ) { - return Either.right(childrenVertecies.right().value()); - } - if (isEmpty(childrenVertecies.left().value())){ - return Either.right(TitanOperationStatus.NOT_FOUND); - } - return Either.left(childrenVertecies.left().value().get(0)); - } - - /** - * - * @param parentVertex - * @param edgeLabel - * @param parseFlag - * @return - */ - public Either, TitanOperationStatus> getChildrenVertecies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.OUT); - } - - public Either, TitanOperationStatus> getParentVertecies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.IN); - } - - public Either, TitanOperationStatus> getParentVertecies(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.IN); - } - - private Either, TitanOperationStatus> getAdjacentVerticies(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag, Direction direction) { - List list = new ArrayList<>(); - try { - Either graphRes = titanClient.getGraph(); - if (graphRes.isRight()) { - logger.error("Failed to retrieve graph. status is {}", graphRes); - return Either.right(graphRes.right().value()); - } - Iterator edgesCreatorIterator = parentVertex.edges(direction, edgeLabel.name()); - if (edgesCreatorIterator != null) { - while (edgesCreatorIterator.hasNext()) { - Edge edge = edgesCreatorIterator.next(); - TitanVertex vertex; - if (direction == Direction.IN) { - vertex = (TitanVertex) edge.outVertex(); - } else { - vertex = (TitanVertex) edge.inVertex(); - } - // GraphVertex graphVertex = createAndFill(vertex, parseFlag); - - list.add(vertex); - } - } - if (list.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - } catch (Exception e) { - logger.error("Failed to perform graph operation ", e); - Either.right(TitanGraphClient.handleTitanException(e)); - } - - return Either.left(list); - } - - /** - * - * @param parentVertex - * @param edgeLabel - * @param parseFlag - * @return - */ - public Either, TitanOperationStatus> getChildrenVertecies(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.OUT); - } - - private Either, TitanOperationStatus> getAdjacentVerticies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag, Direction direction) { - List list = new ArrayList<>(); - - Either, TitanOperationStatus> adjacentVerticies = getAdjacentVerticies(parentVertex.getVertex(), edgeLabel, parseFlag, direction); - if (adjacentVerticies.isRight()) { - return Either.right(adjacentVerticies.right().value()); - } - adjacentVerticies.left().value().stream().forEach(vertex -> { - list.add(createAndFill((TitanVertex) vertex, parseFlag)); - }); - - return Either.left(list); - } - - /** - * Searches Edge by received label and criteria - * - * @param vertex - * @param label - * @param properties - * @return found edge or TitanOperationStatus - */ - public Either getBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, Map properties) { - - Either result = null; - Edge matchingEdge = null; - String notFoundMsg = "No edges in graph for criteria"; - try { - TitanVertexQuery query = vertex.getVertex().query().labels(label.name()); - - if (properties != null && !properties.isEmpty()) { - for (Map.Entry entry : properties.entrySet()) { - query = query.has(entry.getKey().getProperty(), entry.getValue()); - } - } - - Iterable edges = query.edges(); - if (edges == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg); - result = Either.right(TitanOperationStatus.NOT_FOUND); - } else { - Iterator eIter = edges.iterator(); - if (eIter.hasNext()) { - matchingEdge = eIter.next(); - } else { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg); - result = Either.right(TitanOperationStatus.NOT_FOUND); - } - } - if (result == null) { - result = Either.left(matchingEdge); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during getting edge by criteria for component with id {}. {}", vertex.getUniqueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - return result; - } - - public Either getEdgeByChildrenVertexProperties(GraphVertex vertex, EdgeLabelEnum label, Map properties) { - Either result = null; - Edge matchingEdge = null; - String notFoundMsg = "No edges in graph for criteria"; - try { - - Iterator edges = vertex.getVertex().edges(Direction.OUT, label.name()); - while (edges.hasNext()) { - matchingEdge = edges.next(); - Vertex childV = matchingEdge.inVertex(); - Map vertexProperties = getVertexProperties(childV); - Optional> findNotMatch = properties.entrySet().stream().filter(e -> vertexProperties.get(e.getKey()) == null || !vertexProperties.get(e.getKey()).equals(e.getValue())).findFirst(); - if (!findNotMatch.isPresent()) { - result = Either.left(matchingEdge); - } - } - if (result == null) { - //no match - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg); - result = Either.right(TitanOperationStatus.NOT_FOUND); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during getting edge by criteria for component with id {}. {}", vertex.getUniqueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - return result; - } - - /** - * Deletes Edge by received label and criteria - * - * @param vertex - * @param label - * @param properties - * @return - */ - public Either deleteBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, Map properties) { - Either result = null; - try { - result = getBelongingEdgeByCriteria(vertex, label, properties); - if (result.isLeft()) { - Edge edge = result.left().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to delete an edge with the label {} belonging to the vertex {} ", label.name(), vertex.getUniqueId()); - edge.remove(); - result = Either.left(edge); - } else { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find an edge with the label {} belonging to the vertex {} ", label.name(), vertex.getUniqueId()); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge by criteria for the component with id {}. {}", vertex == null ? "NULL" : vertex.getUniqueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - return result; - } - - @SuppressWarnings("unchecked") - /** - * Deletes an edge between vertices fromVertex and toVertex according to received label - * - * @param fromVertex - * @param toVertex - * @param label - * @return - */ - - public Either deleteEdge(GraphVertex fromVertex, GraphVertex toVertex, EdgeLabelEnum label) { - return deleteEdge(fromVertex.getVertex(), toVertex.getVertex(), label, fromVertex.getUniqueId(), toVertex.getUniqueId(), false); - } - - public Either deleteAllEdges(GraphVertex fromVertex, GraphVertex toVertex, EdgeLabelEnum label) { - return deleteEdge(fromVertex.getVertex(), toVertex.getVertex(), label, fromVertex.getUniqueId(), toVertex.getUniqueId(), true); - } - - public Either deleteEdge(TitanVertex fromVertex, TitanVertex toVertex, EdgeLabelEnum label, String uniqueIdFrom, String uniqueIdTo, boolean deleteAll) { - Either result = null; - try { - Iterable edges = fromVertex.query().labels(label.name()).edges(); - Iterator eIter = edges.iterator(); - while (eIter.hasNext()) { - Edge edge = eIter.next(); - String currVertexUniqueId = edge.inVertex().value(GraphPropertyEnum.UNIQUE_ID.getProperty()); - if (currVertexUniqueId != null && currVertexUniqueId.equals(uniqueIdTo)) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to delete an edge with the label {} between vertices {} and {}. ", label.name(), uniqueIdFrom, uniqueIdTo); - edge.remove(); - result = Either.left(edge); - if (!deleteAll) { - break; - } - } - } - if (result == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete an edge with the label {} between vertices {} and {}. ", label.name(), uniqueIdFrom, uniqueIdTo); - result = Either.right(TitanOperationStatus.NOT_FOUND); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge with the label {} between vertices {} and {}. {}", label.name(), uniqueIdFrom, uniqueIdTo, e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - return result; - } - - public TitanOperationStatus deleteEdgeByDirection(GraphVertex fromVertex, Direction direction, EdgeLabelEnum label) { - try { - Iterator edges = fromVertex.getVertex().edges(direction, label.name()); - - while (edges.hasNext()) { - Edge edge = edges.next(); - edge.remove(); - } - } catch (Exception e) { - logger.debug("Failed to remove from vertex {} edges {} by direction {} ", fromVertex.getUniqueId(), label, direction, e); - return TitanGraphClient.handleTitanException(e); - } - return TitanOperationStatus.OK; - } - - /** - * Updates vertex properties. Note that graphVertex argument should contain updated data - * - * @param graphVertex - * @return - */ - public Either updateVertex(GraphVertex graphVertex) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId()); - try { - graphVertex.updateMetadataJsonWithCurrentMetadataProperties(); - setVertexProperties(graphVertex.getVertex(), graphVertex); - - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - return Either.left(graphVertex); - } - - /** - * Fetches vertices by uniqueId according to received parse flag - * - * @param verticesToGet - * @return - */ - public Either, TitanOperationStatus> getVerticesByUniqueIdAndParseFlag(Map> verticesToGet) { - - Either, TitanOperationStatus> result = null; - Map vertices = new HashMap<>(); - TitanOperationStatus titatStatus; - Either getVertexRes = null; - for (Map.Entry> entry : verticesToGet.entrySet()) { - if (entry.getValue().getKey() == GraphPropertyEnum.UNIQUE_ID) { - getVertexRes = getVertexById(entry.getKey(), entry.getValue().getValue()); - } else if (entry.getValue().getKey() == GraphPropertyEnum.USERID) { - getVertexRes = getVertexByPropertyAndLabel(entry.getValue().getKey(), entry.getKey(), VertexTypeEnum.USER, entry.getValue().getValue()); - } - if (getVertexRes == null) { - titatStatus = TitanOperationStatus.ILLEGAL_ARGUMENT; - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Invalid vertex type label {} has been received. ", entry.getValue().getKey(), titatStatus); - return Either.right(titatStatus); - } - if (getVertexRes.isRight()) { - titatStatus = getVertexRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get vertex by id {} . Status is {}. ", entry.getKey(), titatStatus); - result = Either.right(titatStatus); - break; - } else { - vertices.put(entry.getKey(), getVertexRes.left().value()); - } - } - if (result == null) { - result = Either.left(vertices); - } - return result; - } - - /** - * Creates edge between "from" and "to" vertices with specified label and properties extracted from received edge - * - * @param from - * @param to - * @param label - * @param edgeToCopy - * @return - */ - public TitanOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Edge edgeToCopy) { - return createEdge(from, to, label, getEdgeProperties(edgeToCopy)); - } - - public TitanOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, Edge prevEdge, EdgeLabelEnum prevLabel, EdgeLabelEnum newLabel) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, fromVertex!=null ? fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()) : "NULL", - toVertex!=null ? toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()) : "NULL"); - - TitanOperationStatus result = createEdge(fromVertex, toVertex, newLabel, prevEdge); - if (result == TitanOperationStatus.OK) { - prevEdge.remove(); - } - return result; - } - - /** - * Replaces previous label of edge with new label - * - * @param fromVertex - * @param toVertex - * @param prevLabel - * @param newLabel - * @return - */ - public TitanOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, EdgeLabelEnum prevLabel, EdgeLabelEnum newLabel) { - - TitanOperationStatus result = null; - Iterator prevEdgeIter = toVertex.edges(Direction.IN, prevLabel.name()); - if (prevEdgeIter == null || !prevEdgeIter.hasNext()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), - toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty())); - result = TitanOperationStatus.NOT_FOUND; - } - if (result == null) { - result = replaceEdgeLabel(fromVertex, toVertex, prevEdgeIter.next(), prevLabel, newLabel); - } - return result; - } - - /** - * Updates metadata properties of vertex on graph. Json metadata property of the vertex will be updated with received properties too. - * - * - * @param vertex - * @param properties - * @return - */ - public TitanOperationStatus updateVertexMetadataPropertiesWithJson(Vertex vertex, Map properties) { - try { - if (!MapUtils.isEmpty(properties)) { - String jsonMetadataStr = (String) vertex.property(GraphPropertyEnum.METADATA.getProperty()).value(); - Map jsonMetadataMap = JsonParserUtils.toMap(jsonMetadataStr); - for (Map.Entry property : properties.entrySet()) { - vertex.property(property.getKey().getProperty(), property.getValue()); - jsonMetadataMap.put(property.getKey().getProperty(), property.getValue()); - } - vertex.property(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.toJson(jsonMetadataMap)); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occurred during update vertex metadata properties with json{}. {}", vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), e.getMessage()); - return TitanGraphClient.handleTitanException(e); - } - return TitanOperationStatus.OK; - } - - public TitanOperationStatus disassociateAndDeleteLast(GraphVertex vertex, Direction direction, EdgeLabelEnum label) { - try { - Iterator edges = vertex.getVertex().edges(direction, label.name()); - - while (edges.hasNext()) { - Edge edge = edges.next(); - Vertex secondVertex; - Direction reverseDirection; - if (direction == Direction.IN) { - secondVertex = edge.outVertex(); - reverseDirection = Direction.OUT; - } else { - secondVertex = edge.inVertex(); - reverseDirection = Direction.IN; - } - edge.remove(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Edge {} with direction {} was removed from {}", label.name(), direction, vertex.getVertex()); - - Iterator restOfEdges = secondVertex.edges(reverseDirection, label.name()); - if (!restOfEdges.hasNext()) { - secondVertex.remove(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "This was last edge . Vertex {} was removed ", vertex.getUniqueId()); - } - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge with the label {} direction {} from vertex {}. {}", label.name(), direction, vertex.getUniqueId(), e); - return TitanGraphClient.handleTitanException(e); - } - return TitanOperationStatus.OK; - } - - public Object getProperty(TitanVertex vertex, String key) { - PropertyKey propertyKey = titanClient.getGraph().left().value().getPropertyKey(key); - return vertex.valueOrNull(propertyKey); - } - - public Object getProperty(Edge edge, EdgePropertyEnum key) { - Object value = null; - try { - Property property = edge.property(key.getProperty()); - if (property != null) { - value = property.orElse(null); - if (value != null && key == EdgePropertyEnum.INSTANCES) { - return JsonParserUtils.toList((String) value, String.class); - } - return value; - } - } catch (Exception e) { - - } - return value; - } - - /** - * - * @param vertexA - * @param vertexB - * @param label - * @param direction - * @return - */ - public TitanOperationStatus moveEdge(GraphVertex vertexA, GraphVertex vertexB, EdgeLabelEnum label, Direction direction) { - TitanOperationStatus result = deleteEdgeByDirection(vertexA, direction, label); - if (result != TitanOperationStatus.OK) { - logger.error("Failed to diassociate {} from element {}. error {} ", label, vertexA.getUniqueId(), result); - return result; - } - TitanOperationStatus createRelation; - if (direction == Direction.IN) { - createRelation = createEdge(vertexB, vertexA, label, null); - } else { - createRelation = createEdge(vertexA, vertexB, label, null); - } - if (createRelation != TitanOperationStatus.OK) { - return createRelation; - } - return TitanOperationStatus.OK; - } - - public Either getBelongingEdgeByCriteria(String parentId, EdgeLabelEnum label, Map properties) { - Either getVertexRes = getVertexById(parentId, JsonParseFlagEnum.NoParse); - if (getVertexRes.isRight()) { - return Either.right(getVertexRes.right().value()); - } - return getBelongingEdgeByCriteria(getVertexRes.left().value(), label, properties); - } -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/heal/AbstractJanusGraphVertexHeal.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/heal/AbstractJanusGraphVertexHeal.java new file mode 100644 index 0000000000..f60a063a0a --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/heal/AbstractJanusGraphVertexHeal.java @@ -0,0 +1,22 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * 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. + */ +package org.openecomp.sdc.be.dao.jsongraph.heal; + +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; + +public abstract class AbstractJanusGraphVertexHeal implements Heal { + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/heal/AbstractTitanVertexHeal.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/heal/AbstractTitanVertexHeal.java deleted file mode 100644 index e01ddab989..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/heal/AbstractTitanVertexHeal.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright © 2016-2018 European Support Limited - * - * 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. - */ -package org.openecomp.sdc.be.dao.jsongraph.heal; - -import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; - -public abstract class AbstractTitanVertexHeal implements Heal { - -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/HealingTitanGenericDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/HealingTitanGenericDao.java deleted file mode 100644 index 37546a5c2a..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/HealingTitanGenericDao.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright © 2016-2018 European Support Limited - * - * 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. - */ -package org.openecomp.sdc.be.dao.titan; - -import com.thinkaurelius.titan.core.TitanVertex; -import fj.data.Either; -import java.util.List; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; -import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; -import org.openecomp.sdc.be.dao.impl.HealingPipelineDao; -import org.openecomp.sdc.be.dao.jsongraph.heal.Heal; -import org.openecomp.sdc.be.dao.jsongraph.heal.HealConstants; -import org.openecomp.sdc.be.dao.jsongraph.heal.HealVersion; -import org.openecomp.sdc.be.dao.jsongraph.heal.HealVersionBuilder; -import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component("titan-generic-dao") -public class HealingTitanGenericDao extends TitanGenericDao { - - @Autowired - private HealingPipelineDao healingPipelineDao; - - public HealingTitanGenericDao(TitanGraphClient titanClient) { - super(titanClient); - } - - @Override - public ImmutablePair getChildVertex(TitanVertex childVertex, GraphEdgeLabels edgeType) { - ImmutablePair childVertexEdgeImmutablePair = super.getChildVertex(childVertex, edgeType); - final TitanVertex graphVertex = childVertexEdgeImmutablePair.left; - healingPipelineDao.performGraphReadHealing(graphVertex, edgeType); - healingPipelineDao.setHealingVersion(graphVertex); - return childVertexEdgeImmutablePair; - } - - @Override - public Either>, TitanOperationStatus> getChildrenNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz, boolean withEdges) { - Either>, TitanOperationStatus> either = super.getChildrenNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz, withEdges); - if (either.isRight()) { - return either; - } - List> list = either.left().value(); - list.forEach(this::transformPair); - return either; - } - - @Override - public Either, TitanOperationStatus> getChild(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz) { - Either, TitanOperationStatus> eitherChild = super.getChild(key, uniqueId, edgeType, nodeTypeEnum, clazz); - if (eitherChild.isRight()) { - return eitherChild; - } - ImmutablePair pair = eitherChild.left().value(); - GraphNode graphNode = pair.left; - GraphEdge graphEdge = pair.right; - healingPipelineDao.performGraphReadHealing(graphNode, graphEdge); - healingPipelineDao.setHealingVersion(graphNode); - return eitherChild; - } - - private void transformPair(ImmutablePair either) { - GraphEdge edgeType = either.right; - GraphNode childVertex = either.left; - Integer healingVersioInt = childVertex.getHealingVersion(); - HealVersionBuilder.build(healingVersioInt); - healingPipelineDao.performGraphReadHealing(childVertex, edgeType); - healingPipelineDao.setHealingVersion(childVertex); - } - - @Override - public Either>, TitanOperationStatus> getChildrenVertecies(String key, String uniqueId, GraphEdgeLabels edgeType) { - Either>, TitanOperationStatus> either = super.getChildrenVertecies(key, uniqueId, edgeType); - if (either.isRight()) { - return either; - } - List> list = either.left().value(); - list.forEach(this::transformVertexPair); - return either; - } - - private void transformVertexPair(ImmutablePair either) { - String edgeType = either.right.label(); - TitanVertex childVertex = either.left; - VertexProperty healingVersionProperty = childVertex.property(GraphPropertyEnum.HEALING_VERSION.getProperty()); - Integer healingVersioInt = healingVersionProperty.orElse(HealConstants.DEFAULT_HEAL_VERSION); - HealVersionBuilder.build(healingVersioInt); - healingPipelineDao.performGraphReadHealing(childVertex, edgeType); - healingPipelineDao.setHealingVersion(childVertex); - } - - @Override - public Either updateNode(GraphNode node, Class clazz) { - healingPipelineDao.setHealingVersion(node); - return super.updateNode(node, clazz); - } - - @Override - public TitanOperationStatus updateVertex(GraphNode node, Vertex vertex) { - healingPipelineDao.setHealingVersion(node); - return super.updateVertex(node, vertex); - } - - - public void setHealingPipelineDao(HealingPipelineDao healingPipelineDao) { - this.healingPipelineDao = healingPipelineDao; - } -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/QueryType.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/QueryType.java deleted file mode 100644 index 689ed32a8a..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/QueryType.java +++ /dev/null @@ -1,28 +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.dao.titan; - -/** - * Created by mlando on 9/21/2016. - */ -public enum QueryType { - HAS, HAS_NOT -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java deleted file mode 100644 index 2123910650..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java +++ /dev/null @@ -1,1769 +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.dao.titan; - -import com.thinkaurelius.titan.core.PropertyKey; -import com.thinkaurelius.titan.core.TitanEdge; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanGraphQuery; -import com.thinkaurelius.titan.core.TitanVertex; -import com.thinkaurelius.titan.core.TitanVertexQuery; -import com.thinkaurelius.titan.graphdb.query.TitanPredicate; -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.Map.Entry; -import java.util.stream.Collectors; -import java.util.stream.StreamSupport; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.ImmutableTriple; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Element; -import org.apache.tinkerpop.gremlin.structure.Property; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.util.ElementHelper; -import org.openecomp.sdc.be.config.ConfigurationManager; -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.GraphPropertiesDictionary; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.resources.data.GraphNodeLock; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.springframework.beans.factory.annotation.Qualifier; - -public class TitanGenericDao { - - private static final String FAILED_TO_RETRIEVE_GRAPH_STATUS_IS = "Failed to retrieve graph. status is {}"; - private static final String NO_EDGES_IN_GRAPH_FOR_CRITERIA = "No edges in graph for criteria"; - private static final String FAILED_TO_CREATE_EDGE_FROM_TO = "Failed to create edge from [{}] to [{}]"; - private TitanGraphClient titanClient; - private static Logger log = Logger.getLogger(TitanGenericDao.class.getName()); - private static final String LOCK_NODE_PREFIX = "lock_"; - - public TitanGenericDao(@Qualifier("titan-client") TitanGraphClient titanClient) { - this.titanClient = titanClient; - log.info("** TitanGenericDao created"); - } - - public TitanOperationStatus commit() { - log.debug("doing commit."); - return titanClient.commit(); - } - - public TitanOperationStatus rollback() { - log.error("Going to execute rollback on graph."); - return titanClient.rollback(); - } - - public void handleTransactionCommitRollback(boolean inTransaction, Either result) { - if (!inTransaction) { - if (result == null || result.isRight()) { - rollback(); - } else { - commit(); - } - } - } - - public Either getGraph() { - return titanClient.getGraph(); - } - - // For healthCheck - public boolean isGraphOpen() { - return titanClient.getHealth(); - } - - /** - * - * @param node - * @param clazz - * @return - */ - public Either createNode(T node, Class clazz) { - log.debug("try to create node for ID [{}]", node.getKeyValueId()); - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - T newNode; - try { - TitanGraph tGraph = graph.left().value(); - - Vertex vertex = tGraph.addVertex(); - - vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), node.getLabel()); - - Map properties = node.toGraphMap(); - if (properties != null) { - setProperties(vertex, properties); - } - Map newProps = getProperties(vertex); - newNode = GraphElementFactory.createElement(node.getLabel(), GraphElementTypeEnum.Node, newProps, clazz); - log.debug("created node for props : {}", newProps); - log.debug("Node was created for ID [{}]", node.getKeyValueId()); - return Either.left(newNode); - - } catch (Exception e) { - log.debug("Failed to create Node for ID [{}]", node.getKeyValueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - log.debug("Failed to create Node for ID [{}] {}", node.getKeyValueId(), graph.right().value()); - return Either.right(graph.right().value()); - } - } - - public Either createNode(GraphNode node) { - log.debug("try to create node for ID [{}]", node.getKeyValueId()); - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - TitanVertex vertex = tGraph.addVertex(); - - vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), node.getLabel()); - - Map properties = node.toGraphMap(); - if (properties != null) { - setProperties(vertex, properties); - } - log.debug("Node was created for ID [{}]", node.getKeyValueId()); - return Either.left(vertex); - - } catch (Exception e) { - log.debug("Failed to create Node for ID [{}]", node.getKeyValueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - log.debug("Failed to create Node for ID [{}] {}", node.getKeyValueId(), graph.right().value()); - return Either.right(graph.right().value()); - } - } - - /** - * - * @param relation - * @return - */ - public Either createRelation(GraphRelation relation) { - log.debug("try to create relation from [{}] to [{}] ", relation.getFrom(), relation.getTo()); - - RelationEndPoint from = relation.getFrom(); - RelationEndPoint to = relation.getTo(); - ImmutablePair fromKeyId = new ImmutablePair<>(from.getIdName(), from.getIdValue()); - ImmutablePair toKeyId = new ImmutablePair<>(to.getIdName(), to.getIdValue()); - - return createEdge(relation.getType(), fromKeyId, toKeyId, from.getLabel().getName(), to.getLabel().getName(), relation.toGraphMap()); - - } - - private Either createEdge(String type, ImmutablePair from, ImmutablePair to, String fromLabel, String toLabel, Map properties) { - Either graph = titanClient.getGraph(); - - if (graph.isLeft()) { - try { - Either fromV = getVertexByPropertyAndLabel(from.getKey(), from.getValue(), fromLabel); - if (fromV.isRight()) { - TitanOperationStatus error = fromV.right().value(); - if (TitanOperationStatus.NOT_FOUND.equals(error)) { - return Either.right(TitanOperationStatus.INVALID_ID); - } else { - return Either.right(error); - } - } - Either toV = getVertexByPropertyAndLabel(to.getKey(), to.getValue(), toLabel); - if (toV.isRight()) { - TitanOperationStatus error = toV.right().value(); - if (TitanOperationStatus.NOT_FOUND.equals(error)) { - return Either.right(TitanOperationStatus.INVALID_ID); - } else { - return Either.right(error); - } - } - - Vertex fromVertex = fromV.left().value(); - Vertex toVertex = toV.left().value(); - Edge edge = fromVertex.addEdge(type, toVertex); - - if (properties != null) { - - setProperties(edge, properties); - } - - Vertex vertexOut = edge.outVertex(); - Vertex vertexIn = edge.inVertex(); - - GraphNode nodeOut = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(vertexOut), GraphNode.class); - GraphNode nodeIn = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(vertexIn), GraphNode.class); - - GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeOut, nodeIn); - - return Either.left(newRelation); - } catch (Exception e) { - log.debug(FAILED_TO_CREATE_EDGE_FROM_TO, from, to, e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - } else { - log.debug("Failed to create edge from [{}] to [{}] {}", from, to, graph.right().value()); - return Either.right(graph.right().value()); - } - } - - public TitanOperationStatus createEdge(Vertex vertexOut, Vertex vertexIn, GraphEdgeLabels type, Map properties) { - try { - Edge edge = addEdge(vertexOut, vertexIn, type, properties); - } catch (Exception e) { - log.debug(FAILED_TO_CREATE_EDGE_FROM_TO, vertexOut, vertexIn, e); - return TitanGraphClient.handleTitanException(e); - } - return TitanOperationStatus.OK; - - } - - private Edge addEdge(Vertex vertexOut, Vertex vertexIn, GraphEdgeLabels type, Map properties) { - Edge edge = vertexOut.addEdge(type.getProperty(), vertexIn); - - if (properties != null) { - - setProperties(edge, properties); - } - return edge; - } - - /** - * creates an identical edge in the graph - * @param edge - * @return the copy operation status - */ - public Either copyEdge(Vertex out, Vertex in, Edge edge) { - GraphEdgeLabels byName = GraphEdgeLabels.getByName(edge.label()); - return this.saveEdge(out, in, byName, edgePropertiesToMap(edge)); - } - - private Map edgePropertiesToMap(Edge edge) { - Iterable> propertiesIterable = edge::properties; - return StreamSupport.stream(propertiesIterable.spliterator(), false).collect(Collectors.toMap(Property::key, Property::value)); - } - - public Either saveEdge(Vertex vertexOut, Vertex vertexIn, GraphEdgeLabels type, Map properties) { - try { - Edge edge = addEdge(vertexOut, vertexIn, type, properties); - return Either.left(edge); - } catch (Exception e) { - log.debug(FAILED_TO_CREATE_EDGE_FROM_TO, vertexOut, vertexIn, e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } - - public TitanOperationStatus createEdge(TitanVertex vertexOut, GraphNode to, GraphEdgeLabels type, Map properties) { - - TitanVertex vertexIn; - Either toV = getVertexByPropertyAndLabel(to.getUniqueIdKey(), to.getUniqueId(), to.getLabel()); - if (toV.isRight()) { - TitanOperationStatus error = toV.right().value(); - if (TitanOperationStatus.NOT_FOUND.equals(error)) { - return TitanOperationStatus.INVALID_ID; - } else { - return error; - } - } - vertexIn = (TitanVertex) toV.left().value(); - return createEdge(vertexOut, vertexIn, type, properties); - } - - /** - * - * @param from - * @param to - * @param label - * @param properties - * @return - */ - public Either createRelation(GraphNode from, GraphNode to, GraphEdgeLabels label, Map properties) { - log.debug("try to create relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); - return createEdge(label.getProperty(), from.getKeyValueId(), to.getKeyValueId(), from.getLabel(), to.getLabel(), properties); - } - - public Either replaceRelationLabel(GraphNode from, GraphNode to, GraphEdgeLabels label, GraphEdgeLabels newLabel) { - - log.debug("try to replace relation {} to {} from [{}] to [{}]", label.name(), newLabel.name(), from.getKeyValueId(), to.getKeyValueId()); - Either getRelationResult = getRelation(from, to, label); - if (getRelationResult.isRight()) { - return getRelationResult; - } - - GraphRelation origRelation = getRelationResult.left().value(); - Either createRelationResult = createRelation(from, to, newLabel, origRelation.toGraphMap()); - if (createRelationResult.isRight()) { - return createRelationResult; - } - - Either deleteRelationResult = deleteRelation(origRelation); - if (deleteRelationResult.isRight()) { - return deleteRelationResult; - } - return Either.left(createRelationResult.left().value()); - } - - /** - * - * @param keyName - * @param keyValue - * @param clazz - * @return - */ - public Either getNode(String keyName, Object keyValue, Class clazz) { - - log.debug("Try to get node for key [{}] with value [{}] ", keyName, keyValue); - - Either vertexByProperty = getVertexByProperty(keyName, keyValue); - - if (vertexByProperty.isLeft()) { - try { - Vertex vertex = vertexByProperty.left().value(); - Map properties = getProperties(vertex); - T node = GraphElementFactory.createElement((String) properties.get(GraphPropertiesDictionary.LABEL.getProperty()), GraphElementTypeEnum.Node, properties, clazz); - return Either.left(node); - } catch (Exception e) { - log.debug("Failed to get node for key [{}] with value [{}] ", keyName, keyValue, e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - } else { - log.debug("Failed to get node for key [{}] with value [{}] ", keyName, keyValue, vertexByProperty.right().value()); - return Either.right(vertexByProperty.right().value()); - } - } - - /** - * - * @param from - * @param to - * @param label - * @return - */ - public Either getRelation(GraphNode from, GraphNode to, GraphEdgeLabels label) { - log.debug("try to get relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); - - Either edge = getEdgeByNodes(from, to, label); - - if (edge.isLeft()) { - try { - Map properties = getProperties(edge.left().value()); - GraphRelation relation = GraphElementFactory.createRelation(label.getProperty(), properties, from, to); - return Either.left(relation); - } catch (Exception e) { - log.debug("Failed to get get relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - } else { - log.debug("Failed to get get relation from [{}] to [{}] {}", from.getKeyValueId(), to.getKeyValueId(), edge.right().value()); - return Either.right(edge.right().value()); - } - } - - public Either getEdgeByNodes(GraphNode from, GraphNode to, GraphEdgeLabels label) { - ImmutablePair keyValueIdFrom = from.getKeyValueId(); - ImmutablePair keyValueIdTo = to.getKeyValueId(); - - return getEdgeByVerticies(keyValueIdFrom.getKey(), keyValueIdFrom.getValue(), keyValueIdTo.getKey(), keyValueIdTo.getValue(), label.getProperty()); - } - - public Either deleteIncomingRelationByCriteria(GraphNode to, GraphEdgeLabels label, Map props) { - - Either edgeByCriteria = getIncomingEdgeByCriteria(to, label, props); - if (edgeByCriteria.isLeft()) { - Either graph = getGraph(); - if (graph.isLeft()) { - Edge edge = edgeByCriteria.left().value(); - log.debug("delete edge {} to {} ", label.getProperty(), to.getUniqueId()); - edge.remove(); - Map properties = getProperties(edge); - Vertex fromVertex = edge.outVertex(); - String fromLabel = fromVertex.value(GraphPropertiesDictionary.LABEL.getProperty()); - GraphNode nodeFrom = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(fromVertex), GraphNode.class); - GraphRelation relation = GraphElementFactory.createRelation(label.getProperty(), properties, nodeFrom, to); - return Either.left(relation); - } else { - log.debug("failed to get graph"); - return Either.right(graph.right().value()); - } - - } else { - log.debug("failed to find edge {} to {}", label.getProperty(), to.getUniqueId()); - return Either.right(edgeByCriteria.right().value()); - } - - } - - public Either getIncomingRelationByCriteria(GraphNode to, GraphEdgeLabels label, Map props) { - - Either edgeByCriteria = getIncomingEdgeByCriteria(to, label, props); - if (edgeByCriteria.isLeft()) { - Either graph = getGraph(); - if (graph.isLeft()) { - Edge edge = edgeByCriteria.left().value(); - Map properties = getProperties(edge); - Vertex fromVertex = edge.outVertex(); - String fromLabel = fromVertex.value(GraphPropertiesDictionary.LABEL.getProperty()); - GraphNode nodeFrom = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(fromVertex), GraphNode.class); - GraphRelation relation = GraphElementFactory.createRelation(label.getProperty(), properties, nodeFrom, to); - return Either.left(relation); - } else { - log.debug("failed to get graph"); - return Either.right(graph.right().value()); - } - - } else { - log.debug("failed to find edge {} to {}", label.getProperty(), to.getUniqueId()); - return Either.right(edgeByCriteria.right().value()); - } - - } - - public Either getIncomingEdgeByCriteria(GraphNode to, GraphEdgeLabels label, Map props) { - - ImmutablePair keyValueIdTo = to.getKeyValueId(); - - Either vertexFrom = getVertexByProperty(keyValueIdTo.getKey(), keyValueIdTo.getValue()); - if (vertexFrom.isRight()) { - return Either.right(vertexFrom.right().value()); - } - Vertex vertex = vertexFrom.left().value(); - TitanVertex titanVertex = (TitanVertex) vertex; - TitanVertexQuery query = titanVertex.query(); - query = query.labels(label.getProperty()); - - if (props != null && !props.isEmpty()) { - for (Map.Entry entry : props.entrySet()) { - query = query.has(entry.getKey(), entry.getValue()); - } - } - Edge matchingEdge = null; - Iterable edges = query.edges(); - if (edges == null) { - log.debug(NO_EDGES_IN_GRAPH_FOR_CRITERIA); - return Either.right(TitanOperationStatus.NOT_FOUND); - } - Iterator eIter = edges.iterator(); - if (eIter.hasNext()) { - matchingEdge = eIter.next(); - } - - if (matchingEdge == null) { - log.debug(NO_EDGES_IN_GRAPH_FOR_CRITERIA); - return Either.right(TitanOperationStatus.NOT_FOUND); - } - return Either.left(matchingEdge); - } - - public Either getEdgeByVerticies(String keyNameFrom, Object keyValueFrom, String keyNameTo, Object keyValueTo, String label) { - Either graph = titanClient.getGraph(); - - if (graph.isLeft()) { - try { - Either vertexFrom = getVertexByProperty(keyNameFrom, keyValueFrom); - if (vertexFrom.isRight()) { - return Either.right(vertexFrom.right().value()); - } - Iterable edges = vertexFrom.left().value().query().labels(label).edges(); - Iterator eIter = edges.iterator(); - while (eIter.hasNext()) { - Edge edge = eIter.next(); - Vertex vertexIn = edge.inVertex(); - if (vertexIn.value(keyNameTo) != null && vertexIn.value(keyNameTo).equals(keyValueTo) && label.equals(edge.label())) { - return Either.left(edge); - } - } - log.debug("No relation in graph from [{}={}] to [{}={}]", keyNameFrom, keyValueFrom, keyNameTo, keyValueTo); - return Either.right(TitanOperationStatus.NOT_FOUND); - } catch (Exception e) { - log.debug("Failed to get get relation from [{}={}] to [{}={}]", keyNameFrom, keyValueFrom, keyNameTo, keyValueTo, e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - } else { - return Either.right(graph.right().value()); - } - } - - public Either, TitanOperationStatus> getEdgesForNode(GraphNode node, Direction requestedDirection) { - - Either, TitanOperationStatus> result; - - ImmutablePair keyValueId = node.getKeyValueId(); - Either eitherVertex = getVertexByProperty(keyValueId.getKey(), keyValueId.getValue()); - - if (eitherVertex.isLeft()) { - List edges = prepareEdgesList(eitherVertex.left().value(), requestedDirection); - - result = Either.left(edges); - } else { - result = Either.right(eitherVertex.right().value()); - } - return result; - } - - private List prepareEdgesList(Vertex vertex, Direction requestedDirection) { - List edges = new ArrayList<>(); - Iterator edgesItr = ((TitanVertex) vertex).query().edges().iterator(); - while (edgesItr.hasNext()) { - Edge edge = edgesItr.next(); - Direction currEdgeDirection = getEdgeDirection(vertex, edge); - if (currEdgeDirection == requestedDirection || requestedDirection == Direction.BOTH) { - edges.add(edge); - } - - } - return edges; - } - - private Direction getEdgeDirection(Vertex vertex, Edge edge) { - Direction result; - Vertex vertexOut = edge.outVertex(); - if (vertexOut.equals(vertex)) { - result = Direction.OUT; - } else { - result = Direction.IN; - - } - return result; - } - - /** - * - * @param from - * @param to - * @param label - * @param properties - * @return - */ - public Either updateRelation(GraphNode from, GraphNode to, GraphEdgeLabels label, Map properties) { - log.debug("try to update relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); - return updateEdge(label.getProperty(), from.getKeyValueId(), to.getKeyValueId(), from.getLabel(), to.getLabel(), properties); - } - - private Either updateEdge(String type, ImmutablePair from, ImmutablePair to, String fromLabel, String toLabel, Map properties) { - - Either edgeS = getEdgeByVerticies(from.getKey(), from.getValue(), to.getKey(), to.getValue(), type); - if (edgeS.isLeft()) { - - try { - Edge edge = edgeS.left().value(); - if (properties != null) { - setProperties(edge, properties); - } - - Vertex vertexOut = edge.outVertex(); - Vertex vertexIn = edge.inVertex(); - - GraphNode nodeOut = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(vertexOut), GraphNode.class); - GraphNode nodeIn = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(vertexIn), GraphNode.class); - - GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeOut, nodeIn); - if (log.isDebugEnabled()) { - log.debug("Relation was updated from [{}] to [{}] ", from, to); - } - return Either.left(newRelation); - } catch (Exception e) { - if (log.isDebugEnabled()) { - log.debug("Failed to update relation from [{}] to [{}] ", from, to, e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - } else { - if (log.isDebugEnabled()) { - log.debug("Failed to update relation from [{}] to [{}] {}", from, to, edgeS.right().value()); - } - return Either.right(edgeS.right().value()); - } - } - - /** - * - * @param relation - * @return - */ - public Either updateRelation(GraphRelation relation) { - log.debug("try to update relation from [{}] to [{}]", relation.getFrom(), relation.getTo()); - RelationEndPoint from = relation.getFrom(); - RelationEndPoint to = relation.getTo(); - ImmutablePair fromKeyId = new ImmutablePair<>(from.getIdName(), from.getIdValue()); - ImmutablePair toKeyId = new ImmutablePair<>(to.getIdName(), to.getIdValue()); - - return updateEdge(relation.getType(), fromKeyId, toKeyId, from.getLabel().getName(), to.getLabel().getName(), relation.toGraphMap()); - - } - - private Either getVertexByPropertyAndLabel(String name, Object value, String label) { - - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - @SuppressWarnings("unchecked") - Iterable vertecies = tGraph.query().has(name, value).has(GraphPropertiesDictionary.LABEL.getProperty(), label).vertices(); - - java.util.Iterator iterator = vertecies.iterator(); - if (iterator.hasNext()) { - Vertex vertex = iterator.next(); - return Either.left(vertex); - } - if (log.isDebugEnabled()) { - log.debug("No vertex in graph for key =" + name + " and value = " + value + " label = " + label); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } catch (Exception e) { - if (log.isDebugEnabled()) { - log.debug("Failed to get vertex in graph for key ={} and value = {} label = {}",name,value,label); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (log.isDebugEnabled()) { - log.debug("No vertex in graph for key ={} and value = {} label = {} error : {}",name,value,label,graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - public Either getVertexByProperty(String name, Object value) { - - Either graph = titanClient.getGraph(); - if (value == null) { - if (log.isDebugEnabled()) { - log.debug("No vertex in graph for key = {} and value = {}", name, value); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - @SuppressWarnings("unchecked") - Iterable vertecies = tGraph.query().has(name, value).vertices(); - - java.util.Iterator iterator = vertecies.iterator(); - if (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - return Either.left(vertex); - } else { - if (log.isDebugEnabled()) { - log.debug("No vertex in graph for key ={} and value = {}", name, value); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } - } catch (Exception e) { - if (log.isDebugEnabled()) { - log.debug("Failed to get vertex in graph for key = {} and value = ", name, value); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - } else { - if (log.isDebugEnabled()) { - log.debug("No vertex in graph for key = {} and value = {} error : {}", name, value, graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - public Either, TitanOperationStatus> getByCriteria(NodeTypeEnum type, Map hasProps, Map hasNotProps, Class clazz) { - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - TitanGraphQuery query = tGraph.query(); - query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), type.getName()); - - if (hasProps != null && !hasProps.isEmpty()) { - for (Map.Entry entry : hasProps.entrySet()) { - query = query.has(entry.getKey(), entry.getValue()); - } - } - if (hasNotProps != null && !hasNotProps.isEmpty()) { - for (Map.Entry entry : hasNotProps.entrySet()) { - query = query.hasNot(entry.getKey(), entry.getValue()); - } - } - 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 = getProperties(vertex); - - T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node, newProp, clazz); - result.add(element); - } - if (log.isDebugEnabled()) { - log.debug("Number of fetced nodes in graph for criteria : from type = {} and properties has = {}, properties hasNot = {} is {}", type, hasProps, hasNotProps, result.size()); - } - if (result.size() == 0) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - return Either.left(result); - } catch (Exception e) { - if (log.isDebugEnabled()) { - log.debug("Failed get by criteria for type = {}", type, e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (log.isDebugEnabled()) { - log.debug("Failed get by criteria for type ={} error : {}", type, graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - public Either, TitanOperationStatus> getByCriteria(NodeTypeEnum type, Class clazz, List> props) { - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - TitanGraphQuery query = tGraph.query(); - query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), type.getName()); - for (ImmutableTriple prop : props) { - if (QueryType.HAS.equals(prop.getLeft())) { - query = query.has(prop.getMiddle(), prop.getRight()); - } else { - query = query.hasNot(prop.getMiddle(), prop.getRight()); - } - } - 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 = 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); - } - - return Either.left(result); - } catch (Exception e) { - if (log.isDebugEnabled()) { - log.debug("Failed get by criteria for type = {}", type, e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (log.isDebugEnabled()) { - log.debug("Failed get by criteria for type ={} error : {}", type, graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - public Either, TitanOperationStatus> getByCriteria(NodeTypeEnum type, Map props, Class clazz) { - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - 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.has(entry.getKey(), entry.getValue()); - } - } - 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 = getProperties(vertex); - - T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node, newProp, clazz); - result.add(element); - } - if (log.isDebugEnabled()) { - log.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size()); - } - if (result.size() == 0) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - return Either.left(result); - } catch (Exception e) { - if (log.isDebugEnabled()) { - log.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (log.isDebugEnabled()) { - log.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - public Either, TitanOperationStatus> getByCriteriaWithPredicate(NodeTypeEnum type, Map> props, Class clazz) { - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - TitanGraphQuery query = tGraph.query(); - query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), type.getName()); - - if (props != null && !props.isEmpty()) { - TitanPredicate predicate = null; - Object object = null; - for (Map.Entry> entry : props.entrySet()) { - predicate = entry.getValue().getKey(); - object = entry.getValue().getValue(); - query = query.has(entry.getKey(), predicate, object); - } - } - 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 = 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); - } - if (log.isDebugEnabled()) { - log.debug("No nodes in graph for criteria : from type = {} and properties = {}", type, props); - } - return Either.left(result); - } catch (Exception e) { - if (log.isDebugEnabled()) { - log.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (log.isDebugEnabled()) { - log.debug("Failed get by criteria for type = {} and properties = {} error : {}", type, props, graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - public Either, TitanOperationStatus> getAll(NodeTypeEnum type, Class clazz) { - return getByCriteria(type, null, clazz); - } - - /** - * - * @param node - * @param clazz - * @return - */ - public Either updateNode(GraphNode node, Class clazz) { - log.debug("Try to update node for {}", node.getKeyValueId()); - - ImmutablePair keyValueId = node.getKeyValueId(); - Either vertexByProperty = getVertexByPropertyAndLabel(keyValueId.getKey(), keyValueId.getValue(), node.getLabel()); - - if (vertexByProperty.isLeft()) { - try { - Vertex vertex = vertexByProperty.left().value(); - - Map mapProps = node.toGraphMap(); - - for (Map.Entry entry : mapProps.entrySet()) { - if (!entry.getKey().equals(node.getUniqueIdKey())) { - vertex.property(entry.getKey(), entry.getValue()); - } - } - - Either vertexByPropertyAndLabel = getVertexByPropertyAndLabel(keyValueId.getKey(), keyValueId.getValue(), node.getLabel()); - if (vertexByPropertyAndLabel.isRight()) { - return Either.right(vertexByPropertyAndLabel.right().value()); - } else { - Map newProp = getProperties(vertexByPropertyAndLabel.left().value()); - T updateNode = GraphElementFactory.createElement(node.getLabel(), GraphElementTypeEnum.Node, newProp, clazz); - return Either.left(updateNode); - } - } catch (Exception e) { - if (log.isDebugEnabled()) { - log.debug("Failed to update node for {}", node.getKeyValueId(), e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - } else { - if (log.isDebugEnabled()) { - log.debug("Failed to update node for {} error :{}", node.getKeyValueId(), vertexByProperty.right().value()); - } - return Either.right(vertexByProperty.right().value()); - } - - } - - public TitanOperationStatus updateVertex(GraphNode node, Vertex vertex) { - log.debug("Try to update node for {}", node.getKeyValueId()); - try { - - Map mapProps = node.toGraphMap(); - - for (Map.Entry entry : mapProps.entrySet()) { - if (!entry.getKey().equals(node.getUniqueIdKey())) { - vertex.property(entry.getKey(), entry.getValue()); - } - } - - } catch (Exception e) { - if (log.isDebugEnabled()) { - log.debug("Failed to update node for {}", node.getKeyValueId(), e); - } - return TitanGraphClient.handleTitanException(e); - } - return TitanOperationStatus.OK; - - } - - /** - * - * @param node - * @param clazz - * @return - */ - public Either deleteNode(GraphNode node, Class clazz) { - log.debug("Try to delete node for {}", node.getKeyValueId()); - ImmutablePair keyValueId = node.getKeyValueId(); - return deleteNode(keyValueId.getKey(), keyValueId.getValue(), clazz); - } - - /** - * - * @param keyName - * @param keyValue - * @param clazz - * @return - */ - public Either deleteNode(String keyName, Object keyValue, Class clazz) { - Either vertexByProperty = getVertexByProperty(keyName, keyValue); - - if (vertexByProperty.isLeft()) { - try { - Vertex vertex = vertexByProperty.left().value(); - - Map properties = getProperties(vertex); - if (properties != null) { - String label = (String) properties.get(GraphPropertiesDictionary.LABEL.getProperty()); - - T node = GraphElementFactory.createElement(label, GraphElementTypeEnum.Node, properties, clazz); - if (node != null) { - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - TitanGraph tGraph = graph.left().value(); - vertex.remove(); - } else { - return Either.right(graph.right().value()); - } - return Either.left(node); - } else { - if (log.isDebugEnabled()) { - log.debug("Failed to delete node for {} = {} Missing label property on node", keyName, keyValue); - } - return Either.right(TitanOperationStatus.MISSING_NODE_LABEL); - } - } else { - if (log.isDebugEnabled()) { - log.debug("Failed to delete node for {} = {} Missing label property on node", keyName, keyValue); - } - return Either.right(TitanOperationStatus.MISSING_NODE_LABEL); - } - } catch (Exception e) { - if (log.isDebugEnabled()) { - log.debug("Failed to delete node for {} = {}", keyName, keyValue, e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - return Either.right(vertexByProperty.right().value()); - } - } - - public Either deleteRelation(GraphRelation relation) { - log.debug("try to delete relation from [{}] to [{}]", relation.getFrom(), relation.getTo()); - RelationEndPoint from = relation.getFrom(); - RelationEndPoint to = relation.getTo(); - ImmutablePair fromKeyId = new ImmutablePair<>(from.getIdName(), from.getIdValue()); - ImmutablePair toKeyId = new ImmutablePair<>(to.getIdName(), to.getIdValue()); - - return deleteEdge(relation.getType(), fromKeyId, toKeyId, from.getLabel().getName(), to.getLabel().getName()); - - } - - public Either isRelationExist(GraphNode from, GraphNode to, GraphEdgeLabels edgeLabel) { - return getEdgeByNodes(from, to, edgeLabel) - .left() - .map(edge -> true) - .right() - .bind(err -> err == TitanOperationStatus.NOT_FOUND ? Either.left(false): Either.right(err)); - } - - public Either deleteRelation(GraphNode from, GraphNode to, GraphEdgeLabels label) { - log.debug("try to delete relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); - return deleteEdge(label.getProperty(), from.getKeyValueId(), to.getKeyValueId(), from.getLabel(), to.getLabel()); - } - - private Either deleteEdge(String type, ImmutablePair fromKeyId, ImmutablePair toKeyId, String fromLabel, String toLabel) { - Either edgeS = getEdgeByVerticies(fromKeyId.getKey(), fromKeyId.getValue(), toKeyId.getKey(), toKeyId.getValue(), type); - if (edgeS.isLeft()) { - try { - Edge edge = edgeS.left().value(); - - Vertex vertexOut = edge.outVertex(); - Vertex vertexIn = edge.inVertex(); - - GraphNode nodeOut = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(vertexOut), GraphNode.class); - GraphNode nodeIn = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(vertexIn), GraphNode.class); - - GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeOut, nodeIn); - - Either graph = titanClient.getGraph(); - - if (graph.isLeft()) { - edge.remove(); - ; - } else { - if (log.isDebugEnabled()) { - log.debug("Failed to delete relation {} from {} to {} error : {}",type,fromKeyId,toKeyId,graph.right().value()); - } - return Either.right(graph.right().value()); - } - return Either.left(newRelation); - } catch (Exception e) { - if (log.isDebugEnabled()) { - log.debug("Failed to delete relation {} from {} to {}", type, fromKeyId, toKeyId, e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - } else { - if (log.isDebugEnabled()) { - log.debug("Failed to delete relation {} from {} to {} error : {}", type, fromKeyId, toKeyId, edgeS.right().value()); - } - return Either.right(edgeS.right().value()); - } - } - - public void setTitanGraphClient(TitanGraphClient titanGraphClient) { - this.titanClient = titanGraphClient; - } - - public Either deleteIncomingRelation(GraphRelation relation) { - - RelationEndPoint to = relation.getTo(); - ImmutablePair toKeyId = new ImmutablePair<>(to.getIdName(), to.getIdValue()); - - return deleteIncomingEdge(relation.getType(), toKeyId); - - } - - private Either deleteIncomingEdge(String type, ImmutablePair toKeyId) { - - Either graph = titanClient.getGraph(); - - if (graph.isLeft()) { - Either rootVertexResult = getVertexByProperty(toKeyId.getKey(), toKeyId.getValue()); - if (rootVertexResult.isLeft()) { - Vertex rootVertex = rootVertexResult.left().value(); - Iterator edgesIterator = rootVertex.edges(Direction.IN, type); - if (edgesIterator != null) { - - Edge edge = null; - - if (edgesIterator.hasNext()) { - edge = edgesIterator.next(); - if (edgesIterator.hasNext()) { - return Either.right(TitanOperationStatus.MULTIPLE_EDGES_WITH_SAME_LABEL); - } - } else { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - log.debug("Find the tail vertex of the edge of type {} to vertex {}", type, toKeyId); - Vertex vertexOut = edge.outVertex(); - String fromLabel = vertexOut.value(GraphPropertiesDictionary.LABEL.getProperty()); - String toLabel = rootVertex.value(GraphPropertiesDictionary.LABEL.getProperty()); - log.debug("The label of the outgoing vertex is {}", fromLabel); - GraphNode nodeOut = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(vertexOut), GraphNode.class); - - GraphNode nodeIn = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(rootVertex), GraphNode.class); - - GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeOut, nodeIn); - - edge.remove(); - - return Either.left(newRelation); - - } else { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - } else { - return Either.right(graph.right().value()); - } - - } else { - return Either.right(graph.right().value()); - } - - } - - public Either deleteOutgoingRelation(GraphRelation relation) { - - RelationEndPoint from = relation.getFrom(); - ImmutablePair fromKeyId = new ImmutablePair<>(from.getIdName(), from.getIdValue()); - - return deleteOutgoingEdge(relation.getType(), fromKeyId); - - } - - private Either deleteOutgoingEdge(String type, ImmutablePair toKeyId) { - - Either graph = titanClient.getGraph(); - - if (graph.isLeft()) { - Either rootVertexResult = getVertexByProperty(toKeyId.getKey(), toKeyId.getValue()); - if (rootVertexResult.isLeft()) { - Vertex rootVertex = rootVertexResult.left().value(); - Iterator edgesIterator = rootVertex.edges(Direction.OUT, type); - if (edgesIterator != null) { - - Edge edge = null; - - if (edgesIterator.hasNext()) { - edge = edgesIterator.next(); - if (edgesIterator.hasNext()) { - return Either.right(TitanOperationStatus.MULTIPLE_EDGES_WITH_SAME_LABEL); - } - } else { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - log.debug("Find the tail vertex of the edge of type {} to vertex ", type, toKeyId); - Vertex vertexIn = edge.inVertex(); - String toLabel = vertexIn.value(GraphPropertiesDictionary.LABEL.getProperty()); - String fromLabel = rootVertex.value(GraphPropertiesDictionary.LABEL.getProperty()); - log.debug("The label of the tail vertex is {}", toLabel); - GraphNode nodeFrom = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(rootVertex), GraphNode.class); - - GraphNode nodeTo = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(vertexIn), GraphNode.class); - - GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeFrom, nodeTo); - - edge.remove(); - - return Either.left(newRelation); - - } else { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - } else { - return Either.right(graph.right().value()); - } - - } else { - return Either.right(graph.right().value()); - } - } - - /** - * - * @param id - * @return - */ - - public TitanOperationStatus lockElement(String id, NodeTypeEnum type) { - - StringBuffer lockId = new StringBuffer(LOCK_NODE_PREFIX); - lockId.append(type.getName()).append("_").append(id); - return lockNode(lockId.toString()); - } - - public TitanOperationStatus lockElement(GraphNode node) { - - StringBuffer lockId = createLockElementId(node); - - return lockNode(lockId.toString()); - } - - private TitanOperationStatus lockNode(String lockId) { - TitanOperationStatus status = TitanOperationStatus.OK; - - GraphNodeLock lockNode = new GraphNodeLock(lockId); - - Either lockNodeNew = createNode(lockNode, GraphNodeLock.class); - if (lockNodeNew.isLeft()) { - log.debug("before commit, Lock node created for {}", lockId); - return titanClient.commit(); - } else { - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - TitanGraph tGraph = graph.left().value(); - Either vertex = getVertexByProperty(lockNode.getUniqueIdKey(), lockNode.getUniqueId()); - if (vertex.isLeft()) { - status = relockNode(lockNode, lockNodeNew, tGraph, vertex); - } else { - status = vertex.right().value(); - } - } else { - status = graph.right().value(); - } - } - return status; - } - - private TitanOperationStatus relockNode(GraphNodeLock lockNode, Either lockNodeNew, TitanGraph tGraph, Either vertex) { - TitanOperationStatus status = TitanOperationStatus.OK; - Long time = vertex.left().value().value(GraphPropertiesDictionary.CREATION_DATE.getProperty()); - Long lockTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanLockTimeout(); - if (time + lockTimeout * 1000 < System.currentTimeMillis()) { - log.debug("Found not released lock node with id {}", lockNode.getUniqueId()); - vertex.left().value().remove(); - lockNodeNew = createNode(lockNode, GraphNodeLock.class); - if (lockNodeNew.isLeft()) { - log.debug("Lock node created for {}", lockNode.getUniqueIdKey()); - return titanClient.commit(); - } else { - log.debug("Failed Lock node for {} . Commit transacton for deleted previous vertex .", lockNode.getUniqueIdKey()); - titanClient.commit(); - status = checkLockError(lockNode.getUniqueIdKey(), lockNodeNew); - } - } else { - log.debug("Failed Lock node for {} rollback transacton", lockNode.getUniqueIdKey()); - titanClient.rollback(); - status = checkLockError(lockNode.getUniqueIdKey(), lockNodeNew); - } - return status; - } - - public Either>, TitanOperationStatus> getChildrenNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz, boolean withEdges) { - - List> immutablePairs = new ArrayList<>(); - - Either graphRes = titanClient.getGraph(); - if (graphRes.isRight()) { - log.error(FAILED_TO_RETRIEVE_GRAPH_STATUS_IS, graphRes); - return Either.right(graphRes.right().value()); - } - - TitanGraph titanGraph = graphRes.left().value(); - @SuppressWarnings("unchecked") - Iterable vertices = titanGraph.query().has(key, uniqueId).vertices(); - if (vertices == null || !vertices.iterator().hasNext()) { - return Either.right(TitanOperationStatus.INVALID_ID); - } - - Vertex rootVertex = vertices.iterator().next(); - - Iterator edgesCreatorIterator = rootVertex.edges(Direction.OUT, edgeType.getProperty()); - if (edgesCreatorIterator != null) { - while (edgesCreatorIterator.hasNext()) { - Edge edge = edgesCreatorIterator.next(); - GraphEdge graphEdge = null; - - if (withEdges) { - Map edgeProps = getProperties(edge); - GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label()); - graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps); - } - - Vertex outgoingVertex = edge.inVertex(); - Map properties = getProperties(outgoingVertex); - T data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz); - - ImmutablePair immutablePair = new ImmutablePair<>(clazz.cast(data), graphEdge); - immutablePairs.add(immutablePair); - } - } - - if (immutablePairs.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - return Either.left(immutablePairs); - - } - - public Either>, TitanOperationStatus> getChildrenVertecies(String key, String uniqueId, GraphEdgeLabels edgeType) { - - List> immutablePairs = new ArrayList<>(); - - Either graphRes = titanClient.getGraph(); - if (graphRes.isRight()) { - log.error(FAILED_TO_RETRIEVE_GRAPH_STATUS_IS, graphRes); - return Either.right(graphRes.right().value()); - } - - TitanGraph titanGraph = graphRes.left().value(); - @SuppressWarnings("unchecked") - Iterable vertices = titanGraph.query().has(key, uniqueId).vertices(); - if (vertices == null || !vertices.iterator().hasNext()) { - return Either.right(TitanOperationStatus.INVALID_ID); - } - - Vertex rootVertex = vertices.iterator().next(); - - Iterator edgesCreatorIterator = rootVertex.edges(Direction.OUT, edgeType.getProperty()); - if (edgesCreatorIterator != null) { - while (edgesCreatorIterator.hasNext()) { - Edge edge = edgesCreatorIterator.next(); - TitanVertex vertex = (TitanVertex) edge.inVertex(); - - ImmutablePair immutablePair = new ImmutablePair<>(vertex, edge); - immutablePairs.add(immutablePair); - } - } - if (immutablePairs.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - return Either.left(immutablePairs); - - } - - public Either>, TitanOperationStatus> getChildrenNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz) { - return this.getChildrenNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz, true); - } - - private TitanOperationStatus checkLockError(String lockId, Either lockNodeNew) { - TitanOperationStatus status; - TitanOperationStatus error = lockNodeNew.right().value(); - log.debug("Failed to Lock node for {} error = {}", lockId, error); - if (error.equals(TitanOperationStatus.TITAN_SCHEMA_VIOLATION) || error.equals(TitanOperationStatus.ILLEGAL_ARGUMENT)) { - status = TitanOperationStatus.ALREADY_LOCKED; - } else { - status = error; - } - return status; - } - - /** - * - * @param node - * @return - */ - public TitanOperationStatus releaseElement(GraphNode node) { - StringBuffer lockId = createLockElementId(node); - - return unlockNode(lockId); - } - - private TitanOperationStatus unlockNode(StringBuffer lockId) { - GraphNodeLock lockNode = new GraphNodeLock(lockId.toString()); - - Either lockNodeNew = deleteNode(lockNode, GraphNodeLock.class); - if (lockNodeNew.isLeft()) { - log.debug("Lock node released for lock id = {}", lockId); - return titanClient.commit(); - } else { - titanClient.rollback(); - TitanOperationStatus error = lockNodeNew.right().value(); - log.debug("Failed to Release node for lock id {} error = {}", lockId, error); - return error; - } - } - - public TitanOperationStatus releaseElement(String id, NodeTypeEnum type) { - StringBuffer lockId = new StringBuffer(LOCK_NODE_PREFIX); - lockId.append(type.getName()).append("_").append(id); - return unlockNode(lockId); - } - - private StringBuffer createLockElementId(GraphNode node) { - StringBuffer lockId = new StringBuffer(LOCK_NODE_PREFIX); - lockId.append(node.getLabel()).append("_").append(node.getUniqueId()); - return lockId; - } - - public Either, TitanOperationStatus> getChild(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz) { - - Either>, TitanOperationStatus> childrenNodes = getChildrenNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz); - - if (childrenNodes.isRight()) { - return Either.right(childrenNodes.right().value()); - } - - List> value = childrenNodes.left().value(); - - if (value.size() > 1) { - return Either.right(TitanOperationStatus.MULTIPLE_CHILDS_WITH_SAME_EDGE); - } - - return Either.left(value.get(0)); - - } - - public ImmutablePair getChildVertex(TitanVertex vertex, GraphEdgeLabels edgeType) { - - ImmutablePair pair = null; - Iterator edges = vertex.edges(Direction.OUT, edgeType.getProperty()); - if (edges.hasNext()) { - // get only first edge - Edge edge = edges.next(); - pair = new ImmutablePair<>((TitanVertex) edge.inVertex(), edge); - } - return pair; - } - - public Either>, TitanOperationStatus> getParentNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz) { - - List> immutablePairs = new ArrayList<>(); - - T data = null; - GraphEdge graphEdge = null; - - Either graphRes = titanClient.getGraph(); - if (graphRes.isRight()) { - log.error(FAILED_TO_RETRIEVE_GRAPH_STATUS_IS, graphRes); - return Either.right(graphRes.right().value()); - } - - TitanGraph titanGraph = graphRes.left().value(); - @SuppressWarnings("unchecked") - Iterable vertices = titanGraph.query().has(key, uniqueId).vertices(); - if (vertices == null || !vertices.iterator().hasNext()) { - return Either.right(TitanOperationStatus.INVALID_ID); - } - - Vertex rootVertex = vertices.iterator().next(); - - Iterator edgesCreatorIterator = rootVertex.edges(Direction.IN, edgeType.name()); - if (edgesCreatorIterator != null) { - while (edgesCreatorIterator.hasNext()) { - Edge edge = edgesCreatorIterator.next(); - Map edgeProps = getProperties(edge); - GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label()); - graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps); - - Vertex outgoingVertex = edge.outVertex(); - Map properties = getProperties(outgoingVertex); - data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz); - - ImmutablePair immutablePair = new ImmutablePair<>(clazz.cast(data), graphEdge); - immutablePairs.add(immutablePair); - } - } - - if (immutablePairs.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - return Either.left(immutablePairs); - - } - - public Either, TitanOperationStatus> getParentNode(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz) { - - Either>, TitanOperationStatus> parentNodesRes = this.getParentNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz); - - if (parentNodesRes.isRight()) { - log.debug("failed to get edge key:{} uniqueId:{} edgeType {} nodeTypeEnum: {}, reason:{}", key, uniqueId, edgeType, nodeTypeEnum, parentNodesRes.right().value()); - return Either.right(parentNodesRes.right().value()); - } - - List> value = parentNodesRes.left().value(); - - if (value.size() > 1) { - return Either.right(TitanOperationStatus.MULTIPLE_CHILDS_WITH_SAME_EDGE); - } - - return Either.left(value.get(0)); - } - - public Either, TitanOperationStatus> getChildByEdgeCriteria(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz, Map edgeProperties) { - - Either outgoingEdgeByCriteria = getOutgoingEdgeByCriteria(key, uniqueId, edgeType, edgeProperties); - if (outgoingEdgeByCriteria.isRight()) { - TitanOperationStatus status = outgoingEdgeByCriteria.right().value(); - log.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}" + uniqueId, edgeType, edgeProperties); - return Either.right(status); - } - - Edge edge = outgoingEdgeByCriteria.left().value(); - Map edgeProps = getProperties(edge); - GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label()); - GraphEdge graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps); - - Vertex outgoingVertex = edge.inVertex(); - Map properties = getProperties(outgoingVertex); - T data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz); - - ImmutablePair immutablePair = new ImmutablePair<>(clazz.cast(data), graphEdge); - - return Either.left(immutablePair); - } - - public Either, TitanOperationStatus> getChildByEdgeCriteria(TitanVertex vertex, GraphEdgeLabels edgeType, Map edgeProperties) { - - Either outgoingEdgeByCriteria = getOutgoingEdgeByCriteria(vertex, edgeType, edgeProperties); - if (outgoingEdgeByCriteria.isRight()) { - TitanOperationStatus status = outgoingEdgeByCriteria.right().value(); - log.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}", vertex, edgeType, edgeProperties); - return Either.right(status); - } - Edge edge = outgoingEdgeByCriteria.left().value(); - - TitanVertex outgoingVertex = (TitanVertex) edge.inVertex(); - - ImmutablePair immutablePair = new ImmutablePair<>(outgoingVertex, edge); - - return Either.left(immutablePair); - } - - public Either getOutgoingEdgeByCriteria(String key, String value, GraphEdgeLabels label, Map props) { - - Either vertexFrom = getVertexByProperty(key, value); - if (vertexFrom.isRight()) { - TitanOperationStatus status = vertexFrom.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - return Either.right(TitanOperationStatus.INVALID_ID); - } - return Either.right(status); - } - - return getOutgoingEdgeByCriteria(vertexFrom.left().value(), label, props); - } - - public Either getOutgoingEdgeByCriteria(TitanVertex vertex, GraphEdgeLabels label, Map props) { - - TitanVertexQuery query = vertex.query(); - query = query.direction(Direction.OUT).labels(label.getProperty()); - - if (props != null && !props.isEmpty()) { - for (Map.Entry entry : props.entrySet()) { - query = query.has(entry.getKey(), entry.getValue()); - } - } - Edge matchingEdge = null; - Iterable edges = query.edges(); - if (edges == null) { - log.debug(NO_EDGES_IN_GRAPH_FOR_CRITERIA); - return Either.right(TitanOperationStatus.NOT_FOUND); - } - Iterator eIter = edges.iterator(); - if (eIter.hasNext()) { - matchingEdge = eIter.next(); - } - - if (matchingEdge == null) { - log.debug(NO_EDGES_IN_GRAPH_FOR_CRITERIA); - return Either.right(TitanOperationStatus.NOT_FOUND); - } - return Either.left(matchingEdge); - } - - public Either>, TitanOperationStatus> deleteChildrenNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz) { - - List> result = new ArrayList<>(); - - Either>, TitanOperationStatus> childrenNodesRes = getChildrenNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz); - - if (childrenNodesRes.isRight()) { - TitanOperationStatus status = childrenNodesRes.right().value(); - return Either.right(status); - } - - List> list = childrenNodesRes.left().value(); - for (ImmutablePair pair : list) { - T node = pair.getKey(); - Either deleteNodeRes = this.deleteNode(node, clazz); - if (deleteNodeRes.isRight()) { - TitanOperationStatus status = deleteNodeRes.right().value(); - log.error("Failed to delete node {} . status is {}", node, status); - return Either.right(status); - } - ImmutablePair deletedPair = new ImmutablePair<>(node, pair.getValue()); - result.add(deletedPair); - } - - return Either.left(result); - - } - - public void setProperties(Element element, Map properties) { - - if (properties != null && !properties.isEmpty()) { - - Object[] propertyKeyValues = new Object[properties.size() * 2]; - int i = 0; - for (Entry entry : properties.entrySet()) { - propertyKeyValues[i++] = entry.getKey(); - propertyKeyValues[i++] = entry.getValue(); - } - - ElementHelper.attachProperties(element, propertyKeyValues); - - } - - } - - public Map getProperties(Element element) { - - Map result = new HashMap<>(); - - if (element != null && element.keys() != null && element.keys().size() > 0) { - Map propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()])); - - for (Entry entry : propertyMap.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue().value(); - - result.put(key, value); - } - } - return result; - } - - public Object getProperty(TitanVertex vertex, String key) { - PropertyKey propertyKey = titanClient.getGraph().left().value().getPropertyKey(key); - return vertex.valueOrNull(propertyKey); - } - - public Object getProperty(Edge edge, String key) { - Object value = null; - Property property = edge.property(key); - if (property != null) { - return property.orElse(null); - } - return value; - } - - public Either>, TitanOperationStatus> getChildrenByEdgeCriteria(Vertex vertex, String vertexUniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz, - Map edgeProperties) { - - List> result = new ArrayList<>(); - - Either, TitanOperationStatus> outgoingEdgeByCriteria = getOutgoingEdgesByCriteria(vertex, edgeType, edgeProperties); - if (outgoingEdgeByCriteria.isRight()) { - TitanOperationStatus status = outgoingEdgeByCriteria.right().value(); - log.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}", vertexUniqueId, edgeType, edgeProperties); - return Either.right(status); - } - - List edges = outgoingEdgeByCriteria.left().value(); - if (edges != null) { - for (Edge edge : edges) { - Map edgeProps = getProperties(edge); - GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label()); - GraphEdge graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps); - - Vertex outgoingVertex = edge.inVertex(); - Map properties = getProperties(outgoingVertex); - T data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz); - - ImmutablePair immutablePair = new ImmutablePair<>(clazz.cast(data), graphEdge); - result.add(immutablePair); - } - } - - return Either.left(result); - } - - public Either, TitanOperationStatus> getOutgoingEdgesByCriteria(Vertex vertexFrom, GraphEdgeLabels label, Map props) { - - List edgesResult = new ArrayList<>(); - - TitanVertex titanVertex = (TitanVertex) vertexFrom; - TitanVertexQuery query = titanVertex.query(); - - query = query.direction(Direction.OUT).labels(label.getProperty()); - - if (props != null && !props.isEmpty()) { - for (Map.Entry entry : props.entrySet()) { - query = query.has(entry.getKey(), entry.getValue()); - } - } - - Iterable edges = query.edges(); - Iterator eIter = edges.iterator(); - if (edges == null || !eIter.hasNext()) { - log.debug("No edges found in graph for criteria (label = {} properties={})", label.getProperty(), props); - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - while (eIter.hasNext()) { - Edge edge = eIter.next(); - edgesResult.add(edge); - } - - if (edgesResult.isEmpty()) { - log.debug("No edges found in graph for criteria (label = {} properties={})", label.getProperty(), props); - return Either.right(TitanOperationStatus.NOT_FOUND); - } - return Either.left(edgesResult); - - } - -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java deleted file mode 100644 index 9d5ff9d226..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java +++ /dev/null @@ -1,408 +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.dao.titan; - -import com.thinkaurelius.titan.core.*; -import com.thinkaurelius.titan.core.schema.ConsistencyModifier; -import com.thinkaurelius.titan.core.schema.TitanGraphIndex; -import com.thinkaurelius.titan.core.schema.TitanManagement; -import com.thinkaurelius.titan.core.util.TitanCleanup; -import com.thinkaurelius.titan.diskstorage.ResourceUnavailableException; -import com.thinkaurelius.titan.diskstorage.locking.PermanentLockingException; -import com.thinkaurelius.titan.graphdb.database.idassigner.IDPoolExhaustedException; -import fj.data.Either; -import org.apache.commons.configuration.BaseConfiguration; -import org.apache.tinkerpop.gremlin.structure.T; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.DAOTitanStrategy; -import org.openecomp.sdc.be.dao.TitanClientStrategy; -import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.concurrent.*; - - -@Component("titan-client") -public class TitanGraphClient { - private static Logger logger = LoggerFactory.getLogger(TitanGraphClient.class.getName()); - private static Logger healthLogger = LoggerFactory.getLogger("titan.healthcheck"); - - private static final String HEALTH_CHECK = GraphPropertiesDictionary.HEALTH_CHECK.getProperty(); - private static final String OK = "GOOD"; - - public TitanGraphClient() { - } - - private class HealthCheckTask implements Callable { - @Override - public Vertex call() { - - TitanVertex v = (TitanVertex) graph.query().has(HEALTH_CHECK, OK).vertices().iterator().next(); - TitanVertexProperty property = v.property("healthcheck", OK + "_" + System.currentTimeMillis()); - healthLogger.trace("Health Check Node Found...{}", v.property(HEALTH_CHECK)); - graph.tx().commit(); - - return v; - } - } - - private class HealthCheckScheduledTask implements Runnable { - @Override - public void run() { - healthLogger.trace("Executing TITAN Health Check Task - Start"); - boolean healthStatus = isGraphOpen(); - healthLogger.trace("Executing TITAN Health Check Task - Status = {}", healthStatus); - if (healthStatus != lastHealthState) { - logger.trace("TITAN Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus); - lastHealthState = healthStatus; - logAlarm(); - } - } - } - - private class ReconnectTask implements Runnable { - @Override - public void run() { - logger.trace("Trying to reconnect to Titan..."); - if (graph == null) { - createGraph(titanCfgFile); - } - } - } - - private TitanGraph graph; - - // Health Check Variables - - /** - * This executor will execute the health check task on a callable task that can be executed with a timeout. - */ - ExecutorService healthCheckExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "Titan-Health-Check-Thread"); - } - }); - private long healthCheckReadTimeout = 2; - HealthCheckTask healthCallableTask = new HealthCheckTask(); - HealthCheckScheduledTask healthCheckScheduledTask = new HealthCheckScheduledTask(); - boolean lastHealthState = false; - - // Reconnection variables - private ScheduledExecutorService reconnectScheduler = null; - private ScheduledExecutorService healthCheckScheduler = null; - private Runnable reconnectTask = null; - private long reconnectInterval = 3; - @SuppressWarnings("rawtypes") - private Future reconnectFuture; - - private String titanCfgFile = null; - TitanClientStrategy titanClientStrategy; - - public TitanGraphClient(TitanClientStrategy titanClientStrategy) { - super(); - this.titanClientStrategy = titanClientStrategy; - - // Initialize a single threaded scheduler for health-check - this.healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "Titan-Health-Check-Task"); - } - }); - - healthCheckReadTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanHealthCheckReadTimeout(2); - reconnectInterval = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanReconnectIntervalInSeconds(3); - - logger.info("** TitanGraphClient created"); - } - - @PostConstruct - public TitanOperationStatus createGraph() { - - logger.info("** createGraph started **"); - - if (ConfigurationManager.getConfigurationManager().getConfiguration().getTitanInMemoryGraph()) { - BaseConfiguration conf = new BaseConfiguration(); - conf.setProperty("storage.backend", "inmemory"); - graph = TitanFactory.open(conf); - createTitanSchema(); - logger.info("** in memory graph created"); - return TitanOperationStatus.OK; - } else { - this.titanCfgFile = titanClientStrategy.getConfigFile(); - if (titanCfgFile == null || titanCfgFile.isEmpty()) { - titanCfgFile = "config/titan.properties"; - } - - // yavivi - // In case connection failed on init time, schedule a reconnect task - // in the BG - TitanOperationStatus status = createGraph(titanCfgFile); - logger.debug("Create Titan graph status {}", status); - if (status != TitanOperationStatus.OK) { - this.startReconnectTask(); - } - - return status; - } - } - - private void startHealthCheckTask() { - this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS); - } - - /** - * This method will be invoked ONLY on init time in case Titan storage is down. - */ - private void startReconnectTask() { - this.reconnectTask = new ReconnectTask(); - // Initialize a single threaded scheduler - this.reconnectScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "Titan-Reconnect-Task"); - } - }); - - logger.info("Scheduling reconnect task {} with interval of {} seconds", reconnectTask, reconnectInterval); - reconnectFuture = this.reconnectScheduler.scheduleAtFixedRate(this.reconnectTask, 0, this.reconnectInterval, TimeUnit.SECONDS); - } - - public void cleanupGraph() { - if (graph != null) { - // graph.shutdown(); - graph.close(); - TitanCleanup.clear(graph); - } - } - - private boolean graphInitialized(){ - TitanManagement graphMgmt = graph.openManagement(); - return graphMgmt.containsPropertyKey(HEALTH_CHECK) && graphMgmt.containsGraphIndex(HEALTH_CHECK); - } - - - public TitanOperationStatus createGraph(String titanCfgFile) { - logger.info("** open graph with {} started", titanCfgFile); - try { - logger.info("openGraph : try to load file {}", titanCfgFile); - graph = TitanFactory.open(titanCfgFile); - if (graph.isClosed() || !graphInitialized()) { - logger.error("titan graph was not initialized"); - return TitanOperationStatus.NOT_CREATED; - } - - } catch (Exception e) { - this.graph = null; - logger.info("createGraph : failed to open Titan graph with configuration file: {}", titanCfgFile); - logger.debug("createGraph : failed with exception.", e); - return TitanOperationStatus.NOT_CONNECTED; - } - - logger.info("** Titan graph created "); - - // Do some post creation actions - this.onGraphOpened(); - - return TitanOperationStatus.OK; - } - - private void onGraphOpened() { - // if a reconnect task is running, cancel it. - if (this.reconnectFuture != null) { - logger.info("** Cancelling Titan reconnect task"); - reconnectFuture.cancel(true); - } - - // create health-check node - if (!graph.query().has(HEALTH_CHECK, OK).vertices().iterator().hasNext()) { - logger.trace("Healthcheck Singleton node does not exist, Creating healthcheck node..."); - Vertex healthCheckNode = graph.addVertex(); - healthCheckNode.property(HEALTH_CHECK, OK); - logger.trace("Healthcheck node created successfully. ID={}", healthCheckNode.property(T.id.getAccessor())); - graph.tx().commit(); - } else { - logger.trace("Skipping Healthcheck Singleton node creation. Already exist..."); - } - this.startHealthCheckTask(); - } - - - public Either getGraph() { - if (graph != null) { - return Either.left(graph); - } else { - return Either.right(TitanOperationStatus.NOT_CREATED); - } - } - - public TitanOperationStatus commit() { - if (graph != null) { - try { - graph.tx().commit(); - return TitanOperationStatus.OK; - } catch (Exception e) { - return handleTitanException(e); - } - } else { - return TitanOperationStatus.NOT_CREATED; - } - } - - public TitanOperationStatus rollback() { - if (graph != null) { - try { - // graph.rollback(); - graph.tx().rollback(); - return TitanOperationStatus.OK; - } catch (Exception e) { - return handleTitanException(e); - } - } else { - return TitanOperationStatus.NOT_CREATED; - } - } - - public static TitanOperationStatus handleTitanException(Exception e) { - if (e instanceof TitanConfigurationException) { - return TitanOperationStatus.TITAN_CONFIGURATION; - } - if (e instanceof SchemaViolationException) { - return TitanOperationStatus.TITAN_SCHEMA_VIOLATION; - } - if (e instanceof PermanentLockingException) { - return TitanOperationStatus.TITAN_SCHEMA_VIOLATION; - } - if (e instanceof IDPoolExhaustedException) { - return TitanOperationStatus.GENERAL_ERROR; - } - if (e instanceof InvalidElementException) { - return TitanOperationStatus.INVALID_ELEMENT; - } - if (e instanceof InvalidIDException) { - return TitanOperationStatus.INVALID_ID; - } - if (e instanceof QueryException) { - return TitanOperationStatus.INVALID_QUERY; - } - if (e instanceof ResourceUnavailableException) { - return TitanOperationStatus.RESOURCE_UNAVAILABLE; - } - if (e instanceof IllegalArgumentException) { - // TODO check the error message?? - return TitanOperationStatus.ILLEGAL_ARGUMENT; - } - - return TitanOperationStatus.GENERAL_ERROR; - } - - public boolean getHealth() { - return this.lastHealthState; - } - - private boolean isGraphOpen() { - healthLogger.trace("Invoking Titan health check ..."); - Vertex v = null; - if (graph != null) { - try { - Future future = healthCheckExecutor.submit(healthCallableTask); - v = future.get(this.healthCheckReadTimeout, TimeUnit.SECONDS); - healthLogger.trace("Health Check Node Found... {}", v.property(HEALTH_CHECK)); - graph.tx().commit(); - } catch (Exception e) { - String message = e.getMessage(); - if (message == null) { - message = e.getClass().getName(); - } - logger.error("Titan Health Check Failed. {}", message); - return false; - } - return true; - } else { - return false; - } - } - - - public static void main(String[] args) throws InterruptedException { - TitanGraphClient client = new TitanGraphClient(new DAOTitanStrategy()); - client.createGraph(); - - while (true) { - boolean health = client.isGraphOpen(); - System.err.println("health=" + health); - Thread.sleep(2000); - } - - } - - - private static final String TITAN_HEALTH_CHECK_STR = "titanHealthCheck"; - - private void logAlarm() { - if (lastHealthState) { - BeEcompErrorManager.getInstance().logBeHealthCheckTitanRecovery(TITAN_HEALTH_CHECK_STR); - } else { - BeEcompErrorManager.getInstance().logBeHealthCheckTitanError(TITAN_HEALTH_CHECK_STR); - } - } - - private void createTitanSchema() { - - TitanManagement graphMgt = graph.openManagement(); - TitanGraphIndex index = null; - for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) { - PropertyKey propKey = null; - if (!graphMgt.containsPropertyKey(prop.getProperty())) { - Class clazz = prop.getClazz(); - if (!clazz.isAssignableFrom(ArrayList.class) && !clazz.isAssignableFrom(HashMap.class)) { - propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); - } - } else { - propKey = graphMgt.getPropertyKey(prop.getProperty()); - } - if (prop.isIndexed()) { - if (!graphMgt.containsGraphIndex(prop.getProperty())) { - if (prop.isUnique()) { - index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex(); - // Ensures only one name per vertex - graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); - // Ensures name uniqueness in the graph - graphMgt.setConsistency(index, ConsistencyModifier.LOCK); - - } else { - graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex(); - } - } - } - } - graphMgt.commit(); - } - -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanOperationStatus.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanOperationStatus.java deleted file mode 100644 index dc9ed02fca..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanOperationStatus.java +++ /dev/null @@ -1,26 +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.dao.titan; - -public enum TitanOperationStatus { - OK, NOT_CONNECTED, NOT_CREATED, INDEX_CANNOT_BE_CHANGED, NOT_FOUND, MISSING_UNIQUE_ID, MISSING_NODE_LABEL, MULTIPLE_EDGES_WITH_SAME_LABEL, CANNOT_DELETE_NON_LEAF_NODE, MULTIPLE_NODES_WITH_SAME_ID, GRAPH_IS_NOT_AVAILABLE, TITAN_CONFIGURATION, TITAN_SCHEMA_VIOLATION, INVALID_ELEMENT, INVALID_QUERY, INVALID_ID, RESOURCE_UNAVAILABLE, ILLEGAL_ARGUMENT, ALREADY_LOCKED, ALREADY_EXIST, MULTIPLE_CHILDS_WITH_SAME_EDGE, GENERAL_ERROR, MATCH_NOT_FOUND, INVALID_TYPE, PROPERTY_NAME_ALREADY_EXISTS, INVALID_PROPERTY, - -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanUtils.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanUtils.java deleted file mode 100644 index 163ef807fb..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanUtils.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.openecomp.sdc.be.dao.titan; - -import com.thinkaurelius.titan.graphdb.query.TitanPredicate; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -import static com.thinkaurelius.titan.core.attribute.Contain.NOT_IN; -import static java.util.Collections.emptyMap; -import static org.apache.commons.collections.CollectionUtils.isEmpty; - -public class TitanUtils { - - private TitanUtils() { - } - - public static Map> buildNotInPredicate(String propKey, Collection notInCollection) { - if (isEmpty(notInCollection)) { - return emptyMap(); - } - Map> predicateCriteria = new HashMap<>(); - predicateCriteria.put(propKey, new HashMap.SimpleEntry<>(NOT_IN, notInCollection)); - return predicateCriteria; - } -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/transactions/SimpleTitanTransactionManager.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/transactions/SimpleTitanTransactionManager.java deleted file mode 100644 index 2e5b7ea84c..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/transactions/SimpleTitanTransactionManager.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.openecomp.sdc.be.dao.titan.transactions; - -import com.thinkaurelius.titan.core.TitanException; -import com.thinkaurelius.titan.core.TitanGraph; -import org.openecomp.sdc.be.dao.titan.TitanGraphClient; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.springframework.stereotype.Component; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.TransactionSystemException; -import org.springframework.transaction.support.SimpleTransactionStatus; - -import javax.annotation.PostConstruct; - -/** - * Simple transaction manager for the titan database. - * This manager does not deal with transactions propagation and relies on the fact that transactions are automatically created with the first operation on the graph - */ -@Component -public class SimpleTitanTransactionManager implements PlatformTransactionManager { - - private static final Logger log = Logger.getLogger(SimpleTitanTransactionManager.class.getName()); - private final TitanGraphClient titanClient; - private TitanGraph titanGraph; - - public SimpleTitanTransactionManager(TitanGraphClient titanClient) { - this.titanClient = titanClient; - } - - @PostConstruct - public void onInit() { - titanGraph = titanClient.getGraph().left().on(this::onFailingToStartTitan); - } - - @Override - public TransactionStatus getTransaction(TransactionDefinition transactionDefinition) { - log.debug("#getTransaction - returning simple transaction status"); - return new SimpleTransactionStatus(); - } - - @Override - public void commit(TransactionStatus transactionStatus) { - log.debug("#commit - committing transaction"); - try { - titanGraph.tx().commit(); - } catch (TitanException e) { - log.debug("#commit - failed to commit transaction", e); - throw new TransactionSystemException("failed to commit transaction", e); - } - } - - @Override - public void rollback(TransactionStatus transactionStatus) { - log.debug("#rollback - committing transaction"); - try { - titanGraph.tx().rollback(); - } catch (TitanException e) { - log.debug("#rollback - failed to rollback transaction", e); - throw new TransactionSystemException("failed to rollback transaction", e); - } - } - - private TitanGraph onFailingToStartTitan(TitanOperationStatus err) { - log.debug("#onFailingToStartTitan - could not open titan client"); - throw new IllegalStateException("titan could not be initialized: " + err); - } - -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java index b7ca47600a..c6c609b189 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java @@ -26,7 +26,7 @@ public interface AuditingTypesConstants { String REPO_KEYSPACE = "sdcrepository"; String AUDIT_KEYSPACE = "sdcaudit"; String COMPONENT_KEYSPACE = "sdccomponent"; - String TITAN_KEYSPACE = "titan"; + String janusGraph_KEYSPACE = "janusgraph"; String USER_ADMIN_EVENT_TYPE = "useradminevent"; String USER_ACCESS_EVENT_TYPE = "useraccessevent"; diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/cassandra/HealingPipelineDaoTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/cassandra/HealingPipelineDaoTest.java index 83b68920b9..c0d9e4644c 100644 --- a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/cassandra/HealingPipelineDaoTest.java +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/cassandra/HealingPipelineDaoTest.java @@ -17,10 +17,10 @@ package org.openecomp.sdc.be.dao.cassandra; import com.google.common.collect.ImmutableListMultimap; -import com.thinkaurelius.titan.core.TitanVertex; -import com.thinkaurelius.titan.graphdb.relations.StandardVertexProperty; -import com.thinkaurelius.titan.graphdb.types.system.EmptyVertex; -import com.thinkaurelius.titan.graphdb.types.system.ImplicitKey; +import org.janusgraph.core.JanusGraphVertex; +import org.janusgraph.graphdb.relations.StandardVertexProperty; +import org.janusgraph.graphdb.types.system.EmptyVertex; +import org.janusgraph.graphdb.types.system.ImplicitKey; import java.util.HashMap; import org.junit.Test; import org.mockito.Mockito; @@ -85,7 +85,7 @@ public class HealingPipelineDaoTest { } @Test - public void testPipelineFilter3AttributesTitanVertex() { + public void testPipelineFilter3AttributesJanusGraphVertex() { // init data HealingPipelineDao healingPipelineDao = new HealingPipelineDao(); healingPipelineDao.setHealVersion(7); @@ -95,16 +95,16 @@ public class HealingPipelineDaoTest { assertEquals(2, healingPipelineDao.getHealersForVertex(GraphEdgeLabels.CAPABILITY.getProperty(), HealVersionBuilder.build(5)).size()); - TitanVertex titanVertex = Mockito.mock(TitanVertex.class); + JanusGraphVertex janusGraphVertex = Mockito.mock(JanusGraphVertex.class); final int version = 5; StandardVertexProperty vertexProperty = new StandardVertexProperty(1, ImplicitKey.ID, new EmptyVertex(), version, (byte) 1); - Mockito.when(titanVertex.property(GraphPropertyEnum.HEALING_VERSION.getProperty())).thenReturn(vertexProperty); + Mockito.when(janusGraphVertex.property(GraphPropertyEnum.HEALING_VERSION.getProperty())).thenReturn(vertexProperty); // perform test - Optional optional = healingPipelineDao.performGraphReadHealing(titanVertex, GraphEdgeLabels.CAPABILITY); + Optional optional = healingPipelineDao.performGraphReadHealing(janusGraphVertex, GraphEdgeLabels.CAPABILITY); assertTrue(optional.isPresent()); - final TitanVertex changedVertex = (TitanVertex) optional.get(); + final JanusGraphVertex changedVertex = (JanusGraphVertex) optional.get(); //validate result assertNotNull(changedVertex); @@ -112,7 +112,7 @@ public class HealingPipelineDaoTest { } @Test - public void testPipelineFilterGenericTitanDao() { + public void testPipelineFilterGenericJanusGraphDao() { // init data HealingPipelineDao healingPipelineDao = new HealingPipelineDao(); healingPipelineDao.setHealVersion(7); @@ -140,7 +140,7 @@ public class HealingPipelineDaoTest { } @Test - public void testPipelineFilterTitanGraph1Attributes() { + public void testPipelineFilterJanusGraph1Attributes() { // init data HealingPipelineDao healingPipelineDao = new HealingPipelineDao(); healingPipelineDao.setHealVersion(7); @@ -217,9 +217,9 @@ public class HealingPipelineDaoTest { .put(GraphEdgeLabels.ATTRIBUTE.getProperty(), new GraphNodeHealTestMock(4)) .put(GraphEdgeLabels.ATTRIBUTE.getProperty(), new GraphNodeHealTestMock(5)) .put(GraphEdgeLabels.ATTRIBUTE.getProperty(), new GraphNodeHealTestMock(6)) - .put(GraphEdgeLabels.CAPABILITY.getProperty(), new TitanVertexHealTestMock(4)) - .put(GraphEdgeLabels.CAPABILITY.getProperty(), new TitanVertexHealTestMock(5)) - .put(GraphEdgeLabels.CAPABILITY.getProperty(), new TitanVertexHealTestMock(6)).build(); + .put(GraphEdgeLabels.CAPABILITY.getProperty(), new JanusGraphVertexHealTestMock(4)) + .put(GraphEdgeLabels.CAPABILITY.getProperty(), new JanusGraphVertexHealTestMock(5)) + .put(GraphEdgeLabels.CAPABILITY.getProperty(), new JanusGraphVertexHealTestMock(6)).build(); } public GraphEdge createGraphEdge(GraphEdgeLabels graphEdgeLabels){ @@ -247,7 +247,7 @@ public class HealingPipelineDaoTest { } - private class GraphNodeHealTestMock extends AbstractTitanVertexHeal { + private class GraphNodeHealTestMock extends AbstractJanusGraphVertexHeal { private HealVersion healVersion; public GraphNodeHealTestMock(int i) { @@ -266,10 +266,10 @@ public class HealingPipelineDaoTest { } - private class TitanVertexHealTestMock implements Heal { + private class JanusGraphVertexHealTestMock implements Heal { private HealVersion healVersion; - public TitanVertexHealTestMock(int i) { + public JanusGraphVertexHealTestMock(int i) { healVersion = HealVersionBuilder.build(i); } @@ -279,7 +279,7 @@ public class HealingPipelineDaoTest { } @Override - public void healData(TitanVertex parentV) { + public void healData(JanusGraphVertex parentV) { } } diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphUtilsTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphUtilsTest.java new file mode 100644 index 0000000000..b3fd59e8b6 --- /dev/null +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/janusgraph/JanusGraphUtilsTest.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.be.dao.janusgraph; + +import org.janusgraph.graphdb.query.JanusGraphPredicate; +import org.apache.tinkerpop.gremlin.structure.T; +import org.junit.Test; + +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; +public class JanusGraphUtilsTest { + + @Test + public void testBuildNotInPredicate() throws Exception { + String propKey = ""; + Collection notInCollection = null; + Map> result; + + // default test + result = JanusGraphUtils.buildNotInPredicate(propKey, notInCollection); + } +} \ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertexTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertexTest.java index b336bc65e9..8ce20191fd 100644 --- a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertexTest.java +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertexTest.java @@ -1,6 +1,6 @@ package org.openecomp.sdc.be.dao.jsongraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphVertex; import org.junit.Test; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -70,7 +70,7 @@ public class GraphVertexTest { @Test public void testGetVertex() throws Exception { GraphVertex testSubject; - TitanVertex result; + JanusGraphVertex result; // default test testSubject = createTestSubject(); @@ -81,7 +81,7 @@ public class GraphVertexTest { @Test public void testSetVertex() throws Exception { GraphVertex testSubject; - TitanVertex vertex = null; + JanusGraphVertex vertex = null; // default test testSubject = createTestSubject(); diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/JanusGraphDaoMockTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/JanusGraphDaoMockTest.java new file mode 100644 index 0000000000..72a9d54336 --- /dev/null +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/JanusGraphDaoMockTest.java @@ -0,0 +1,586 @@ +package org.openecomp.sdc.be.dao.jsongraph; + +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; +import fj.data.Either; +import mockit.Deencapsulation; +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.Element; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.Before; +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.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class JanusGraphDaoMockTest { + + @InjectMocks + JanusGraphDao testSubject; + + @Mock + JanusGraphClient janusGraphClient; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testCommit() throws Exception { + JanusGraphOperationStatus result; + + // default test + result = testSubject.commit(); + } + + @Test + public void testRollback() throws Exception { + JanusGraphOperationStatus result; + + // default test + result = testSubject.rollback(); + } + + @Test + public void testGetGraph() throws Exception { + + Either result; + + // default test + + result = testSubject.getGraph(); + } + + @Test + public void testCreateVertex() throws Exception { + + GraphVertex graphVertex = new GraphVertex(); + graphVertex.setLabel(VertexTypeEnum.ADDITIONAL_INFORMATION); + Either result; + + JanusGraph tg = Mockito.mock(JanusGraph.class); + Either value = Either.left(tg); + // default test + JanusGraphVertex value2 = Mockito.mock(JanusGraphVertex.class); + Mockito.when(tg.addVertex()).thenReturn(value2); + Mockito.when(janusGraphClient.getGraph()).thenReturn(value); + result = testSubject.createVertex(graphVertex); + } + + @Test + public void testCreateVertexErrorGetGraph() throws Exception { + + GraphVertex graphVertex = new GraphVertex(); + graphVertex.setLabel(VertexTypeEnum.ADDITIONAL_INFORMATION); + Either result; + + Either value = Either.right(JanusGraphOperationStatus.GENERAL_ERROR); + // default test + Mockito.when(janusGraphClient.getGraph()).thenReturn(value); + result = testSubject.createVertex(graphVertex); + } + + @Test + public void testCreateVertexException() throws Exception { + + GraphVertex graphVertex = new GraphVertex(); + graphVertex.setLabel(VertexTypeEnum.ADDITIONAL_INFORMATION); + Either result; + + JanusGraph tg = Mockito.mock(JanusGraph.class); + Either value = Either.left(tg); + // default test + Mockito.when(tg.addVertex()).thenThrow(RuntimeException.class); + Mockito.when(janusGraphClient.getGraph()).thenReturn(value); + result = testSubject.createVertex(graphVertex); + } + + @Test + public void testGetVertexByPropertyAndLabel() throws Exception { + Either result; + + // default test + Mockito.when(janusGraphClient.getGraph()).thenReturn(Either.right(JanusGraphOperationStatus.GENERAL_ERROR)); + result = testSubject.getVertexByPropertyAndLabel(GraphPropertyEnum.COMPONENT_TYPE, "mock", + VertexTypeEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testGetFirstFoundVertex() throws Exception { + Iterable vertices = Mockito.mock(Iterable.class); + Either result; + + Iterator value = Mockito.mock(Iterator.class); + Mockito.when(vertices.iterator()).thenReturn(value); + Mockito.when(value.hasNext()).thenReturn(true); + JanusGraphVertex value2 = Mockito.mock(JanusGraphVertex.class); + Mockito.when(value.next()).thenReturn(value2); + + // default test + result = Deencapsulation.invoke(testSubject, "getFirstFoundVertex", JsonParseFlagEnum.NoParse, vertices); + } + + @Test + public void testGetFirstFoundVertexNotFound() throws Exception { + Iterable vertices = Mockito.mock(Iterable.class); + Either result; + + Iterator value = Mockito.mock(Iterator.class); + Mockito.when(vertices.iterator()).thenReturn(value); + Mockito.when(value.hasNext()).thenReturn(false); + JanusGraphVertex value2 = Mockito.mock(JanusGraphVertex.class); + Mockito.when(value.next()).thenReturn(value2); + + // default test + result = Deencapsulation.invoke(testSubject, "getFirstFoundVertex", JsonParseFlagEnum.NoParse, vertices); + } + + @Test + public void testGetVertexById_1Exception() throws Exception { + + String id = "mock"; + Either result; + + JanusGraph tg = Mockito.mock(JanusGraph.class); + Either value = Either.left(tg); + // default test + JanusGraphVertex value2 = Mockito.mock(JanusGraphVertex.class); + Mockito.when(tg.addVertex()).thenReturn(value2); + Mockito.when(janusGraphClient.getGraph()).thenReturn(value); + + // test 1 + result = testSubject.getVertexById(id, JsonParseFlagEnum.NoParse); + // Assert.assertEquals(null, result); + } + + @Test + public void testGetVertexById_1GraphClosed() throws Exception { + + String id = "mock"; + Either result; + + Object b; + Either value = Either.right(JanusGraphOperationStatus.GENERAL_ERROR); + // default test + JanusGraphVertex value2 = Mockito.mock(JanusGraphVertex.class); + Mockito.when(janusGraphClient.getGraph()).thenReturn(value); + + // test 1 + result = testSubject.getVertexById(id, JsonParseFlagEnum.NoParse); + // Assert.assertEquals(null, result); + } + + @Test + public void testSetVertexProperties_1() throws Exception { + Vertex vertex = Mockito.mock(Vertex.class); + Map properties = new HashMap<>(); + properties.put("mock", "mock"); + + // default test + testSubject.setVertexProperties(vertex, properties); + } + + @Test + public void testCreateAndFill() throws Exception { + + JanusGraphVertex vertex = Mockito.mock(JanusGraphVertex.class); + JsonParseFlagEnum parseFlag = null; + GraphVertex result; + + // default test + + result = Deencapsulation.invoke(testSubject, "createAndFill", vertex, JsonParseFlagEnum.NoParse); + } + + @Test + public void testParseVertexProperties() throws Exception { + + GraphVertex graphVertex = new GraphVertex(); + JanusGraphVertex vertex = Mockito.mock(JanusGraphVertex.class); + graphVertex.setVertex(vertex); + JsonParseFlagEnum parseFlag = null; + + // default test + + testSubject.parseVertexProperties(graphVertex, JsonParseFlagEnum.NoParse); + } + + + @Test + public void testCreateEdge() throws Exception { + + GraphVertex from = Mockito.mock(GraphVertex.class); + GraphVertex to = Mockito.mock(GraphVertex.class); + + JanusGraphVertex value = Mockito.mock(JanusGraphVertex.class); + Mockito.when(from.getVertex()).thenReturn(value); + Mockito.when(to.getVertex()).thenReturn(value); + Map properties = new HashMap<>(); + JanusGraphOperationStatus result; + + // default test + + result = testSubject.createEdge(from, to, EdgeLabelEnum.ADDITIONAL_INFORMATION, properties); + from = new GraphVertex(); + to = new GraphVertex(); + result = testSubject.createEdge(from, to, EdgeLabelEnum.ADDITIONAL_INFORMATION, properties); + } + + @Test + public void testSetEdgeProperties() throws Exception { + + Element element = Mockito.mock(Element.class); + Map properties = new HashMap<>(); + + // test 1 + + properties.put(EdgePropertyEnum.STATE, "mock"); + testSubject.setEdgeProperties(element, properties); + } + + @Test + public void testGetByCriteria() throws Exception { + Map props = new HashMap<>(); + Either, JanusGraphOperationStatus> result; + + JanusGraph tg = Mockito.mock(JanusGraph.class); + Either value = Either.left(tg); + JanusGraphVertex value2 = Mockito.mock(JanusGraphVertex.class); + Mockito.when(tg.addVertex()).thenReturn(value2); + Mockito.when(janusGraphClient.getGraph()).thenReturn(value); + + // default test + result = testSubject.getByCriteria(VertexTypeEnum.ADDITIONAL_INFORMATION, props); + } + + @Test + public void testGetByCriteria_1() throws Exception { + + Map props = new HashMap<>(); + Either, JanusGraphOperationStatus> result; + + Either value = Either.right(JanusGraphOperationStatus.GENERAL_ERROR); + JanusGraphVertex value2 = Mockito.mock(JanusGraphVertex.class); + Mockito.when(janusGraphClient.getGraph()).thenReturn(value); + + // default test + result = testSubject.getByCriteria(VertexTypeEnum.ADDITIONAL_INFORMATION, props, JsonParseFlagEnum.NoParse); + } + + @Test + public void testGetCatalogVerticies() throws Exception { + Either, JanusGraphOperationStatus> result; + + Either value = Either.right(JanusGraphOperationStatus.GENERAL_ERROR); + // default test + JanusGraphVertex value2 = Mockito.mock(JanusGraphVertex.class); + Mockito.when(janusGraphClient.getGraph()).thenReturn(value); + + // default test + result = testSubject.getCatalogOrArchiveVerticies(true); + } + + @Test + public void testGetChildVertex() throws Exception { + + GraphVertex parentVertex = new GraphVertex(); + EdgeLabelEnum edgeLabel = null; + JsonParseFlagEnum parseFlag = null; + Either result; + + Either value = Either.right(JanusGraphOperationStatus.GENERAL_ERROR); + JanusGraphVertex value2 = Mockito.mock(JanusGraphVertex.class); + Mockito.when(janusGraphClient.getGraph()).thenReturn(value); + + // default test + result = testSubject.getChildVertex(parentVertex, EdgeLabelEnum.ADDITIONAL_INFORMATION, JsonParseFlagEnum.NoParse); + } + + @Test + public void testGetChildVertex_1() throws Exception { + + Vertex parentVertex = null; + EdgeLabelEnum edgeLabel = null; + JsonParseFlagEnum parseFlag = null; + Either result; + + Either value = Either.right(JanusGraphOperationStatus.GENERAL_ERROR); + JanusGraphVertex value2 = Mockito.mock(JanusGraphVertex.class); + Mockito.when(janusGraphClient.getGraph()).thenReturn(value); + + // default test + result = testSubject.getChildVertex(parentVertex, edgeLabel, parseFlag); + } + + + @Test + public void testGetParentVertex_1() throws Exception { + + Vertex parentVertex = null; + EdgeLabelEnum edgeLabel = null; + JsonParseFlagEnum parseFlag = null; + Either result; + + // default test + + result = testSubject.getParentVertex(parentVertex, edgeLabel, parseFlag); + } + + @Test + public void testGetParentVertecies_1() throws Exception { + + Vertex parentVertex = null; + EdgeLabelEnum edgeLabel = null; + JsonParseFlagEnum parseFlag = null; + Either, JanusGraphOperationStatus> result; + + // default test + + result = testSubject.getParentVertecies(parentVertex, edgeLabel, parseFlag); + } + + @Test + public void testGetAdjacentVerticies() throws Exception { + + Vertex parentVertex = null; + EdgeLabelEnum edgeLabel = null; + JsonParseFlagEnum parseFlag = null; + Direction direction = null; + Either, JanusGraphOperationStatus> result; + + Either value = Either.right(JanusGraphOperationStatus.GENERAL_ERROR); + JanusGraphVertex value2 = Mockito.mock(JanusGraphVertex.class); + Mockito.when(janusGraphClient.getGraph()).thenReturn(value); + // default test + result = Deencapsulation.invoke(testSubject, "getAdjacentVerticies", + new Object[] { Vertex.class, EdgeLabelEnum.class, JsonParseFlagEnum.class, Direction.class }); + } + + @Test + public void testGetChildrenVertecies_1() throws Exception { + + Vertex parentVertex = null; + EdgeLabelEnum edgeLabel = null; + JsonParseFlagEnum parseFlag = null; + Either, JanusGraphOperationStatus> result; + + // default test + + result = testSubject.getChildrenVertecies(parentVertex, edgeLabel, parseFlag); + } + + + @Test + public void testDeleteBelongingEdgeByCriteria() throws Exception { + + GraphVertex vertex = null; + EdgeLabelEnum label = null; + Map properties = null; + Either result; + + // default test + + result = testSubject.deleteBelongingEdgeByCriteria(vertex, label, properties); + } + + @Test + public void testDeleteEdge() throws Exception { + + GraphVertex fromVertex = new GraphVertex(); + GraphVertex toVertex = new GraphVertex(); + Either result; + + Either value = Either.right(JanusGraphOperationStatus.GENERAL_ERROR); + JanusGraphVertex value2 = Mockito.mock(JanusGraphVertex.class); + Mockito.when(janusGraphClient.getGraph()).thenReturn(value); + + // default test + result = testSubject.deleteEdge(fromVertex, toVertex, EdgeLabelEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testDeleteEdgeByDirection() throws Exception { + GraphVertex fromVertex = new GraphVertex(); + JanusGraphOperationStatus result; + + // default test + result = testSubject.deleteEdgeByDirection(fromVertex, Direction.BOTH, EdgeLabelEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testDeleteEdgeByDirectionMock() throws Exception { + GraphVertex fromVertex = Mockito.mock(GraphVertex.class); + JanusGraphOperationStatus result; + + JanusGraphVertex value = Mockito.mock(JanusGraphVertex.class);; + Mockito.when(fromVertex.getVertex()).thenReturn(value); + Iterator value2 = Mockito.mock(Iterator.class);; + Mockito.when(value.edges(Mockito.any(), Mockito.any())).thenReturn(value2); + Mockito.when(value2.hasNext()).thenReturn(true, false); + Edge value3 = Mockito.mock(Edge.class);; + Mockito.when(value2.next()).thenReturn(value3); + // default test + result = testSubject.deleteEdgeByDirection(fromVertex, Direction.BOTH, EdgeLabelEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testUpdateVertex() throws Exception { + + GraphVertex graphVertex = new GraphVertex(); + Either result; + + // default test + + result = testSubject.updateVertex(graphVertex); + } + + @Test + public void testGetVerticesByUniqueIdAndParseFlag() throws Exception { + + Map> verticesToGet = new HashMap<>(); + Either, JanusGraphOperationStatus> result; + + // default test + result = testSubject.getVerticesByUniqueIdAndParseFlag(verticesToGet); + ImmutablePair value3 = ImmutablePair.of(GraphPropertyEnum.COMPONENT_TYPE, JsonParseFlagEnum.NoParse); + verticesToGet.put("mock", value3); + try { + result = testSubject.getVerticesByUniqueIdAndParseFlag(verticesToGet); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testCreateEdge_2() throws Exception { + + Vertex from = null; + Vertex to = null; + EdgeLabelEnum label = null; + Edge edgeToCopy = null; + JanusGraphOperationStatus result; + + // default test + + result = testSubject.createEdge(from, to, label, edgeToCopy); + } + + + @Test + public void testReplaceEdgeLabel() throws Exception { + + Vertex fromVertex = null; + Vertex toVertex = null; + Edge prevEdge = null; + EdgeLabelEnum prevLabel = null; + EdgeLabelEnum newLabel = null; + JanusGraphOperationStatus result; + + // default test + + result = testSubject.replaceEdgeLabel(fromVertex, toVertex, prevEdge, prevLabel, newLabel); + } + + @Test + public void testUpdateVertexMetadataPropertiesWithJson() throws Exception { + + Vertex vertex = Mockito.mock(Vertex.class);; + Map properties = new HashMap<>(); + properties.put(GraphPropertyEnum.COMPONENT_TYPE, "mock"); + JanusGraphOperationStatus result; + + // default test + + result = testSubject.updateVertexMetadataPropertiesWithJson(vertex, properties); + } + + //TODO Last + @Test + public void testDisassociateAndDeleteLast() throws Exception { + + GraphVertex vertex = Mockito.mock(GraphVertex.class); + JanusGraphOperationStatus result; + + JanusGraphVertex value = Mockito.mock(JanusGraphVertex.class); + Iterator mockiter = Mockito.mock(Iterator.class); + Edge nextmock = Mockito.mock(Edge.class); + Mockito.when(vertex.getVertex()).thenReturn(value); + Mockito.when(value.edges(Mockito.any(), Mockito.any())).thenReturn(mockiter); + Mockito.when(mockiter.hasNext()).thenReturn(true, false); + Mockito.when(mockiter.next()).thenReturn(nextmock); + Vertex secondVertex = Mockito.mock(Vertex.class); + Mockito.when(nextmock.outVertex()).thenReturn(secondVertex); + Mockito.when(nextmock.inVertex()).thenReturn(secondVertex); + Iterator restOfEdges = Mockito.mock(Iterator.class); + Mockito.when(secondVertex.edges(Mockito.any(), Mockito.any())).thenReturn(restOfEdges); + Mockito.when(restOfEdges.hasNext()).thenReturn(false); + + // default test + result = testSubject.disassociateAndDeleteLast(vertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testDisassociateAndDeleteLastOut() throws Exception { + + GraphVertex vertex = Mockito.mock(GraphVertex.class); + JanusGraphOperationStatus result; + + JanusGraphVertex value = Mockito.mock(JanusGraphVertex.class); + Iterator mockiter = Mockito.mock(Iterator.class); + Edge nextmock = Mockito.mock(Edge.class); + Mockito.when(vertex.getVertex()).thenReturn(value); + Mockito.when(value.edges(Mockito.any(), Mockito.any())).thenReturn(mockiter); + Mockito.when(mockiter.hasNext()).thenReturn(true, false); + Mockito.when(mockiter.next()).thenReturn(nextmock); + Vertex secondVertex = Mockito.mock(Vertex.class); + Mockito.when(nextmock.outVertex()).thenReturn(secondVertex); + Mockito.when(nextmock.inVertex()).thenReturn(secondVertex); + Iterator restOfEdges = Mockito.mock(Iterator.class); + Mockito.when(secondVertex.edges(Mockito.any(), Mockito.any())).thenReturn(restOfEdges); + Mockito.when(restOfEdges.hasNext()).thenReturn(false); + + // default test + result = testSubject.disassociateAndDeleteLast(vertex, Direction.IN, EdgeLabelEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testDisassociateAndDeleteLastException() throws Exception { + + GraphVertex vertex = Mockito.mock(GraphVertex.class); + JanusGraphOperationStatus result; + + Mockito.when(vertex.getVertex()).thenThrow(RuntimeException.class); + + // default test + result = testSubject.disassociateAndDeleteLast(vertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testMoveEdge() throws Exception { + + GraphVertex vertexA = new GraphVertex(); + GraphVertex vertexB = new GraphVertex(); + JanusGraphOperationStatus result; + + // default test + + result = testSubject.moveEdge(vertexA, vertexB, EdgeLabelEnum.ADDITIONAL_INFORMATION, Direction.BOTH); + } +} \ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/JanusGraphDaoTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/JanusGraphDaoTest.java new file mode 100644 index 0000000000..9019de9d24 --- /dev/null +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/JanusGraphDaoTest.java @@ -0,0 +1,312 @@ +package org.openecomp.sdc.be.dao.jsongraph; + +import org.janusgraph.core.JanusGraph; +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Element; +import org.apache.tinkerpop.gremlin.structure.Property; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.dao.DAOJanusGraphStrategy; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.utils.DAOConfDependentTest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class JanusGraphDaoTest extends DAOConfDependentTest{ + + + private static Logger logger = LoggerFactory.getLogger(JanusGraphDaoTest.class); + private JanusGraphDao dao = new JanusGraphDao(new JanusGraphClient(new DAOJanusGraphStrategy())); + + @Before + public void init(){ + dao.janusGraphClient.createGraph(); + } + + @After + public void end(){ + dao.janusGraphClient.cleanupGraph(); + } + + @Test + public void testCreateVertex() throws Exception { + Either result; + + // default test + GraphVertex graphVertex = new GraphVertex(VertexTypeEnum.REQUIREMENTS); + result = dao.createVertex(graphVertex); + + graphVertex = new GraphVertex(); + result = dao.createVertex(graphVertex); + } + + @Test + public void testGetVertexByLabel() throws Exception { + Either result; + + // default test + result = dao.getVertexByLabel(VertexTypeEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testCommit() throws Exception { + JanusGraphOperationStatus result; + + // default test + + result = dao.commit(); + } + + + @Test + public void testRollback() throws Exception { + + JanusGraphOperationStatus result; + + // default test + + result = dao.rollback(); + } + + @Test + public void testGetGraph() throws Exception { + + Either result; + + // default test + + result = dao.getGraph(); + } + + @Test + public void testGetVertexByPropertyAndLabel() throws Exception { + + GraphPropertyEnum name = null; + Object value = null; + VertexTypeEnum label = null; + Either result; + + // default test + + result = dao.getVertexByPropertyAndLabel(name, value, label); + + result = dao.getVertexByPropertyAndLabel(GraphPropertyEnum.COMPONENT_TYPE, new Object(), VertexTypeEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testGetVertexByPropertyAndLabel_1() throws Exception { + + GraphPropertyEnum name = null; + Object value = null; + VertexTypeEnum label = null; + JsonParseFlagEnum parseFlag = null; + Either result; + + // default test + + result = dao.getVertexByPropertyAndLabel(name, value, label, parseFlag); + } + + + @Test + public void testGetVertexById() throws Exception { + + String id = ""; + Either result; + + // default test + + result = dao.getVertexById(id); + } + + @Test + public void testGetVertexById_1() throws Exception { + + String id = ""; + JsonParseFlagEnum parseFlag = null; + Either result; + + // test 1 + + id = null; + result = dao.getVertexById(id, parseFlag); + + // test 2 + + id = ""; + result = dao.getVertexById(id, parseFlag); + } + + @Test + public void testGetVertexProperties() throws Exception { + + Element element = null; + Map result; + + // test 1 + + element = null; + result = dao.getVertexProperties(element); + } + + + @Test + public void testGetEdgeProperties() throws Exception { + + Element element = null; + Map result; + + // test 1 + + element = null; + result = dao.getEdgeProperties(element); + } + + @Test + public void testGetByCriteria() throws Exception { + + VertexTypeEnum type = null; + Map props = null; + Either, JanusGraphOperationStatus> result; + + // default test + + result = dao.getByCriteria(type, props); + } + + @Test + public void testGetByCriteria_1() throws Exception { + + VertexTypeEnum type = null; + Map props = null; + JsonParseFlagEnum parseFlag = null; + Either, JanusGraphOperationStatus> result; + + // default test + + result = dao.getByCriteria(type, props, parseFlag); + } + + + @Test + public void testGetByCriteria_2() throws Exception { + + VertexTypeEnum type = null; + Map props = null; + Map hasNotProps = null; + JsonParseFlagEnum parseFlag = null; + Either, JanusGraphOperationStatus> result; + + // default test + + result = dao.getByCriteria(type, props, hasNotProps, parseFlag); + } + + @Test + public void testGetCatalogVerticies() throws Exception { + + Either, JanusGraphOperationStatus> result; + + // default test + + result = dao.getCatalogOrArchiveVerticies(true); + } + + @Test + public void testGetParentVertecies_1() throws Exception { + + Vertex parentVertex = null; + EdgeLabelEnum edgeLabel = null; + JsonParseFlagEnum parseFlag = null; + Either, JanusGraphOperationStatus> result; + + // default test + + result = dao.getParentVertecies(parentVertex, edgeLabel, parseFlag); + } + + @Test + public void testGetChildrenVertecies_1() throws Exception { + + Vertex parentVertex = null; + EdgeLabelEnum edgeLabel = null; + JsonParseFlagEnum parseFlag = null; + Either, JanusGraphOperationStatus> result; + + // default test + + result = dao.getChildrenVertecies(parentVertex, edgeLabel, parseFlag); + } + + @Test + public void testUpdateVertexMetadataPropertiesWithJson() throws Exception { + + Vertex vertex = null; + Map properties = null; + JanusGraphOperationStatus result; + + // default test + + result = dao.updateVertexMetadataPropertiesWithJson(vertex, properties); + } + + @Test + public void testGetProperty() throws Exception { + Edge edge = Mockito.mock(Edge.class);; + Object result; + + Property value = Mockito.mock(Property.class); + Mockito.when(edge.property(Mockito.any())).thenReturn(value); + + // default test + result = dao.getProperty(edge, EdgePropertyEnum.STATE); + } + + @Test + public void testGetProperty_1() throws Exception { + Edge edge = Mockito.mock(Edge.class);; + Object result; + + // default test + result = dao.getProperty(edge, EdgePropertyEnum.STATE); + } + + @Test + public void testGetPropertyexception() throws Exception { + Edge edge = Mockito.mock(Edge.class);; + Object result; + + Property value = Mockito.mock(Property.class); + Mockito.when(edge.property(Mockito.any())).thenThrow(RuntimeException.class); + + // default test + result = dao.getProperty(edge, EdgePropertyEnum.STATE); + } + + @Test + public void testGetBelongingEdgeByCriteria_1() throws Exception { + + String parentId = ""; + EdgeLabelEnum label = null; + Map properties = null; + Either result; + + // default test + + result = dao.getBelongingEdgeByCriteria(parentId, label, properties); + } +} \ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoMockTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoMockTest.java deleted file mode 100644 index 5703e53c9c..0000000000 --- a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoMockTest.java +++ /dev/null @@ -1,586 +0,0 @@ -package org.openecomp.sdc.be.dao.jsongraph; - -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; -import fj.data.Either; -import mockit.Deencapsulation; -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.Element; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.junit.Before; -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.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanGraphClient; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -public class TitanDaoMockTest { - - @InjectMocks - TitanDao testSubject; - - @Mock - TitanGraphClient titanClient; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testCommit() throws Exception { - TitanOperationStatus result; - - // default test - result = testSubject.commit(); - } - - @Test - public void testRollback() throws Exception { - TitanOperationStatus result; - - // default test - result = testSubject.rollback(); - } - - @Test - public void testGetGraph() throws Exception { - - Either result; - - // default test - - result = testSubject.getGraph(); - } - - @Test - public void testCreateVertex() throws Exception { - - GraphVertex graphVertex = new GraphVertex(); - graphVertex.setLabel(VertexTypeEnum.ADDITIONAL_INFORMATION); - Either result; - - TitanGraph tg = Mockito.mock(TitanGraph.class); - Either value = Either.left(tg); - // default test - TitanVertex value2 = Mockito.mock(TitanVertex.class); - Mockito.when(tg.addVertex()).thenReturn(value2); - Mockito.when(titanClient.getGraph()).thenReturn(value); - result = testSubject.createVertex(graphVertex); - } - - @Test - public void testCreateVertexErrorGetGraph() throws Exception { - - GraphVertex graphVertex = new GraphVertex(); - graphVertex.setLabel(VertexTypeEnum.ADDITIONAL_INFORMATION); - Either result; - - Either value = Either.right(TitanOperationStatus.GENERAL_ERROR); - // default test - Mockito.when(titanClient.getGraph()).thenReturn(value); - result = testSubject.createVertex(graphVertex); - } - - @Test - public void testCreateVertexException() throws Exception { - - GraphVertex graphVertex = new GraphVertex(); - graphVertex.setLabel(VertexTypeEnum.ADDITIONAL_INFORMATION); - Either result; - - TitanGraph tg = Mockito.mock(TitanGraph.class); - Either value = Either.left(tg); - // default test - Mockito.when(tg.addVertex()).thenThrow(RuntimeException.class); - Mockito.when(titanClient.getGraph()).thenReturn(value); - result = testSubject.createVertex(graphVertex); - } - - @Test - public void testGetVertexByPropertyAndLabel() throws Exception { - Either result; - - // default test - Mockito.when(titanClient.getGraph()).thenReturn(Either.right(TitanOperationStatus.GENERAL_ERROR)); - result = testSubject.getVertexByPropertyAndLabel(GraphPropertyEnum.COMPONENT_TYPE, "mock", - VertexTypeEnum.ADDITIONAL_INFORMATION); - } - - @Test - public void testGetFirstFoundVertex() throws Exception { - Iterable vertices = Mockito.mock(Iterable.class); - Either result; - - Iterator value = Mockito.mock(Iterator.class); - Mockito.when(vertices.iterator()).thenReturn(value); - Mockito.when(value.hasNext()).thenReturn(true); - TitanVertex value2 = Mockito.mock(TitanVertex.class); - Mockito.when(value.next()).thenReturn(value2); - - // default test - result = Deencapsulation.invoke(testSubject, "getFirstFoundVertex", JsonParseFlagEnum.NoParse, vertices); - } - - @Test - public void testGetFirstFoundVertexNotFound() throws Exception { - Iterable vertices = Mockito.mock(Iterable.class); - Either result; - - Iterator value = Mockito.mock(Iterator.class); - Mockito.when(vertices.iterator()).thenReturn(value); - Mockito.when(value.hasNext()).thenReturn(false); - TitanVertex value2 = Mockito.mock(TitanVertex.class); - Mockito.when(value.next()).thenReturn(value2); - - // default test - result = Deencapsulation.invoke(testSubject, "getFirstFoundVertex", JsonParseFlagEnum.NoParse, vertices); - } - - @Test - public void testGetVertexById_1Exception() throws Exception { - - String id = "mock"; - Either result; - - TitanGraph tg = Mockito.mock(TitanGraph.class); - Either value = Either.left(tg); - // default test - TitanVertex value2 = Mockito.mock(TitanVertex.class); - Mockito.when(tg.addVertex()).thenReturn(value2); - Mockito.when(titanClient.getGraph()).thenReturn(value); - - // test 1 - result = testSubject.getVertexById(id, JsonParseFlagEnum.NoParse); - // Assert.assertEquals(null, result); - } - - @Test - public void testGetVertexById_1GraphClosed() throws Exception { - - String id = "mock"; - Either result; - - Object b; - Either value = Either.right(TitanOperationStatus.GENERAL_ERROR); - // default test - TitanVertex value2 = Mockito.mock(TitanVertex.class); - Mockito.when(titanClient.getGraph()).thenReturn(value); - - // test 1 - result = testSubject.getVertexById(id, JsonParseFlagEnum.NoParse); - // Assert.assertEquals(null, result); - } - - @Test - public void testSetVertexProperties_1() throws Exception { - Vertex vertex = Mockito.mock(Vertex.class); - Map properties = new HashMap<>(); - properties.put("mock", "mock"); - - // default test - testSubject.setVertexProperties(vertex, properties); - } - - @Test - public void testCreateAndFill() throws Exception { - - TitanVertex vertex = Mockito.mock(TitanVertex.class); - JsonParseFlagEnum parseFlag = null; - GraphVertex result; - - // default test - - result = Deencapsulation.invoke(testSubject, "createAndFill", vertex, JsonParseFlagEnum.NoParse); - } - - @Test - public void testParseVertexProperties() throws Exception { - - GraphVertex graphVertex = new GraphVertex(); - TitanVertex vertex = Mockito.mock(TitanVertex.class); - graphVertex.setVertex(vertex); - JsonParseFlagEnum parseFlag = null; - - // default test - - testSubject.parseVertexProperties(graphVertex, JsonParseFlagEnum.NoParse); - } - - - @Test - public void testCreateEdge() throws Exception { - - GraphVertex from = Mockito.mock(GraphVertex.class); - GraphVertex to = Mockito.mock(GraphVertex.class); - - TitanVertex value = Mockito.mock(TitanVertex.class); - Mockito.when(from.getVertex()).thenReturn(value); - Mockito.when(to.getVertex()).thenReturn(value); - Map properties = new HashMap<>(); - TitanOperationStatus result; - - // default test - - result = testSubject.createEdge(from, to, EdgeLabelEnum.ADDITIONAL_INFORMATION, properties); - from = new GraphVertex(); - to = new GraphVertex(); - result = testSubject.createEdge(from, to, EdgeLabelEnum.ADDITIONAL_INFORMATION, properties); - } - - @Test - public void testSetEdgeProperties() throws Exception { - - Element element = Mockito.mock(Element.class); - Map properties = new HashMap<>(); - - // test 1 - - properties.put(EdgePropertyEnum.STATE, "mock"); - testSubject.setEdgeProperties(element, properties); - } - - @Test - public void testGetByCriteria() throws Exception { - Map props = new HashMap<>(); - Either, TitanOperationStatus> result; - - TitanGraph tg = Mockito.mock(TitanGraph.class); - Either value = Either.left(tg); - TitanVertex value2 = Mockito.mock(TitanVertex.class); - Mockito.when(tg.addVertex()).thenReturn(value2); - Mockito.when(titanClient.getGraph()).thenReturn(value); - - // default test - result = testSubject.getByCriteria(VertexTypeEnum.ADDITIONAL_INFORMATION, props); - } - - @Test - public void testGetByCriteria_1() throws Exception { - - Map props = new HashMap<>(); - Either, TitanOperationStatus> result; - - Either value = Either.right(TitanOperationStatus.GENERAL_ERROR); - TitanVertex value2 = Mockito.mock(TitanVertex.class); - Mockito.when(titanClient.getGraph()).thenReturn(value); - - // default test - result = testSubject.getByCriteria(VertexTypeEnum.ADDITIONAL_INFORMATION, props, JsonParseFlagEnum.NoParse); - } - - @Test - public void testGetCatalogVerticies() throws Exception { - Either, TitanOperationStatus> result; - - Either value = Either.right(TitanOperationStatus.GENERAL_ERROR); - // default test - TitanVertex value2 = Mockito.mock(TitanVertex.class); - Mockito.when(titanClient.getGraph()).thenReturn(value); - - // default test - result = testSubject.getCatalogOrArchiveVerticies(true); - } - - @Test - public void testGetChildVertex() throws Exception { - - GraphVertex parentVertex = new GraphVertex(); - EdgeLabelEnum edgeLabel = null; - JsonParseFlagEnum parseFlag = null; - Either result; - - Either value = Either.right(TitanOperationStatus.GENERAL_ERROR); - TitanVertex value2 = Mockito.mock(TitanVertex.class); - Mockito.when(titanClient.getGraph()).thenReturn(value); - - // default test - result = testSubject.getChildVertex(parentVertex, EdgeLabelEnum.ADDITIONAL_INFORMATION, JsonParseFlagEnum.NoParse); - } - - @Test - public void testGetChildVertex_1() throws Exception { - - Vertex parentVertex = null; - EdgeLabelEnum edgeLabel = null; - JsonParseFlagEnum parseFlag = null; - Either result; - - Either value = Either.right(TitanOperationStatus.GENERAL_ERROR); - TitanVertex value2 = Mockito.mock(TitanVertex.class); - Mockito.when(titanClient.getGraph()).thenReturn(value); - - // default test - result = testSubject.getChildVertex(parentVertex, edgeLabel, parseFlag); - } - - - @Test - public void testGetParentVertex_1() throws Exception { - - Vertex parentVertex = null; - EdgeLabelEnum edgeLabel = null; - JsonParseFlagEnum parseFlag = null; - Either result; - - // default test - - result = testSubject.getParentVertex(parentVertex, edgeLabel, parseFlag); - } - - @Test - public void testGetParentVertecies_1() throws Exception { - - Vertex parentVertex = null; - EdgeLabelEnum edgeLabel = null; - JsonParseFlagEnum parseFlag = null; - Either, TitanOperationStatus> result; - - // default test - - result = testSubject.getParentVertecies(parentVertex, edgeLabel, parseFlag); - } - - @Test - public void testGetAdjacentVerticies() throws Exception { - - Vertex parentVertex = null; - EdgeLabelEnum edgeLabel = null; - JsonParseFlagEnum parseFlag = null; - Direction direction = null; - Either, TitanOperationStatus> result; - - Either value = Either.right(TitanOperationStatus.GENERAL_ERROR); - TitanVertex value2 = Mockito.mock(TitanVertex.class); - Mockito.when(titanClient.getGraph()).thenReturn(value); - // default test - result = Deencapsulation.invoke(testSubject, "getAdjacentVerticies", - new Object[] { Vertex.class, EdgeLabelEnum.class, JsonParseFlagEnum.class, Direction.class }); - } - - @Test - public void testGetChildrenVertecies_1() throws Exception { - - Vertex parentVertex = null; - EdgeLabelEnum edgeLabel = null; - JsonParseFlagEnum parseFlag = null; - Either, TitanOperationStatus> result; - - // default test - - result = testSubject.getChildrenVertecies(parentVertex, edgeLabel, parseFlag); - } - - - @Test - public void testDeleteBelongingEdgeByCriteria() throws Exception { - - GraphVertex vertex = null; - EdgeLabelEnum label = null; - Map properties = null; - Either result; - - // default test - - result = testSubject.deleteBelongingEdgeByCriteria(vertex, label, properties); - } - - @Test - public void testDeleteEdge() throws Exception { - - GraphVertex fromVertex = new GraphVertex(); - GraphVertex toVertex = new GraphVertex(); - Either result; - - Either value = Either.right(TitanOperationStatus.GENERAL_ERROR); - TitanVertex value2 = Mockito.mock(TitanVertex.class); - Mockito.when(titanClient.getGraph()).thenReturn(value); - - // default test - result = testSubject.deleteEdge(fromVertex, toVertex, EdgeLabelEnum.ADDITIONAL_INFORMATION); - } - - @Test - public void testDeleteEdgeByDirection() throws Exception { - GraphVertex fromVertex = new GraphVertex(); - TitanOperationStatus result; - - // default test - result = testSubject.deleteEdgeByDirection(fromVertex, Direction.BOTH, EdgeLabelEnum.ADDITIONAL_INFORMATION); - } - - @Test - public void testDeleteEdgeByDirectionMock() throws Exception { - GraphVertex fromVertex = Mockito.mock(GraphVertex.class); - TitanOperationStatus result; - - TitanVertex value = Mockito.mock(TitanVertex.class);; - Mockito.when(fromVertex.getVertex()).thenReturn(value); - Iterator value2 = Mockito.mock(Iterator.class);; - Mockito.when(value.edges(Mockito.any(), Mockito.any())).thenReturn(value2); - Mockito.when(value2.hasNext()).thenReturn(true, false); - Edge value3 = Mockito.mock(Edge.class);; - Mockito.when(value2.next()).thenReturn(value3); - // default test - result = testSubject.deleteEdgeByDirection(fromVertex, Direction.BOTH, EdgeLabelEnum.ADDITIONAL_INFORMATION); - } - - @Test - public void testUpdateVertex() throws Exception { - - GraphVertex graphVertex = new GraphVertex(); - Either result; - - // default test - - result = testSubject.updateVertex(graphVertex); - } - - @Test - public void testGetVerticesByUniqueIdAndParseFlag() throws Exception { - - Map> verticesToGet = new HashMap<>(); - Either, TitanOperationStatus> result; - - // default test - result = testSubject.getVerticesByUniqueIdAndParseFlag(verticesToGet); - ImmutablePair value3 = ImmutablePair.of(GraphPropertyEnum.COMPONENT_TYPE, JsonParseFlagEnum.NoParse); - verticesToGet.put("mock", value3); - try { - result = testSubject.getVerticesByUniqueIdAndParseFlag(verticesToGet); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testCreateEdge_2() throws Exception { - - Vertex from = null; - Vertex to = null; - EdgeLabelEnum label = null; - Edge edgeToCopy = null; - TitanOperationStatus result; - - // default test - - result = testSubject.createEdge(from, to, label, edgeToCopy); - } - - - @Test - public void testReplaceEdgeLabel() throws Exception { - - Vertex fromVertex = null; - Vertex toVertex = null; - Edge prevEdge = null; - EdgeLabelEnum prevLabel = null; - EdgeLabelEnum newLabel = null; - TitanOperationStatus result; - - // default test - - result = testSubject.replaceEdgeLabel(fromVertex, toVertex, prevEdge, prevLabel, newLabel); - } - - @Test - public void testUpdateVertexMetadataPropertiesWithJson() throws Exception { - - Vertex vertex = Mockito.mock(Vertex.class);; - Map properties = new HashMap<>(); - properties.put(GraphPropertyEnum.COMPONENT_TYPE, "mock"); - TitanOperationStatus result; - - // default test - - result = testSubject.updateVertexMetadataPropertiesWithJson(vertex, properties); - } - - //TODO Last - @Test - public void testDisassociateAndDeleteLast() throws Exception { - - GraphVertex vertex = Mockito.mock(GraphVertex.class); - TitanOperationStatus result; - - TitanVertex value = Mockito.mock(TitanVertex.class); - Iterator mockiter = Mockito.mock(Iterator.class); - Edge nextmock = Mockito.mock(Edge.class); - Mockito.when(vertex.getVertex()).thenReturn(value); - Mockito.when(value.edges(Mockito.any(), Mockito.any())).thenReturn(mockiter); - Mockito.when(mockiter.hasNext()).thenReturn(true, false); - Mockito.when(mockiter.next()).thenReturn(nextmock); - Vertex secondVertex = Mockito.mock(Vertex.class); - Mockito.when(nextmock.outVertex()).thenReturn(secondVertex); - Mockito.when(nextmock.inVertex()).thenReturn(secondVertex); - Iterator restOfEdges = Mockito.mock(Iterator.class); - Mockito.when(secondVertex.edges(Mockito.any(), Mockito.any())).thenReturn(restOfEdges); - Mockito.when(restOfEdges.hasNext()).thenReturn(false); - - // default test - result = testSubject.disassociateAndDeleteLast(vertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION); - } - - @Test - public void testDisassociateAndDeleteLastOut() throws Exception { - - GraphVertex vertex = Mockito.mock(GraphVertex.class); - TitanOperationStatus result; - - TitanVertex value = Mockito.mock(TitanVertex.class); - Iterator mockiter = Mockito.mock(Iterator.class); - Edge nextmock = Mockito.mock(Edge.class); - Mockito.when(vertex.getVertex()).thenReturn(value); - Mockito.when(value.edges(Mockito.any(), Mockito.any())).thenReturn(mockiter); - Mockito.when(mockiter.hasNext()).thenReturn(true, false); - Mockito.when(mockiter.next()).thenReturn(nextmock); - Vertex secondVertex = Mockito.mock(Vertex.class); - Mockito.when(nextmock.outVertex()).thenReturn(secondVertex); - Mockito.when(nextmock.inVertex()).thenReturn(secondVertex); - Iterator restOfEdges = Mockito.mock(Iterator.class); - Mockito.when(secondVertex.edges(Mockito.any(), Mockito.any())).thenReturn(restOfEdges); - Mockito.when(restOfEdges.hasNext()).thenReturn(false); - - // default test - result = testSubject.disassociateAndDeleteLast(vertex, Direction.IN, EdgeLabelEnum.ADDITIONAL_INFORMATION); - } - - @Test - public void testDisassociateAndDeleteLastException() throws Exception { - - GraphVertex vertex = Mockito.mock(GraphVertex.class); - TitanOperationStatus result; - - Mockito.when(vertex.getVertex()).thenThrow(RuntimeException.class); - - // default test - result = testSubject.disassociateAndDeleteLast(vertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION); - } - - @Test - public void testMoveEdge() throws Exception { - - GraphVertex vertexA = new GraphVertex(); - GraphVertex vertexB = new GraphVertex(); - TitanOperationStatus result; - - // default test - - result = testSubject.moveEdge(vertexA, vertexB, EdgeLabelEnum.ADDITIONAL_INFORMATION, Direction.BOTH); - } -} \ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoTest.java deleted file mode 100644 index 2c4b868ff2..0000000000 --- a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoTest.java +++ /dev/null @@ -1,312 +0,0 @@ -package org.openecomp.sdc.be.dao.jsongraph; - -import com.thinkaurelius.titan.core.TitanGraph; -import fj.data.Either; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Element; -import org.apache.tinkerpop.gremlin.structure.Property; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.openecomp.sdc.be.dao.DAOTitanStrategy; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanGraphClient; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.utils.DAOConfDependentTest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -public class TitanDaoTest extends DAOConfDependentTest{ - - - private static Logger logger = LoggerFactory.getLogger(TitanDaoTest.class); - private TitanDao dao = new TitanDao(new TitanGraphClient(new DAOTitanStrategy())); - - @Before - public void init(){ - dao.titanClient.createGraph(); - } - - @After - public void end(){ - dao.titanClient.cleanupGraph(); - } - - @Test - public void testCreateVertex() throws Exception { - Either result; - - // default test - GraphVertex graphVertex = new GraphVertex(VertexTypeEnum.REQUIREMENTS); - result = dao.createVertex(graphVertex); - - graphVertex = new GraphVertex(); - result = dao.createVertex(graphVertex); - } - - @Test - public void testGetVertexByLabel() throws Exception { - Either result; - - // default test - result = dao.getVertexByLabel(VertexTypeEnum.ADDITIONAL_INFORMATION); - } - - @Test - public void testCommit() throws Exception { - TitanOperationStatus result; - - // default test - - result = dao.commit(); - } - - - @Test - public void testRollback() throws Exception { - - TitanOperationStatus result; - - // default test - - result = dao.rollback(); - } - - @Test - public void testGetGraph() throws Exception { - - Either result; - - // default test - - result = dao.getGraph(); - } - - @Test - public void testGetVertexByPropertyAndLabel() throws Exception { - - GraphPropertyEnum name = null; - Object value = null; - VertexTypeEnum label = null; - Either result; - - // default test - - result = dao.getVertexByPropertyAndLabel(name, value, label); - - result = dao.getVertexByPropertyAndLabel(GraphPropertyEnum.COMPONENT_TYPE, new Object(), VertexTypeEnum.ADDITIONAL_INFORMATION); - } - - @Test - public void testGetVertexByPropertyAndLabel_1() throws Exception { - - GraphPropertyEnum name = null; - Object value = null; - VertexTypeEnum label = null; - JsonParseFlagEnum parseFlag = null; - Either result; - - // default test - - result = dao.getVertexByPropertyAndLabel(name, value, label, parseFlag); - } - - - @Test - public void testGetVertexById() throws Exception { - - String id = ""; - Either result; - - // default test - - result = dao.getVertexById(id); - } - - @Test - public void testGetVertexById_1() throws Exception { - - String id = ""; - JsonParseFlagEnum parseFlag = null; - Either result; - - // test 1 - - id = null; - result = dao.getVertexById(id, parseFlag); - - // test 2 - - id = ""; - result = dao.getVertexById(id, parseFlag); - } - - @Test - public void testGetVertexProperties() throws Exception { - - Element element = null; - Map result; - - // test 1 - - element = null; - result = dao.getVertexProperties(element); - } - - - @Test - public void testGetEdgeProperties() throws Exception { - - Element element = null; - Map result; - - // test 1 - - element = null; - result = dao.getEdgeProperties(element); - } - - @Test - public void testGetByCriteria() throws Exception { - - VertexTypeEnum type = null; - Map props = null; - Either, TitanOperationStatus> result; - - // default test - - result = dao.getByCriteria(type, props); - } - - @Test - public void testGetByCriteria_1() throws Exception { - - VertexTypeEnum type = null; - Map props = null; - JsonParseFlagEnum parseFlag = null; - Either, TitanOperationStatus> result; - - // default test - - result = dao.getByCriteria(type, props, parseFlag); - } - - - @Test - public void testGetByCriteria_2() throws Exception { - - VertexTypeEnum type = null; - Map props = null; - Map hasNotProps = null; - JsonParseFlagEnum parseFlag = null; - Either, TitanOperationStatus> result; - - // default test - - result = dao.getByCriteria(type, props, hasNotProps, parseFlag); - } - - @Test - public void testGetCatalogVerticies() throws Exception { - - Either, TitanOperationStatus> result; - - // default test - - result = dao.getCatalogOrArchiveVerticies(true); - } - - @Test - public void testGetParentVertecies_1() throws Exception { - - Vertex parentVertex = null; - EdgeLabelEnum edgeLabel = null; - JsonParseFlagEnum parseFlag = null; - Either, TitanOperationStatus> result; - - // default test - - result = dao.getParentVertecies(parentVertex, edgeLabel, parseFlag); - } - - @Test - public void testGetChildrenVertecies_1() throws Exception { - - Vertex parentVertex = null; - EdgeLabelEnum edgeLabel = null; - JsonParseFlagEnum parseFlag = null; - Either, TitanOperationStatus> result; - - // default test - - result = dao.getChildrenVertecies(parentVertex, edgeLabel, parseFlag); - } - - @Test - public void testUpdateVertexMetadataPropertiesWithJson() throws Exception { - - Vertex vertex = null; - Map properties = null; - TitanOperationStatus result; - - // default test - - result = dao.updateVertexMetadataPropertiesWithJson(vertex, properties); - } - - @Test - public void testGetProperty() throws Exception { - Edge edge = Mockito.mock(Edge.class);; - Object result; - - Property value = Mockito.mock(Property.class); - Mockito.when(edge.property(Mockito.any())).thenReturn(value); - - // default test - result = dao.getProperty(edge, EdgePropertyEnum.STATE); - } - - @Test - public void testGetProperty_1() throws Exception { - Edge edge = Mockito.mock(Edge.class);; - Object result; - - // default test - result = dao.getProperty(edge, EdgePropertyEnum.STATE); - } - - @Test - public void testGetPropertyexception() throws Exception { - Edge edge = Mockito.mock(Edge.class);; - Object result; - - Property value = Mockito.mock(Property.class); - Mockito.when(edge.property(Mockito.any())).thenThrow(RuntimeException.class); - - // default test - result = dao.getProperty(edge, EdgePropertyEnum.STATE); - } - - @Test - public void testGetBelongingEdgeByCriteria_1() throws Exception { - - String parentId = ""; - EdgeLabelEnum label = null; - Map properties = null; - Either result; - - // default test - - result = dao.getBelongingEdgeByCriteria(parentId, label, properties); - } -} \ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/titan/TitanUtilsTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/titan/TitanUtilsTest.java deleted file mode 100644 index 641eec5773..0000000000 --- a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/titan/TitanUtilsTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.openecomp.sdc.be.dao.titan; - -import com.thinkaurelius.titan.graphdb.query.TitanPredicate; -import org.apache.tinkerpop.gremlin.structure.T; -import org.junit.Test; - -import java.util.Collection; -import java.util.Map; -import java.util.Map.Entry; -public class TitanUtilsTest { - - @Test - public void testBuildNotInPredicate() throws Exception { - String propKey = ""; - Collection notInCollection = null; - Map> result; - - // default test - result = TitanUtils.buildNotInPredicate(propKey, notInCollection); - } -} \ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/JanusGraphGenericDaoTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/JanusGraphGenericDaoTest.java new file mode 100644 index 0000000000..09ab6a1745 --- /dev/null +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/JanusGraphGenericDaoTest.java @@ -0,0 +1,630 @@ +/*- + * ============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.resources; + +import com.google.gson.Gson; +import org.janusgraph.core.PropertyKey; +import org.janusgraph.core.JanusGraphEdge; +import org.janusgraph.core.JanusGraphFactory; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; +import org.janusgraph.core.attribute.Text; +import org.janusgraph.core.schema.JanusGraphManagement; +import fj.data.Either; +import org.apache.commons.configuration.BaseConfiguration; +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.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.utils.UserStatusEnum; +import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.resources.data.*; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.UserRoleEnum; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +import org.springframework.test.context.support.DirtiesContextTestExecutionListener; +import org.springframework.test.context.transaction.TransactionalTestExecutionListener; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class }) +public class JanusGraphGenericDaoTest { + private static Logger log = LoggerFactory.getLogger(JanusGraphGenericDaoTest.class.getName()); + private static ConfigurationManager configurationManager; + + @Resource(name = "janusgraph-generic-dao") + private JanusGraphGenericDao janusGraphDao; + + @BeforeClass + public static void setupBeforeClass() { + ExternalConfiguration.setAppName("catalog-dao"); + String appConfigDir = "src/test/resources/config/catalog-dao"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), + appConfigDir); + configurationManager = new ConfigurationManager(configurationSource); + configurationManager.getConfiguration().setJanusGraphCfgFile("../catalog-be/src/main/resources/config/janusgraph.properties"); + configurationManager.getConfiguration().setJanusGraphInMemoryGraph(true); + } + + // @Test + public void testcheckEdgeProps() { + JanusGraph graph = janusGraphDao.getGraph().left().value(); + JanusGraphVertex v1 = graph.addVertex(); + v1.property("prop1", 123); + JanusGraphVertex v2 = graph.addVertex(); + v2.property("prop1", 456); + JanusGraphEdge addEdge = v1.addEdge("label11", v2); + addEdge.property("edgeProp", "my prop edge"); + graph.tx().commit(); + + Either v11 = janusGraphDao.getVertexByProperty("prop1", 123); + Iterator edges = v11.left().value().edges(Direction.OUT, "label11"); + Edge edge = edges.next(); + // String value = (String)edge.value("edgeProp"); + String value = (String) janusGraphDao.getProperty(edge, "edgeProp"); + log.debug(value); + + } + + @Test + public void testCrudNode() { + + String id = "userId12345abc"; + UserData userData = new UserData("Myname123", "Mylastname", id, "email123", "Tester", + UserStatusEnum.ACTIVE.name(), null); + + Either newNode = janusGraphDao.createNode(userData, UserData.class); + + assertTrue(newNode.isLeft()); + + log.debug("{}", newNode.left().value()); + + janusGraphDao.commit(); + + ImmutablePair keyValueId = userData.getKeyValueId(); + Either node = janusGraphDao.getNode(keyValueId.getKey(), keyValueId.getValue(), + UserData.class); + janusGraphDao.commit(); + assertTrue(node.isLeft()); + log.debug("{}", node.left().value()); + + userData.setRole("Designer"); + node = janusGraphDao.updateNode(userData, UserData.class); + assertTrue(node.isLeft()); + log.debug("{}", node.left().value()); + assertEquals(null, "Designer", node.left().value().getRole()); + janusGraphDao.commit(); + + node = janusGraphDao.deleteNode(userData, UserData.class); + assertTrue(node.isLeft()); + log.debug("{}", node.left().value()); + janusGraphDao.commit(); + + node = janusGraphDao.getNode(keyValueId.getKey(), keyValueId.getValue(), UserData.class); + assertTrue(node.isRight()); + log.debug("{}", node.right().value()); + + } + + @Test + public void testGetByCategoryAndAll() { + + // create 2 nodes + String id = "userId12345abc"; + UserData userData1 = new UserData("Myname123", "Mylastname", id, "email123", "Tester", + UserStatusEnum.ACTIVE.name(), null); + + Either node1 = janusGraphDao.createNode(userData1, UserData.class); + assertTrue(node1.isLeft()); + log.debug("{}", node1.left().value()); + + id = "userIddfkoer45abc"; + UserData userData2 = new UserData("Mynadyhme123", "Mylasghtname", id, "emaighdl123", "Designer", + UserStatusEnum.ACTIVE.name(), null); + Either node2 = janusGraphDao.createNode(userData2, UserData.class); + assertTrue(node2.isLeft()); + log.debug("{}", node2.left().value()); + + janusGraphDao.commit(); + + ImmutablePair keyValueId1 = userData1.getKeyValueId(); + // get first node + Either node = janusGraphDao.getNode(keyValueId1.getKey(), keyValueId1.getValue(), + UserData.class); + assertTrue(node.isLeft()); + log.debug("{}", node.left().value()); + janusGraphDao.commit(); + + // get all must be 2 + 1 default user = 3 + Either, JanusGraphOperationStatus> all = janusGraphDao.getAll(NodeTypeEnum.User, UserData.class); + assertTrue(all.isLeft()); + assertTrue(all.left().value().size() > 0); + + log.debug("{}", all.left().value()); + + Map props = new HashMap<>(); + + props.put(keyValueId1.getKey(), keyValueId1.getValue()); + + // get by criteria. must be 1 + Either, JanusGraphOperationStatus> byCriteria = janusGraphDao.getByCriteria(NodeTypeEnum.User, props, + UserData.class); + assertTrue(byCriteria.isLeft()); + assertEquals(1, byCriteria.left().value().size()); + + log.debug("{}", byCriteria.left().value()); + + // delete all nodes + node = janusGraphDao.deleteNode(userData1, UserData.class); + assertTrue(node.isLeft()); + node = janusGraphDao.deleteNode(userData2, UserData.class); + assertTrue(node.isLeft()); + } + + @Test + public void testGetEdgesForNode() { + String id = "userId12345abc"; + UserData userData = new UserData("Myname123", "Mylastname", id, "email123", UserRoleEnum.ADMIN.name(), + UserStatusEnum.ACTIVE.name(), null); + janusGraphDao.createNode(userData, UserData.class); + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setName("resourceForLock"); + resourceData.getMetadataDataDefinition().setVersion("0.1"); + resourceData.getMetadataDataDefinition().setState("newState"); + resourceData.getMetadataDataDefinition().setUniqueId(resourceData.getMetadataDataDefinition().getName() + "." + + resourceData.getMetadataDataDefinition().getVersion()); + + janusGraphDao.createNode(resourceData, ResourceMetadataData.class); + janusGraphDao.createRelation(userData, resourceData, GraphEdgeLabels.LAST_MODIFIER, null); + janusGraphDao.commit(); + + Either, JanusGraphOperationStatus> eitherEdges = janusGraphDao.getEdgesForNode(userData, Direction.OUT); + assertTrue(eitherEdges.isLeft()); + assertEquals(1, eitherEdges.left().value().size()); + + eitherEdges = janusGraphDao.getEdgesForNode(userData, Direction.IN); + assertTrue(eitherEdges.isLeft()); + assertEquals(0, eitherEdges.left().value().size()); + + eitherEdges = janusGraphDao.getEdgesForNode(resourceData, Direction.OUT); + assertTrue(eitherEdges.isLeft()); + assertEquals(0, eitherEdges.left().value().size()); + + eitherEdges = janusGraphDao.getEdgesForNode(resourceData, Direction.IN); + assertTrue(eitherEdges.isLeft()); + assertEquals(1, eitherEdges.left().value().size()); + + eitherEdges = janusGraphDao.getEdgesForNode(resourceData, Direction.BOTH); + assertTrue(eitherEdges.isLeft()); + assertEquals(1, eitherEdges.left().value().size()); + + eitherEdges = janusGraphDao.getEdgesForNode(userData, Direction.BOTH); + assertTrue(eitherEdges.isLeft()); + assertEquals(1, eitherEdges.left().value().size()); + + janusGraphDao.deleteNode(userData, UserData.class); + janusGraphDao.deleteNode(resourceData, ResourceMetadataData.class); + janusGraphDao.commit(); + } + + @Test + public void testLockElement() { + + ResourceMetadataData resourceData = new ResourceMetadataData(); + + resourceData.getMetadataDataDefinition().setName("resourceForLock"); + resourceData.getMetadataDataDefinition().setVersion("0.1"); + resourceData.getMetadataDataDefinition().setState("newState"); + resourceData.getMetadataDataDefinition().setUniqueId(resourceData.getMetadataDataDefinition().getName() + "." + + resourceData.getMetadataDataDefinition().getVersion()); + + Either resource1 = janusGraphDao.createNode(resourceData, + ResourceMetadataData.class); + assertTrue(resource1.isLeft()); + janusGraphDao.commit(); + String lockId = "lock_" + resourceData.getLabel() + "_" + resource1.left().value().getUniqueId(); + + Either nodeLock = janusGraphDao + .getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class); + assertTrue(nodeLock.isRight()); + assertEquals(JanusGraphOperationStatus.NOT_FOUND, nodeLock.right().value()); + + JanusGraphOperationStatus status = janusGraphDao.lockElement(resourceData); + assertEquals(JanusGraphOperationStatus.OK, status); + + nodeLock = janusGraphDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class); + assertTrue(nodeLock.isLeft()); + assertEquals(lockId, nodeLock.left().value().getUniqueId()); + + janusGraphDao.commit(); + + status = janusGraphDao.lockElement(resourceData); + assertEquals(JanusGraphOperationStatus.ALREADY_LOCKED, status); + + status = janusGraphDao.releaseElement(resourceData); + assertEquals(JanusGraphOperationStatus.OK, status); + + nodeLock = janusGraphDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class); + assertTrue(nodeLock.isRight()); + assertEquals(JanusGraphOperationStatus.NOT_FOUND, nodeLock.right().value()); + janusGraphDao.deleteNode(resourceData, ResourceMetadataData.class); + janusGraphDao.commit(); + + } + + @Test + public void testReLockElement() throws InterruptedException { + + ResourceMetadataData resourceData = new ResourceMetadataData(); + + resourceData.getMetadataDataDefinition().setName("resourceForReLock"); + resourceData.getMetadataDataDefinition().setVersion("0.1"); + resourceData.getMetadataDataDefinition().setState("newState"); + resourceData.getMetadataDataDefinition().setUniqueId(resourceData.getMetadataDataDefinition().getName() + "." + + resourceData.getMetadataDataDefinition().getVersion()); + + Either resource1 = janusGraphDao.createNode(resourceData, + ResourceMetadataData.class); + assertTrue(resource1.isLeft()); + janusGraphDao.commit(); + String lockId = "lock_" + resourceData.getLabel() + "_" + resource1.left().value().getUniqueId(); + + Either nodeLock = janusGraphDao + .getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class); + assertTrue(nodeLock.isRight()); + assertEquals(JanusGraphOperationStatus.NOT_FOUND, nodeLock.right().value()); + + // lock + JanusGraphOperationStatus status = janusGraphDao.lockElement(resourceData); + assertEquals(JanusGraphOperationStatus.OK, status); + + nodeLock = janusGraphDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class); + assertTrue(nodeLock.isLeft()); + assertEquals(lockId, nodeLock.left().value().getUniqueId()); + long time1 = nodeLock.left().value().getTime(); + + janusGraphDao.commit(); + + // timeout + configurationManager.getConfiguration().setJanusGraphLockTimeout(2L); + Thread.sleep(5001); + + // relock + status = janusGraphDao.lockElement(resourceData); + assertEquals(JanusGraphOperationStatus.OK, status); + + nodeLock = janusGraphDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class); + assertTrue(nodeLock.isLeft()); + assertEquals(lockId, nodeLock.left().value().getUniqueId()); + + long time2 = nodeLock.left().value().getTime(); + + assertTrue(time2 > time1); + + status = janusGraphDao.releaseElement(resourceData); + assertEquals(JanusGraphOperationStatus.OK, status); + + nodeLock = janusGraphDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class); + assertTrue(nodeLock.isRight()); + assertEquals(JanusGraphOperationStatus.NOT_FOUND, nodeLock.right().value()); + + janusGraphDao.deleteNode(resourceData, ResourceMetadataData.class); + janusGraphDao.commit(); + + } + + @Test + public void testBoolean() { + ResourceMetadataData resourceData = new ResourceMetadataData(); + + resourceData.getMetadataDataDefinition().setName("resourceForLock"); + resourceData.getMetadataDataDefinition().setVersion("0.1"); + resourceData.getMetadataDataDefinition().setState("NOT_CERTIFIED_CHECKOUT"); + resourceData.getMetadataDataDefinition().setHighestVersion(true); + resourceData.getMetadataDataDefinition().setUniqueId(resourceData.getMetadataDataDefinition().getName() + "." + + resourceData.getMetadataDataDefinition().getVersion()); + + Either resource1 = janusGraphDao.createNode(resourceData, + ResourceMetadataData.class); + assertTrue(resource1.isLeft()); + + resourceData = new ResourceMetadataData(); + + resourceData.getMetadataDataDefinition().setName("resourceForLock"); + resourceData.getMetadataDataDefinition().setVersion("0.2"); + resourceData.getMetadataDataDefinition().setState("NOT_CERTIFIED_CHECKOUT"); + resourceData.getMetadataDataDefinition().setHighestVersion(false); + resourceData.getMetadataDataDefinition().setUniqueId(resourceData.getMetadataDataDefinition().getName() + "." + + resourceData.getMetadataDataDefinition().getVersion()); + + Either resource2 = janusGraphDao.createNode(resourceData, + ResourceMetadataData.class); + janusGraphDao.commit(); + + Map props = new HashMap<>(); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), "NOT_CERTIFIED_CHECKOUT"); + props.put("name", "resourceForLock"); + props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), false); + + // get by criteria. must be 1 + Either, JanusGraphOperationStatus> byCriteria = janusGraphDao + .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); + assertTrue(byCriteria.isLeft()); + + janusGraphDao.deleteNode(resource1.left().value(), ResourceMetadataData.class); + + janusGraphDao.deleteNode(resource2.left().value(), ResourceMetadataData.class); + janusGraphDao.commit(); + } + + // @Test + public void testStringSearch() { + JanusGraph graph; + + BaseConfiguration conf = new BaseConfiguration(); + conf.setProperty("storage.backend", "inmemory"); + graph = JanusGraphFactory.open(conf); + + // JanusGraphManagement graphMgt = graph.getManagementSystem(); + JanusGraphManagement graphMgt = graph.openManagement(); + PropertyKey propKey = graphMgt.makePropertyKey("string1").dataType(String.class).make(); + graphMgt.buildIndex("string1", Vertex.class).addKey(propKey).unique().buildCompositeIndex(); + + propKey = graphMgt.makePropertyKey("string2").dataType(String.class).make(); + + graphMgt.buildIndex("string2", Vertex.class).addKey(propKey).unique().buildCompositeIndex(); + graphMgt.commit(); + + + log.debug("**** predicat index search non case"); + Iterable vertices = graph.query().has("string1", Text.REGEX, "my new string 1").vertices(); + Iterator iter = vertices.iterator(); + while (iter.hasNext()) { + Vertex ver = iter.next(); + // System.out.println(com.tinkerpop.blueprints.util.ElementHelper.getProperties(ver)); + log.debug("{}", janusGraphDao.getProperties(ver)); + } + + } + + @Test + public void testDuplicateResultDueToJanusGraphBug() { + + ResourceMetadataData resourceData1 = new ResourceMetadataData(); + resourceData1.getMetadataDataDefinition().setUniqueId("A"); + ((ResourceMetadataDataDefinition) resourceData1.getMetadataDataDefinition()).setAbstract(true); + resourceData1.getMetadataDataDefinition().setName("aaaa"); + + Either newNode1 = janusGraphDao.createNode(resourceData1, + ResourceMetadataData.class); + assertTrue(newNode1.isLeft()); + log.debug("{}", newNode1.left().value()); + // janusGraphDao.commit(); + + Map props = new HashMap<>(); + props.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), true); + Either, JanusGraphOperationStatus> byCriteria = janusGraphDao + .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); + assertTrue(byCriteria.isLeft()); + assertEquals("check one result returned", 1, byCriteria.left().value().size()); + // janusGraphDao.commit(); + + ResourceMetadataData resourceToUpdate = new ResourceMetadataData(); + ((ResourceMetadataDataDefinition) resourceToUpdate.getMetadataDataDefinition()).setAbstract(false); + resourceToUpdate.getMetadataDataDefinition().setUniqueId("A"); + Either updateNode = janusGraphDao.updateNode(resourceToUpdate, + ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + // janusGraphDao.commit(); + + byCriteria = janusGraphDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); + assertTrue(byCriteria.isRight()); + assertEquals("check one result returned due to janusgraph bug", JanusGraphOperationStatus.NOT_FOUND, + byCriteria.right().value()); + + AdditionalInfoParameterData infoParameterData = new AdditionalInfoParameterData(); + infoParameterData.getAdditionalInfoParameterDataDefinition().setUniqueId("123"); + Map idToKey = new HashMap<>(); + idToKey.put("key1", "value1"); + infoParameterData.setIdToKey(idToKey); + + Either newNode2 = janusGraphDao.createNode(infoParameterData, + AdditionalInfoParameterData.class); + assertTrue(newNode2.isLeft()); + log.debug("{}", newNode2.left().value()); + // janusGraphDao.commit(); + + Map idToKey2 = new HashMap<>(); + idToKey2.put("key1", "value2"); + + Map props2 = new HashMap<>(); + props2.put(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), "123"); + Gson gson = new Gson(); + props2.put(GraphPropertiesDictionary.ADDITIONAL_INFO_ID_TO_KEY.getProperty(), gson.toJson(idToKey2)); + // props2.put(GraphPropertiesDictionary.ADDITIONAL_INFO_ID_TO_KEY.getProperty(), + // idToKey2); + + Either, JanusGraphOperationStatus> byCriteria2 = janusGraphDao + .getByCriteria(NodeTypeEnum.AdditionalInfoParameters, props2, AdditionalInfoParameterData.class); + assertTrue(byCriteria2.isRight()); + assertEquals("check one result returned due to janusgraph bug", JanusGraphOperationStatus.NOT_FOUND, + byCriteria2.right().value()); + + infoParameterData.setIdToKey(idToKey2); + + Either updateNode2 = janusGraphDao.updateNode(infoParameterData, + AdditionalInfoParameterData.class); + assertTrue(updateNode2.isLeft()); + // janusGraphDao.commit(); + + props2.put(GraphPropertiesDictionary.ADDITIONAL_INFO_ID_TO_KEY.getProperty(), idToKey); + byCriteria2 = janusGraphDao.getByCriteria(NodeTypeEnum.AdditionalInfoParameters, props2, + AdditionalInfoParameterData.class); + assertTrue(byCriteria2.isRight()); + assertEquals("check one result returned due to janusgraph bug", JanusGraphOperationStatus.NOT_FOUND, + byCriteria2.right().value()); + + ComponentInstanceData resourceInstanceData = new ComponentInstanceData(); + resourceInstanceData.getComponentInstDataDefinition().setUniqueId("ri123"); + resourceInstanceData.getComponentInstDataDefinition().setPosX("22"); + resourceInstanceData.getComponentInstDataDefinition().setName("myresource_1"); + + Either newNode3 = janusGraphDao.createNode(resourceInstanceData, + ComponentInstanceData.class); + assertTrue(newNode3.isLeft()); + log.debug("{}", newNode3.left().value()); + // janusGraphDao.commit(); + + resourceInstanceData.getComponentInstDataDefinition().setPosX("50"); + Either updateNode3 = janusGraphDao.updateNode(resourceInstanceData, + ComponentInstanceData.class); + assertTrue(updateNode3.isLeft()); + // janusGraphDao.commit(); + + resourceInstanceData.getComponentInstDataDefinition().setName("myresource_2"); + updateNode3 = janusGraphDao.updateNode(resourceInstanceData, ComponentInstanceData.class); + assertTrue(updateNode3.isLeft()); + // janusGraphDao.commit(); + + Map props3 = new HashMap<>(); + props3.put("positionX", "22"); + Either, JanusGraphOperationStatus> byCriteria3 = janusGraphDao + .getByCriteria(NodeTypeEnum.ResourceInstance, props3, ComponentInstanceData.class); + assertTrue(byCriteria3.isRight()); + assertEquals("check one result returned due to janusgraph bug", JanusGraphOperationStatus.NOT_FOUND, + byCriteria3.right().value()); + + props3.put("positionX", "50"); + byCriteria3 = janusGraphDao.getByCriteria(NodeTypeEnum.ResourceInstance, props3, ComponentInstanceData.class); + assertTrue(byCriteria3.isLeft()); + + /////////////////////////// check integer //////////////////////// + + ArtifactData artifactData = new ArtifactData(); + artifactData.getArtifactDataDefinition().setUniqueId("ad234"); + artifactData.getArtifactDataDefinition().setTimeout(100); + + Either newNode4 = janusGraphDao.createNode(artifactData, ArtifactData.class); + assertTrue(newNode4.isLeft()); + log.debug("{}", newNode4.left().value()); + // janusGraphDao.commit(); + + artifactData.getArtifactDataDefinition().setTimeout(50); + Either updateNode4 = janusGraphDao.updateNode(artifactData, ArtifactData.class); + assertTrue(updateNode4.isLeft()); + // janusGraphDao.commit(); + + Map props4 = new HashMap<>(); + props4.put("timeout", 100); + Either, JanusGraphOperationStatus> byCriteria4 = janusGraphDao.getByCriteria(NodeTypeEnum.ArtifactRef, + props4, ArtifactData.class); + assertTrue(byCriteria4.isRight()); + assertEquals("check one result returned due to janusgraph bug", JanusGraphOperationStatus.NOT_FOUND, + byCriteria4.right().value()); + + props4.put("timeout", 50); + byCriteria4 = janusGraphDao.getByCriteria(NodeTypeEnum.ArtifactRef, props4, ArtifactData.class); + assertTrue(byCriteria4.isLeft()); + + janusGraphDao.rollback(); + } + + @Test + public void testDuplicateResultUSeHasNotQueryDueToJanusGraphBug() { + + String name = "bbbb"; + + ResourceMetadataData resourceData1 = new ResourceMetadataData(); + resourceData1.getMetadataDataDefinition().setUniqueId("A"); + ((ResourceMetadataDataDefinition) resourceData1.getMetadataDataDefinition()).setAbstract(true); + resourceData1.getMetadataDataDefinition().setName(name); + + Either newNode1 = janusGraphDao.createNode(resourceData1, + ResourceMetadataData.class); + assertTrue(newNode1.isLeft()); + log.debug("{}", newNode1.left().value()); + // janusGraphDao.commit(); + + Map props = new HashMap<>(); + props.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), true); + Either, JanusGraphOperationStatus> byCriteria = janusGraphDao + .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); + assertTrue(byCriteria.isLeft()); + assertEquals("check one result returned", 1, byCriteria.left().value().size()); + // janusGraphDao.commit(); + + ResourceMetadataData resourceToUpdate = new ResourceMetadataData(); + ((ResourceMetadataDataDefinition) resourceToUpdate.getMetadataDataDefinition()).setAbstract(false); + resourceToUpdate.getMetadataDataDefinition().setUniqueId("A"); + Either updateNode = janusGraphDao.updateNode(resourceToUpdate, + ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + // janusGraphDao.commit(); + + // no result where isAbstract = true + byCriteria = janusGraphDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); + assertTrue(byCriteria.isRight()); + assertEquals("check one result returned due to janusgraph bug", JanusGraphOperationStatus.NOT_FOUND, + byCriteria.right().value()); + + // one result where isAbstract != true + byCriteria = janusGraphDao.getByCriteria(NodeTypeEnum.Resource, null, props, ResourceMetadataData.class); + assertTrue(byCriteria.isLeft()); + assertEquals("check one result returned", 1, byCriteria.left().value().size()); + + props.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), false); + byCriteria = janusGraphDao.getByCriteria(NodeTypeEnum.Resource, null, props, ResourceMetadataData.class); + assertTrue(byCriteria.isRight()); + assertEquals("check one result returned due to janusgraph bug", JanusGraphOperationStatus.NOT_FOUND, + byCriteria.right().value()); + + janusGraphDao.rollback(); + + } + +} diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/TitanGenericDaoTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/TitanGenericDaoTest.java deleted file mode 100644 index e8c6b3cdd1..0000000000 --- a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/TitanGenericDaoTest.java +++ /dev/null @@ -1,631 +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.resources; - -import com.google.gson.Gson; -import com.thinkaurelius.titan.core.PropertyKey; -import com.thinkaurelius.titan.core.TitanEdge; -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; -import com.thinkaurelius.titan.core.attribute.Text; -import com.thinkaurelius.titan.core.schema.TitanManagement; -import fj.data.Either; -import org.apache.commons.configuration.BaseConfiguration; -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.Test; -import org.junit.runner.RunWith; -import org.openecomp.sdc.be.config.ConfigurationManager; -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.UserStatusEnum; -import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.resources.data.*; -import org.openecomp.sdc.common.api.ConfigurationSource; -import org.openecomp.sdc.common.api.UserRoleEnum; -import org.openecomp.sdc.common.impl.ExternalConfiguration; -import org.openecomp.sdc.common.impl.FSConfigurationSource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestExecutionListeners; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; -import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import org.springframework.test.context.transaction.TransactionalTestExecutionListener; - -import javax.annotation.Resource; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:application-context-test.xml") -@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class }) -public class TitanGenericDaoTest { - private static Logger log = LoggerFactory.getLogger(TitanGenericDaoTest.class.getName()); - private static ConfigurationManager configurationManager; - - @Resource(name = "titan-generic-dao") - private TitanGenericDao titanDao; - - @BeforeClass - public static void setupBeforeClass() { - ExternalConfiguration.setAppName("catalog-dao"); - String appConfigDir = "src/test/resources/config/catalog-dao"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), - appConfigDir); - configurationManager = new ConfigurationManager(configurationSource); - configurationManager.getConfiguration() - .setTitanCfgFile("../catalog-be/src/main/resources/config/titan.properties"); - configurationManager.getConfiguration().setTitanInMemoryGraph(true); - } - - // @Test - public void testcheckEdgeProps() { - TitanGraph graph = titanDao.getGraph().left().value(); - TitanVertex v1 = graph.addVertex(); - v1.property("prop1", 123); - TitanVertex v2 = graph.addVertex(); - v2.property("prop1", 456); - TitanEdge addEdge = v1.addEdge("label11", v2); - addEdge.property("edgeProp", "my prop edge"); - graph.tx().commit(); - - Either v11 = titanDao.getVertexByProperty("prop1", 123); - Iterator edges = v11.left().value().edges(Direction.OUT, "label11"); - Edge edge = edges.next(); - // String value = (String)edge.value("edgeProp"); - String value = (String) titanDao.getProperty(edge, "edgeProp"); - log.debug(value); - - } - - @Test - public void testCrudNode() { - - String id = "userId12345abc"; - UserData userData = new UserData("Myname123", "Mylastname", id, "email123", "Tester", - UserStatusEnum.ACTIVE.name(), null); - - Either newNode = titanDao.createNode(userData, UserData.class); - - assertTrue(newNode.isLeft()); - - log.debug("{}", newNode.left().value()); - - titanDao.commit(); - - ImmutablePair keyValueId = userData.getKeyValueId(); - Either node = titanDao.getNode(keyValueId.getKey(), keyValueId.getValue(), - UserData.class); - titanDao.commit(); - assertTrue(node.isLeft()); - log.debug("{}", node.left().value()); - - userData.setRole("Designer"); - node = titanDao.updateNode(userData, UserData.class); - assertTrue(node.isLeft()); - log.debug("{}", node.left().value()); - assertEquals(null, "Designer", node.left().value().getRole()); - titanDao.commit(); - - node = titanDao.deleteNode(userData, UserData.class); - assertTrue(node.isLeft()); - log.debug("{}", node.left().value()); - titanDao.commit(); - - node = titanDao.getNode(keyValueId.getKey(), keyValueId.getValue(), UserData.class); - assertTrue(node.isRight()); - log.debug("{}", node.right().value()); - - } - - @Test - public void testGetByCategoryAndAll() { - - // create 2 nodes - String id = "userId12345abc"; - UserData userData1 = new UserData("Myname123", "Mylastname", id, "email123", "Tester", - UserStatusEnum.ACTIVE.name(), null); - - Either node1 = titanDao.createNode(userData1, UserData.class); - assertTrue(node1.isLeft()); - log.debug("{}", node1.left().value()); - - id = "userIddfkoer45abc"; - UserData userData2 = new UserData("Mynadyhme123", "Mylasghtname", id, "emaighdl123", "Designer", - UserStatusEnum.ACTIVE.name(), null); - Either node2 = titanDao.createNode(userData2, UserData.class); - assertTrue(node2.isLeft()); - log.debug("{}", node2.left().value()); - - titanDao.commit(); - - ImmutablePair keyValueId1 = userData1.getKeyValueId(); - // get first node - Either node = titanDao.getNode(keyValueId1.getKey(), keyValueId1.getValue(), - UserData.class); - assertTrue(node.isLeft()); - log.debug("{}", node.left().value()); - titanDao.commit(); - - // get all must be 2 + 1 default user = 3 - Either, TitanOperationStatus> all = titanDao.getAll(NodeTypeEnum.User, UserData.class); - assertTrue(all.isLeft()); - assertTrue(all.left().value().size() > 0); - - log.debug("{}", all.left().value()); - - Map props = new HashMap<>(); - - props.put(keyValueId1.getKey(), keyValueId1.getValue()); - - // get by criteria. must be 1 - Either, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.User, props, - UserData.class); - assertTrue(byCriteria.isLeft()); - assertEquals(1, byCriteria.left().value().size()); - - log.debug("{}", byCriteria.left().value()); - - // delete all nodes - node = titanDao.deleteNode(userData1, UserData.class); - assertTrue(node.isLeft()); - node = titanDao.deleteNode(userData2, UserData.class); - assertTrue(node.isLeft()); - } - - @Test - public void testGetEdgesForNode() { - String id = "userId12345abc"; - UserData userData = new UserData("Myname123", "Mylastname", id, "email123", UserRoleEnum.ADMIN.name(), - UserStatusEnum.ACTIVE.name(), null); - titanDao.createNode(userData, UserData.class); - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setName("resourceForLock"); - resourceData.getMetadataDataDefinition().setVersion("0.1"); - resourceData.getMetadataDataDefinition().setState("newState"); - resourceData.getMetadataDataDefinition().setUniqueId(resourceData.getMetadataDataDefinition().getName() + "." - + resourceData.getMetadataDataDefinition().getVersion()); - - titanDao.createNode(resourceData, ResourceMetadataData.class); - titanDao.createRelation(userData, resourceData, GraphEdgeLabels.LAST_MODIFIER, null); - titanDao.commit(); - - Either, TitanOperationStatus> eitherEdges = titanDao.getEdgesForNode(userData, Direction.OUT); - assertTrue(eitherEdges.isLeft()); - assertEquals(1, eitherEdges.left().value().size()); - - eitherEdges = titanDao.getEdgesForNode(userData, Direction.IN); - assertTrue(eitherEdges.isLeft()); - assertEquals(0, eitherEdges.left().value().size()); - - eitherEdges = titanDao.getEdgesForNode(resourceData, Direction.OUT); - assertTrue(eitherEdges.isLeft()); - assertEquals(0, eitherEdges.left().value().size()); - - eitherEdges = titanDao.getEdgesForNode(resourceData, Direction.IN); - assertTrue(eitherEdges.isLeft()); - assertEquals(1, eitherEdges.left().value().size()); - - eitherEdges = titanDao.getEdgesForNode(resourceData, Direction.BOTH); - assertTrue(eitherEdges.isLeft()); - assertEquals(1, eitherEdges.left().value().size()); - - eitherEdges = titanDao.getEdgesForNode(userData, Direction.BOTH); - assertTrue(eitherEdges.isLeft()); - assertEquals(1, eitherEdges.left().value().size()); - - titanDao.deleteNode(userData, UserData.class); - titanDao.deleteNode(resourceData, ResourceMetadataData.class); - titanDao.commit(); - } - - @Test - public void testLockElement() { - - ResourceMetadataData resourceData = new ResourceMetadataData(); - - resourceData.getMetadataDataDefinition().setName("resourceForLock"); - resourceData.getMetadataDataDefinition().setVersion("0.1"); - resourceData.getMetadataDataDefinition().setState("newState"); - resourceData.getMetadataDataDefinition().setUniqueId(resourceData.getMetadataDataDefinition().getName() + "." - + resourceData.getMetadataDataDefinition().getVersion()); - - Either resource1 = titanDao.createNode(resourceData, - ResourceMetadataData.class); - assertTrue(resource1.isLeft()); - titanDao.commit(); - String lockId = "lock_" + resourceData.getLabel() + "_" + resource1.left().value().getUniqueId(); - - Either nodeLock = titanDao - .getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class); - assertTrue(nodeLock.isRight()); - assertEquals(TitanOperationStatus.NOT_FOUND, nodeLock.right().value()); - - TitanOperationStatus status = titanDao.lockElement(resourceData); - assertEquals(TitanOperationStatus.OK, status); - - nodeLock = titanDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class); - assertTrue(nodeLock.isLeft()); - assertEquals(lockId, nodeLock.left().value().getUniqueId()); - - titanDao.commit(); - - status = titanDao.lockElement(resourceData); - assertEquals(TitanOperationStatus.ALREADY_LOCKED, status); - - status = titanDao.releaseElement(resourceData); - assertEquals(TitanOperationStatus.OK, status); - - nodeLock = titanDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class); - assertTrue(nodeLock.isRight()); - assertEquals(TitanOperationStatus.NOT_FOUND, nodeLock.right().value()); - titanDao.deleteNode(resourceData, ResourceMetadataData.class); - titanDao.commit(); - - } - - @Test - public void testReLockElement() throws InterruptedException { - - ResourceMetadataData resourceData = new ResourceMetadataData(); - - resourceData.getMetadataDataDefinition().setName("resourceForReLock"); - resourceData.getMetadataDataDefinition().setVersion("0.1"); - resourceData.getMetadataDataDefinition().setState("newState"); - resourceData.getMetadataDataDefinition().setUniqueId(resourceData.getMetadataDataDefinition().getName() + "." - + resourceData.getMetadataDataDefinition().getVersion()); - - Either resource1 = titanDao.createNode(resourceData, - ResourceMetadataData.class); - assertTrue(resource1.isLeft()); - titanDao.commit(); - String lockId = "lock_" + resourceData.getLabel() + "_" + resource1.left().value().getUniqueId(); - - Either nodeLock = titanDao - .getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class); - assertTrue(nodeLock.isRight()); - assertEquals(TitanOperationStatus.NOT_FOUND, nodeLock.right().value()); - - // lock - TitanOperationStatus status = titanDao.lockElement(resourceData); - assertEquals(TitanOperationStatus.OK, status); - - nodeLock = titanDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class); - assertTrue(nodeLock.isLeft()); - assertEquals(lockId, nodeLock.left().value().getUniqueId()); - long time1 = nodeLock.left().value().getTime(); - - titanDao.commit(); - - // timeout - configurationManager.getConfiguration().setTitanLockTimeout(2L); - Thread.sleep(5001); - - // relock - status = titanDao.lockElement(resourceData); - assertEquals(TitanOperationStatus.OK, status); - - nodeLock = titanDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class); - assertTrue(nodeLock.isLeft()); - assertEquals(lockId, nodeLock.left().value().getUniqueId()); - - long time2 = nodeLock.left().value().getTime(); - - assertTrue(time2 > time1); - - status = titanDao.releaseElement(resourceData); - assertEquals(TitanOperationStatus.OK, status); - - nodeLock = titanDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class); - assertTrue(nodeLock.isRight()); - assertEquals(TitanOperationStatus.NOT_FOUND, nodeLock.right().value()); - - titanDao.deleteNode(resourceData, ResourceMetadataData.class); - titanDao.commit(); - - } - - @Test - public void testBoolean() { - ResourceMetadataData resourceData = new ResourceMetadataData(); - - resourceData.getMetadataDataDefinition().setName("resourceForLock"); - resourceData.getMetadataDataDefinition().setVersion("0.1"); - resourceData.getMetadataDataDefinition().setState("NOT_CERTIFIED_CHECKOUT"); - resourceData.getMetadataDataDefinition().setHighestVersion(true); - resourceData.getMetadataDataDefinition().setUniqueId(resourceData.getMetadataDataDefinition().getName() + "." - + resourceData.getMetadataDataDefinition().getVersion()); - - Either resource1 = titanDao.createNode(resourceData, - ResourceMetadataData.class); - assertTrue(resource1.isLeft()); - - resourceData = new ResourceMetadataData(); - - resourceData.getMetadataDataDefinition().setName("resourceForLock"); - resourceData.getMetadataDataDefinition().setVersion("0.2"); - resourceData.getMetadataDataDefinition().setState("NOT_CERTIFIED_CHECKOUT"); - resourceData.getMetadataDataDefinition().setHighestVersion(false); - resourceData.getMetadataDataDefinition().setUniqueId(resourceData.getMetadataDataDefinition().getName() + "." - + resourceData.getMetadataDataDefinition().getVersion()); - - Either resource2 = titanDao.createNode(resourceData, - ResourceMetadataData.class); - titanDao.commit(); - - Map props = new HashMap<>(); - - props.put(GraphPropertiesDictionary.STATE.getProperty(), "NOT_CERTIFIED_CHECKOUT"); - props.put("name", "resourceForLock"); - props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), false); - - // get by criteria. must be 1 - Either, TitanOperationStatus> byCriteria = titanDao - .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); - assertTrue(byCriteria.isLeft()); - - titanDao.deleteNode(resource1.left().value(), ResourceMetadataData.class); - - titanDao.deleteNode(resource2.left().value(), ResourceMetadataData.class); - titanDao.commit(); - } - - // @Test - public void testStringSearch() { - TitanGraph graph; - - BaseConfiguration conf = new BaseConfiguration(); - conf.setProperty("storage.backend", "inmemory"); - graph = TitanFactory.open(conf); - - // TitanManagement graphMgt = graph.getManagementSystem(); - TitanManagement graphMgt = graph.openManagement(); - PropertyKey propKey = graphMgt.makePropertyKey("string1").dataType(String.class).make(); - graphMgt.buildIndex("string1", Vertex.class).addKey(propKey).unique().buildCompositeIndex(); - - propKey = graphMgt.makePropertyKey("string2").dataType(String.class).make(); - - graphMgt.buildIndex("string2", Vertex.class).addKey(propKey).unique().buildCompositeIndex(); - graphMgt.commit(); - - - log.debug("**** predicat index search non case"); - Iterable vertices = graph.query().has("string1", Text.REGEX, "my new string 1").vertices(); - Iterator iter = vertices.iterator(); - while (iter.hasNext()) { - Vertex ver = iter.next(); - // System.out.println(com.tinkerpop.blueprints.util.ElementHelper.getProperties(ver)); - log.debug("{}", titanDao.getProperties(ver)); - } - - } - - @Test - public void testDuplicateResultDueToTitanBug() { - - ResourceMetadataData resourceData1 = new ResourceMetadataData(); - resourceData1.getMetadataDataDefinition().setUniqueId("A"); - ((ResourceMetadataDataDefinition) resourceData1.getMetadataDataDefinition()).setAbstract(true); - resourceData1.getMetadataDataDefinition().setName("aaaa"); - - Either newNode1 = titanDao.createNode(resourceData1, - ResourceMetadataData.class); - assertTrue(newNode1.isLeft()); - log.debug("{}", newNode1.left().value()); - // titanDao.commit(); - - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), true); - Either, TitanOperationStatus> byCriteria = titanDao - .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); - assertTrue(byCriteria.isLeft()); - assertEquals("check one result returned", 1, byCriteria.left().value().size()); - // titanDao.commit(); - - ResourceMetadataData resourceToUpdate = new ResourceMetadataData(); - ((ResourceMetadataDataDefinition) resourceToUpdate.getMetadataDataDefinition()).setAbstract(false); - resourceToUpdate.getMetadataDataDefinition().setUniqueId("A"); - Either updateNode = titanDao.updateNode(resourceToUpdate, - ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - // titanDao.commit(); - - byCriteria = titanDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); - assertTrue(byCriteria.isRight()); - assertEquals("check one result returned due to titan bug", TitanOperationStatus.NOT_FOUND, - byCriteria.right().value()); - - AdditionalInfoParameterData infoParameterData = new AdditionalInfoParameterData(); - infoParameterData.getAdditionalInfoParameterDataDefinition().setUniqueId("123"); - Map idToKey = new HashMap<>(); - idToKey.put("key1", "value1"); - infoParameterData.setIdToKey(idToKey); - - Either newNode2 = titanDao.createNode(infoParameterData, - AdditionalInfoParameterData.class); - assertTrue(newNode2.isLeft()); - log.debug("{}", newNode2.left().value()); - // titanDao.commit(); - - Map idToKey2 = new HashMap<>(); - idToKey2.put("key1", "value2"); - - Map props2 = new HashMap<>(); - props2.put(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), "123"); - Gson gson = new Gson(); - props2.put(GraphPropertiesDictionary.ADDITIONAL_INFO_ID_TO_KEY.getProperty(), gson.toJson(idToKey2)); - // props2.put(GraphPropertiesDictionary.ADDITIONAL_INFO_ID_TO_KEY.getProperty(), - // idToKey2); - - Either, TitanOperationStatus> byCriteria2 = titanDao - .getByCriteria(NodeTypeEnum.AdditionalInfoParameters, props2, AdditionalInfoParameterData.class); - assertTrue(byCriteria2.isRight()); - assertEquals("check one result returned due to titan bug", TitanOperationStatus.NOT_FOUND, - byCriteria2.right().value()); - - infoParameterData.setIdToKey(idToKey2); - - Either updateNode2 = titanDao.updateNode(infoParameterData, - AdditionalInfoParameterData.class); - assertTrue(updateNode2.isLeft()); - // titanDao.commit(); - - props2.put(GraphPropertiesDictionary.ADDITIONAL_INFO_ID_TO_KEY.getProperty(), idToKey); - byCriteria2 = titanDao.getByCriteria(NodeTypeEnum.AdditionalInfoParameters, props2, - AdditionalInfoParameterData.class); - assertTrue(byCriteria2.isRight()); - assertEquals("check one result returned due to titan bug", TitanOperationStatus.NOT_FOUND, - byCriteria2.right().value()); - - ComponentInstanceData resourceInstanceData = new ComponentInstanceData(); - resourceInstanceData.getComponentInstDataDefinition().setUniqueId("ri123"); - resourceInstanceData.getComponentInstDataDefinition().setPosX("22"); - resourceInstanceData.getComponentInstDataDefinition().setName("myresource_1"); - - Either newNode3 = titanDao.createNode(resourceInstanceData, - ComponentInstanceData.class); - assertTrue(newNode3.isLeft()); - log.debug("{}", newNode3.left().value()); - // titanDao.commit(); - - resourceInstanceData.getComponentInstDataDefinition().setPosX("50"); - Either updateNode3 = titanDao.updateNode(resourceInstanceData, - ComponentInstanceData.class); - assertTrue(updateNode3.isLeft()); - // titanDao.commit(); - - resourceInstanceData.getComponentInstDataDefinition().setName("myresource_2"); - updateNode3 = titanDao.updateNode(resourceInstanceData, ComponentInstanceData.class); - assertTrue(updateNode3.isLeft()); - // titanDao.commit(); - - Map props3 = new HashMap<>(); - props3.put("positionX", "22"); - Either, TitanOperationStatus> byCriteria3 = titanDao - .getByCriteria(NodeTypeEnum.ResourceInstance, props3, ComponentInstanceData.class); - assertTrue(byCriteria3.isRight()); - assertEquals("check one result returned due to titan bug", TitanOperationStatus.NOT_FOUND, - byCriteria3.right().value()); - - props3.put("positionX", "50"); - byCriteria3 = titanDao.getByCriteria(NodeTypeEnum.ResourceInstance, props3, ComponentInstanceData.class); - assertTrue(byCriteria3.isLeft()); - - /////////////////////////// check integer //////////////////////// - - ArtifactData artifactData = new ArtifactData(); - artifactData.getArtifactDataDefinition().setUniqueId("ad234"); - artifactData.getArtifactDataDefinition().setTimeout(100); - - Either newNode4 = titanDao.createNode(artifactData, ArtifactData.class); - assertTrue(newNode4.isLeft()); - log.debug("{}", newNode4.left().value()); - // titanDao.commit(); - - artifactData.getArtifactDataDefinition().setTimeout(50); - Either updateNode4 = titanDao.updateNode(artifactData, ArtifactData.class); - assertTrue(updateNode4.isLeft()); - // titanDao.commit(); - - Map props4 = new HashMap<>(); - props4.put("timeout", 100); - Either, TitanOperationStatus> byCriteria4 = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, - props4, ArtifactData.class); - assertTrue(byCriteria4.isRight()); - assertEquals("check one result returned due to titan bug", TitanOperationStatus.NOT_FOUND, - byCriteria4.right().value()); - - props4.put("timeout", 50); - byCriteria4 = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, props4, ArtifactData.class); - assertTrue(byCriteria4.isLeft()); - - titanDao.rollback(); - } - - @Test - public void testDuplicateResultUSeHasNotQueryDueToTitanBug() { - - String name = "bbbb"; - - ResourceMetadataData resourceData1 = new ResourceMetadataData(); - resourceData1.getMetadataDataDefinition().setUniqueId("A"); - ((ResourceMetadataDataDefinition) resourceData1.getMetadataDataDefinition()).setAbstract(true); - resourceData1.getMetadataDataDefinition().setName(name); - - Either newNode1 = titanDao.createNode(resourceData1, - ResourceMetadataData.class); - assertTrue(newNode1.isLeft()); - log.debug("{}", newNode1.left().value()); - // titanDao.commit(); - - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), true); - Either, TitanOperationStatus> byCriteria = titanDao - .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); - assertTrue(byCriteria.isLeft()); - assertEquals("check one result returned", 1, byCriteria.left().value().size()); - // titanDao.commit(); - - ResourceMetadataData resourceToUpdate = new ResourceMetadataData(); - ((ResourceMetadataDataDefinition) resourceToUpdate.getMetadataDataDefinition()).setAbstract(false); - resourceToUpdate.getMetadataDataDefinition().setUniqueId("A"); - Either updateNode = titanDao.updateNode(resourceToUpdate, - ResourceMetadataData.class); - assertTrue(updateNode.isLeft()); - // titanDao.commit(); - - // no result where isAbstract = true - byCriteria = titanDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); - assertTrue(byCriteria.isRight()); - assertEquals("check one result returned due to titan bug", TitanOperationStatus.NOT_FOUND, - byCriteria.right().value()); - - // one result where isAbstract != true - byCriteria = titanDao.getByCriteria(NodeTypeEnum.Resource, null, props, ResourceMetadataData.class); - assertTrue(byCriteria.isLeft()); - assertEquals("check one result returned", 1, byCriteria.left().value().size()); - - props.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), false); - byCriteria = titanDao.getByCriteria(NodeTypeEnum.Resource, null, props, ResourceMetadataData.class); - assertTrue(byCriteria.isRight()); - assertEquals("check one result returned due to titan bug", TitanOperationStatus.NOT_FOUND, - byCriteria.right().value()); - - titanDao.rollback(); - - } - -} diff --git a/catalog-dao/src/test/resources/application-context-test.xml b/catalog-dao/src/test/resources/application-context-test.xml index 24980dfecd..c07512f92c 100644 --- a/catalog-dao/src/test/resources/application-context-test.xml +++ b/catalog-dao/src/test/resources/application-context-test.xml @@ -13,7 +13,7 @@ org.openecomp.sdc.be.dao.impl, org.openecomp.sdc.be.dao.es, org.openecomp.sdc.be.dao.neo4j, - org.openecomp.sdc.be.dao.titan, + org.openecomp.sdc.be.dao.janusgraph, org.openecomp.sdc.be.resources.impl "> diff --git a/catalog-dao/src/test/resources/config/catalog-dao/configuration.yaml b/catalog-dao/src/test/resources/config/catalog-dao/configuration.yaml index 67c0ec7b20..92cf2a3242 100644 --- a/catalog-dao/src/test/resources/config/catalog-dao/configuration.yaml +++ b/catalog-dao/src/test/resources/config/catalog-dao/configuration.yaml @@ -25,9 +25,9 @@ beSslPort: 8443 version: 1.0 released: 2012-11-30 -titanCfgFile: src/main/resources/config/titan.properties -titanInMemoryGraph: true -titanLockTimeout: 30 +janusGraphCfgFile: src/main/resources/config/janusgraph.properties +janusGraphInMemoryGraph: true +janusGraphLockTimeout: 30 # Protocols protocols: diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java index 7f5ea06b97..d8b3295f51 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java @@ -282,7 +282,7 @@ public class HealthCheckService { healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_FE, UP, getAppVersion(), "OK")); healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, null)); - healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, UNKNOWN, null, null)); + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_JANUSGRAPH, UNKNOWN, null, null)); healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_CASSANDRA, UNKNOWN, null, null)); healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_DISTRIBUTION_ENGINE, UNKNOWN, null, null)); healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_ON_BOARDING, UNKNOWN, null, null)); diff --git a/catalog-model/pom.xml b/catalog-model/pom.xml index c5db734701..a28a040640 100644 --- a/catalog-model/pom.xml +++ b/catalog-model/pom.xml @@ -105,11 +105,10 @@ provided - - com.thinkaurelius.titan - titan-core - ${titan.version} + org.janusgraph + janusgraph-core + ${janusgraph.version} provided @@ -132,9 +131,9 @@ - org.onap.sdc.sdc-titan-cassandra - sdc-titan-cassandra - ${sdc.titan.version} + org.janusgraph + janusgraph-cassandra + ${janusgraph.version} provided @@ -143,7 +142,6 @@ - org.apache.commons diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/config/CatalogModelSpringConfig.java b/catalog-model/src/main/java/org/openecomp/sdc/be/config/CatalogModelSpringConfig.java index 6ba7a35836..5b9cf67dc1 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/config/CatalogModelSpringConfig.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/config/CatalogModelSpringConfig.java @@ -8,8 +8,8 @@ import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan({"org.openecomp.sdc.be.model.operations.impl", "org.openecomp.sdc.be.model.cache", - "org.openecomp.sdc.be.model.jsontitan.utils", - "org.openecomp.sdc.be.model.jsontitan.operations", + "org.openecomp.sdc.be.model.jsonjanusgraph.utils", + "org.openecomp.sdc.be.model.jsonjanusgraph.operations", "org.openecomp.sdc.be.dao.cassandra" }) public class CatalogModelSpringConfig { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java index b65997cb35..0a77ecd471 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java @@ -48,7 +48,7 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import static java.util.stream.Collectors.toMap; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java index 5104a172b5..5a670890a9 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java @@ -21,13 +21,13 @@ package org.openecomp.sdc.be.model; import fj.data.Either; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import java.util.List; public interface DerivedNodeTypeResolver { - Either, TitanOperationStatus> findDerivedResources(String parentResource); + Either, JanusGraphOperationStatus> findDerivedResources(String parentResource); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java index 3c1ca26879..4920d4f10c 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java @@ -23,17 +23,13 @@ package org.openecomp.sdc.be.model; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; import java.util.HashMap; -import java.util.List; import java.util.Map; import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.InstantiationTypes; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; - -import java.util.HashMap; -import java.util.Map; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; public class Service extends Component { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationCache.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationCache.java index e9b7f7a2e5..e70ab0ec63 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationCache.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationCache.java @@ -21,14 +21,14 @@ package org.openecomp.sdc.be.model.cache; import fj.data.Either; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import java.util.Map; public interface ApplicationCache { - public abstract Either, TitanOperationStatus> getAll(); + public abstract Either, JanusGraphOperationStatus> getAll(); - public abstract Either get(String uniqueId); + public abstract Either get(String uniqueId); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java index 94992111d3..fb49762736 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java @@ -28,7 +28,7 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.config.Configuration.ApplicationL1CacheConfig; import org.openecomp.sdc.be.config.Configuration.ApplicationL1CacheInfo; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; @@ -146,7 +146,7 @@ public class ApplicationDataTypeCache implements ApplicationCache, TitanOperationStatus> getAllDataTypesFromGraph() { + private Either, JanusGraphOperationStatus> getAllDataTypesFromGraph() { return propertyOperation .getAllDataTypes(); @@ -154,7 +154,7 @@ public class ApplicationDataTypeCache implements ApplicationCache, TitanOperationStatus> getAll() { + public Either, JanusGraphOperationStatus> getAll() { try { @@ -171,7 +171,7 @@ public class ApplicationDataTypeCache implements ApplicationCache get(String uniqueId) { + public Either get(String uniqueId) { try { r.lock(); @@ -202,12 +202,12 @@ public class ApplicationDataTypeCache implements ApplicationCache, TitanOperationStatus> allDataTypeNodes = propertyOperation.getAllDataTypeNodes(); + Either, JanusGraphOperationStatus> allDataTypeNodes = propertyOperation.getAllDataTypeNodes(); Long end = System.currentTimeMillis(); log.trace("Finish fetching all data types from db. Took {} Milliseconds", (end - start)); if (allDataTypeNodes.isRight()) { - TitanOperationStatus status = allDataTypeNodes.right().value(); - if (status != TitanOperationStatus.OK) { + JanusGraphOperationStatus status = allDataTypeNodes.right().value(); + if (status != JanusGraphOperationStatus.OK) { log.debug("ApplicationDataTypesCache - Failed to fetch all data types nodes"); BeEcompErrorManager.getInstance().logInternalConnectionError("FetchDataTypes", "Failed to fetch data types from graph(cache)", ErrorSeverity.INFO); @@ -251,7 +251,7 @@ public class ApplicationDataTypeCache implements ApplicationCache, TitanOperationStatus> allDataTypes = propertyOperation + Either, JanusGraphOperationStatus> allDataTypes = propertyOperation .getAllDataTypes(); if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); + JanusGraphOperationStatus status = allDataTypes.right().value(); log.debug("Failed to fetch all data types from db. Status is {}", status); } else { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ComponentCache.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ComponentCache.java index b17a66434a..0fea33e8e5 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ComponentCache.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ComponentCache.java @@ -37,7 +37,7 @@ 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.model.*; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.resources.data.ComponentCacheData; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.SerializationUtils; @@ -54,10 +54,6 @@ import java.util.stream.Collectors; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.function.Function; -import java.util.stream.Collectors; @org.springframework.stereotype.Component("component-cache") public class ComponentCache { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/DaoInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/DaoInfo.java index 4880afee81..85a7f2ec59 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/DaoInfo.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/DaoInfo.java @@ -20,7 +20,7 @@ package org.openecomp.sdc.be.model.cache; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; public class DaoInfo { private ToscaOperationFacade toscaOperationFacade; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/workers/SyncWorker.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/workers/SyncWorker.java index 7af806f55c..cd78063780 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/workers/SyncWorker.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/workers/SyncWorker.java @@ -22,7 +22,7 @@ package org.openecomp.sdc.be.model.cache.workers; import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation; @@ -85,7 +85,7 @@ public class SyncWorker implements Runnable, IWorker { log.debug("sync worker:{} encounered an exception", workerName); log.debug("exception", e); } finally { - this.cacheMangerOperation.getTitanGenericDao().commit(); + this.cacheMangerOperation.getJanusGraphGenericDao().commit(); } } @@ -97,11 +97,11 @@ public class SyncWorker implements Runnable, IWorker { private void clearCacheRecords() { cacheIdAndTimeMap.forEach((k, v) -> { try { - Either componentFromGraphRes = getComponentMetaData(k, + Either componentFromGraphRes = getComponentMetaData(k, NodeTypeEnum.getByName(v.getType())); if (componentFromGraphRes.isRight()) { - TitanOperationStatus error = componentFromGraphRes.right().value(); - if (TitanOperationStatus.NOT_FOUND.equals(error)) { + JanusGraphOperationStatus error = componentFromGraphRes.right().value(); + if (JanusGraphOperationStatus.NOT_FOUND.equals(error)) { long delay = System.currentTimeMillis() - v.getModificationTime().getTime(); if (delay > updateDelayInMilliseconds) { this.cacheMangerOperation.deleteComponentInCache(k, v.getModificationTime().getTime(), @@ -148,11 +148,11 @@ public class SyncWorker implements Runnable, IWorker { private void syncCacheByComponentType(NodeTypeEnum nodeTypeEnum) { if (!this.shutdown) { log.trace("syncCache records of type:{} .", nodeTypeEnum); - Either, TitanOperationStatus> getAllResult = getAllComponentsMetaData( + Either, JanusGraphOperationStatus> getAllResult = getAllComponentsMetaData( nodeTypeEnum); List componentList = new ArrayList<>(); - if (getAllResult.isRight() && !TitanOperationStatus.NOT_FOUND.equals(getAllResult.right().value())) { - log.debug("error while trying to get all components of type:{} TitanOperationStatus:{}.", nodeTypeEnum, + if (getAllResult.isRight() && !JanusGraphOperationStatus.NOT_FOUND.equals(getAllResult.right().value())) { + log.debug("error while trying to get all components of type:{} JanusGraphOperationStatus:{}.", nodeTypeEnum, getAllResult.right().value()); return; } @@ -243,9 +243,9 @@ public class SyncWorker implements Runnable, IWorker { * @return a list of retrieved nodes matching the given type or not found in * case no nodes were found or error in case of failure */ - private Either, TitanOperationStatus> getAllComponentsMetaData( + private Either, JanusGraphOperationStatus> getAllComponentsMetaData( NodeTypeEnum nodeTypeEnum) { - return this.cacheMangerOperation.getTitanGenericDao().getByCriteria(nodeTypeEnum, null, + return this.cacheMangerOperation.getJanusGraphGenericDao().getByCriteria(nodeTypeEnum, null, ComponentMetadataData.class); } @@ -259,9 +259,9 @@ public class SyncWorker implements Runnable, IWorker { * @return the meta dat of the component or the error encountered during the * get */ - private Either getComponentMetaData(String uid, - NodeTypeEnum nodeTypeEnum) { - return this.cacheMangerOperation.getTitanGenericDao().getNode(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), + private Either getComponentMetaData(String uid, + NodeTypeEnum nodeTypeEnum) { + return this.cacheMangerOperation.getJanusGraphGenericDao().getNode(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), uid, ComponentMetadataData.class); } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeType.java new file mode 100644 index 0000000000..9c3b76d556 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeType.java @@ -0,0 +1,71 @@ +/*- + * ============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.jsonjanusgraph.datamodel; + +import org.openecomp.sdc.be.datatypes.elements.*; + +import java.util.List; +import java.util.Map; + +public class NodeType extends ToscaElement{ + + public NodeType() { + super(ToscaElementTypeEnum.NODE_TYPE); + } + + private List derivedFrom; + private List derivedList; + private Map attributes; + private Map interfaceArtifacts; + + public List getDerivedList() { + return derivedList; + } + + public void setDerivedList(List derivedList) { + this.derivedList = derivedList; + } + + public List getDerivedFrom() { + return derivedFrom; + } + + public void setDerivedFrom(List derivedFrom) { + this.derivedFrom = derivedFrom; + } + + public Map getAttributes() { + return attributes; + } + + public void setAttributes(Map attributes) { + this.attributes = attributes; + } + + public Map getInterfaceArtifacts() { + return interfaceArtifacts; + } + + public void setInterfaceArtifacts(Map interfaceArtifacts) { + this.interfaceArtifacts = interfaceArtifacts; + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/TopologyTemplate.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/TopologyTemplate.java new file mode 100644 index 0000000000..a02b07df15 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/TopologyTemplate.java @@ -0,0 +1,310 @@ +/*- + * ============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.jsonjanusgraph.datamodel; + +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.MapInterfaceInstanceDataDefinition; +import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum; + +import java.util.HashMap; +import java.util.Map; + +public class TopologyTemplate extends ToscaElement{ + + public TopologyTemplate() { + super(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE); + } + private Map inputs; + private Map instInputs; + private Map heatParameters; + private Map instAttributes; + private Map instProperties; + private Map groups; + private Map policies; + private Map instGroups; + private Map serviceApiArtifacts; + private Map forwardingPaths; + private Map compositions; + private Map calculatedCapabilities; + private Map calculatedRequirements; + private Map fullfilledCapabilities; + private Map fullfilledRequirements; + private Map calculatedCapabilitiesProperties; + private Map instDeploymentArtifacts; + private Map instanceArtifacts; + private Map interfaces; + private Map instInterfaces; + private Map componentInstInterfaces; + private Map dataTypes; + + private Map nodeFilterComponents; + //Component Instances External References (instanceId -> ExternalRefsMap) + //----------------------------------------------------------------------- + private Map mapComponentInstancesExternalRefs; + + public Map getMapComponentInstancesExternalRefs() { + return this.mapComponentInstancesExternalRefs; + } + + public void setComponentInstancesExternalRefs(Map mapComponentInstancesExternalRefs) { + this.mapComponentInstancesExternalRefs = mapComponentInstancesExternalRefs; + } + //----------------------------------------------------------------------- + + public Map getInterfaces() { + return interfaces; + } + + public void setInterfaces(Map interfaces) { + this.interfaces = interfaces; + } + + public Map getInstInterfaces() { + return instInterfaces; + } + + public void setInstInterfaces( + Map instInterfaces) { + this.instInterfaces = instInterfaces; + } + + public void addInstInterface(String compId, MapInterfaceInstanceDataDefinition + mapInterfaceInstanceDataDefinition) { + if(MapUtils.isEmpty(this.instInterfaces)) { + this.instInterfaces = new HashMap<>(); + } + + this.instInterfaces.put(compId, mapInterfaceInstanceDataDefinition); + } + + public Map getComponentInstInterfaces() { + return componentInstInterfaces; + } + + public void setComponentInstInterfaces( + Map componentInstInterfaces) { + this.componentInstInterfaces = componentInstInterfaces; + } + + public void addComponentInstanceInterfaceMap(String componentInstanceId, MapInterfaceDataDefinition + mapInterfaceDataDefinition) { + if(MapUtils.isEmpty(this.componentInstInterfaces)) { + this.componentInstInterfaces = new HashMap<>(); + } + + this.componentInstInterfaces.put(componentInstanceId, mapInterfaceDataDefinition); + } + + + public Map getInputs() { + return inputs; + } + public void setInputs(Map inputs) { + this.inputs = inputs; + } + public Map getInstInputs() { + return instInputs; + } + public void setInstInputs(Map instInputs) { + this.instInputs = instInputs; + } + public Map getHeatParameters() { + return heatParameters; + } + public void setHeatParameters(Map heatParameters) { + this.heatParameters = heatParameters; + } + public Map getInstAttributes() { + return instAttributes; + } + public void setInstAttributes(Map instAttributes) { + this.instAttributes = instAttributes; + } + public Map getInstProperties() { + return instProperties; + } + public void setInstProperties(Map instProperties) { + this.instProperties = instProperties; + } + public Map getGroups() { + return groups; + } + public void setGroups(Map groups) { + this.groups = groups; + } + public Map getPolicies() { + return policies; + } + public void setPolicies(Map policies) { + this.policies = policies; + } + public Map getInstGroups() { + return instGroups; + } + public void setInstGroups(Map instGroups) { + this.instGroups = instGroups; + } + public Map getServiceApiArtifacts() { + return serviceApiArtifacts; + } + public void setServiceApiArtifacts(Map serviceApiArtifacts) { + this.serviceApiArtifacts = serviceApiArtifacts; + } + public Map getCompositions() { + return compositions; + } + public void setCompositions(Map compositions) { + this.compositions = compositions; + } + public Map getCalculatedCapabilities() { + return calculatedCapabilities; + } + public void setCalculatedCapabilities(Map calculatedCapabilities) { + this.calculatedCapabilities = calculatedCapabilities; + } + public Map getCalculatedRequirements() { + return calculatedRequirements; + } + public void setCalculatedRequirements(Map calculatedRequirements) { + this.calculatedRequirements = calculatedRequirements; + } + public Map getFullfilledCapabilities() { + return fullfilledCapabilities; + } + public void setFullfilledCapabilities(Map fullfilledCapabilities) { + this.fullfilledCapabilities = fullfilledCapabilities; + } + public Map getFullfilledRequirements() { + return fullfilledRequirements; + } + public void setFullfilledRequirements(Map fullfilledRequirements) { + this.fullfilledRequirements = fullfilledRequirements; + } + + public Map getInstDeploymentArtifacts() { + return instDeploymentArtifacts; + } + public void setInstDeploymentArtifacts(Map instDeploymentArtifacts) { + this.instDeploymentArtifacts = instDeploymentArtifacts; + } + + public Map getCalculatedCapabilitiesProperties() { + return calculatedCapabilitiesProperties; + } + public void setCalculatedCapabilitiesProperties(Map calculatedCapabilitiesProperties) { + this.calculatedCapabilitiesProperties = calculatedCapabilitiesProperties; + } + + public Map getInstanceArtifacts() { + return instanceArtifacts; + } + public void setInstanceArtifacts(Map instanceArtifacts) { + this.instanceArtifacts = instanceArtifacts; + } + + public Map getForwardingPaths() { + return forwardingPaths; + } + + public void setForwardingPaths(Map forwardingPaths) { + this.forwardingPaths = forwardingPaths; + } + + public Map getNodeFilterComponents() { + return nodeFilterComponents; + } + + public void setNodeFilterComponents(Map nodeFilters) { + this.nodeFilterComponents = nodeFilters; + } + + /** + * Gets data types. + * @return Current data types. + */ + public Map getDataTypes() { + return dataTypes; + } + + /** + * Sets data types. + * @param dataTypes New data types. + */ + public void setDataTypes(Map dataTypes) { + this.dataTypes = dataTypes; + } + + /** + * Adds component instance to composition of topology template + * Note that component instance will be overrided in case if the topology template already contains a component instance with the same name + * @param componentInstance + */ + public void addComponentInstance(ComponentInstanceDataDefinition componentInstance){ + if(getCompositions() == null){ + compositions = new HashMap<>(); + } + if(MapUtils.isEmpty(getCompositions())){ + compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), new CompositionDataDefinition()); + } + if(MapUtils.isEmpty(getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances())){ + getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).setComponentInstances(new HashMap<>()); + } + getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances().put(componentInstance.getUniqueId(), componentInstance); + } + /** + * Returns map of component instances from composition + * @return + */ + public Map getComponentInstances() { + Map instances = null; + if(getCompositions() != null && getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()) != null ){ + instances = getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances(); + } + return instances; + } + + + /** + * Sets map of component instances to composition of topology template + * Note that component instances will be overrided in case if the topology template already contains a component instances + * @param instances + */ + public void setComponentInstances(Map instances) { + if(getCompositions() == null){ + compositions = new HashMap<>(); + } + if(MapUtils.isEmpty(getCompositions())){ + compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), new CompositionDataDefinition()); + } + getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).setComponentInstances(instances); + } + public Map getRelations() { + Map relations = null; + if( getCompositions() != null && getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()) != null ){ + relations = getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getRelations(); + } + return relations; + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java new file mode 100644 index 0000000000..7685d1c348 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java @@ -0,0 +1,344 @@ +/*- + * ============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.jsonjanusgraph.datamodel; + +import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTypeOperation; +import org.slf4j.MDC; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +public abstract class ToscaElement { + + protected Map metadata; + protected List categories; + protected Map toscaArtifacts; + private Map artifacts; + private Map deploymentArtifacts; + private Map additionalInformation; + private Map properties; + private Map capabilities; + private Map capabiltiesProperties; + private Map requirements; + + protected ToscaElementTypeEnum toscaType; + // User + private String creatorUserId; + private String creatorFullName; + private String lastUpdaterUserId; + private String lastUpdaterFullName; + + private Map allVersions; + + public ToscaElement(ToscaElementTypeEnum toscaType){ + this.toscaType = toscaType; + } + + public Map getMetadata() { + return metadata; + } + + public void setMetadata(Map metadata) { + this.metadata = metadata; + } + + public List getCategories() { + return categories; + } + + public void setCategories(List categories) { + this.categories = categories; + } + public Map getToscaArtifacts() { + return toscaArtifacts; + } + + public void setToscaArtifacts(Map toscaArtifacts) { + this.toscaArtifacts = toscaArtifacts; + } + + public ToscaElementTypeEnum getToscaType() { + return toscaType; + } + + public void setToscaType(ToscaElementTypeEnum toscaType) { + this.toscaType = toscaType; + } + public Map getArtifacts() { + return artifacts; + } + + public void setArtifacts(Map artifacts) { + this.artifacts = artifacts; + } + + public Map getDeploymentArtifacts() { + return deploymentArtifacts; + } + + public void setDeploymentArtifacts(Map deploymentArtifacts) { + this.deploymentArtifacts = deploymentArtifacts; + } + public Map getAdditionalInformation() { + return additionalInformation; + } + public void setAdditionalInformation(Map additionalInformation) { + this.additionalInformation = additionalInformation; + } + public Map getProperties() { + return properties; + } + public void setProperties(Map properties) { + this.properties = properties; + } + + public Map getAllVersions() { + return allVersions; + } + + public void setAllVersions(Map allVersions) { + this.allVersions = allVersions; + } + + public Map getCapabilities() { + return capabilities; + } + + public void setCapabilities(Map capabilities) { + this.capabilities = capabilities; + } + + public Map getRequirements() { + return requirements; + } + + public void setRequirements(Map requirements) { + this.requirements = requirements; + } + + public Map getCapabilitiesProperties() { + return capabiltiesProperties; + } + + public void setCapabilitiesProperties(Map capabiltiesProperties) { + this.capabiltiesProperties = capabiltiesProperties; + } + + // metadata properties + // ---------------------------- + public Object getMetadataValue(JsonPresentationFields name) { + return getMetadataValueOrDefault(name, null); + } + + public Object getMetadataValueOrDefault(JsonPresentationFields name, Object defaultVal) { + if (metadata != null) { + return metadata.getOrDefault(name.getPresentation(), defaultVal); + } + return null; + } + + public void setMetadataValue(JsonPresentationFields name, Object value) { + if (metadata == null) { + metadata = new HashMap<>(); + } + metadata.put(name.getPresentation(), value); + + } + // -------------------- + public String getUUID() { + return (String) getMetadataValue(JsonPresentationFields.UUID); + } + + public void setUUID(String uuid) { + setMetadataValue(JsonPresentationFields.UUID, uuid); + } + + public String getVersion() { + return (String) getMetadataValue(JsonPresentationFields.VERSION); + } + + public String getNormalizedName() { + return (String) getMetadataValue(JsonPresentationFields.NORMALIZED_NAME); + } + + public void setNormalizedName(String normaliseComponentName) { + setMetadataValue(JsonPresentationFields.NORMALIZED_NAME, normaliseComponentName); + } + + public String getName() { + return (String) getMetadataValue(JsonPresentationFields.NAME); + } + + public String getSystemName() { + return (String) getMetadataValue(JsonPresentationFields.SYSTEM_NAME); + } + public void setSystemName(String systemName) { + setMetadataValue(JsonPresentationFields.SYSTEM_NAME, systemName); + } + + public void setLifecycleState(LifecycleStateEnum state) { + if(state != null) + setMetadataValue(JsonPresentationFields.LIFECYCLE_STATE, state.name()); + } + + public LifecycleStateEnum getLifecycleState() { + return LifecycleStateEnum.findState( (String) getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); + } + + public Long getCreationDate() { + return (Long) getMetadataValue(JsonPresentationFields.CREATION_DATE); + } + + public void setCreationDate(Long currentDate) { + setMetadataValue(JsonPresentationFields.CREATION_DATE, currentDate); + } + + public void setLastUpdateDate(Long currentDate) { + setMetadataValue(JsonPresentationFields.LAST_UPDATE_DATE, currentDate); + } + public Long getLastUpdateDate() { + return (Long) getMetadataValue(JsonPresentationFields.LAST_UPDATE_DATE); + } + + public String getUniqueId() { + return (String) getMetadataValue(JsonPresentationFields.UNIQUE_ID); + } + public void setUniqueId(String uniqueId) { + setMetadataValue(JsonPresentationFields.UNIQUE_ID, uniqueId); + } + + public void setHighestVersion(Boolean isHighest) { + setMetadataValue(JsonPresentationFields.HIGHEST_VERSION, isHighest); + + } + public Boolean isHighestVersion() { + return (Boolean) getMetadataValue(JsonPresentationFields.HIGHEST_VERSION); + + } + public ResourceTypeEnum getResourceType() { + String resourceType = (String) getMetadataValue(JsonPresentationFields.RESOURCE_TYPE); + return resourceType != null ? ResourceTypeEnum.valueOf(resourceType) : null; + } + + public void setResourceType(ResourceTypeEnum resourceType) { + if(resourceType != null) + setMetadataValue(JsonPresentationFields.RESOURCE_TYPE, resourceType.name()); + } + + public ComponentTypeEnum getComponentType() { + return ComponentTypeEnum.valueOf((String) getMetadataValue(JsonPresentationFields.COMPONENT_TYPE)); + } + + public void setComponentType(ComponentTypeEnum componentType) { + if(componentType != null) + setMetadataValue(JsonPresentationFields.COMPONENT_TYPE, componentType.name()); + } + + public String getDerivedFromGenericType(){ + return (String) getMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_TYPE); + } + + public void setDerivedFromGenericType(String derivedFromGenericType){ + setMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_TYPE, derivedFromGenericType); + } + + public String getDerivedFromGenericVersion(){ + return (String) getMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_VERSION); + } + + public void setDerivedFromGenericVersion(String derivedFromGenericVersion){ + setMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_VERSION, derivedFromGenericVersion); + } + + public Boolean isArchived() { return (Boolean) getMetadataValue(JsonPresentationFields.IS_ARCHIVED); } + + public void setArchived(Boolean archived) { setMetadataValue(JsonPresentationFields.IS_ARCHIVED, archived); } + + public Long getArchiveTime() { + Object archiveTime = getMetadataValue(JsonPresentationFields.ARCHIVE_TIME); + if (archiveTime instanceof Integer){ + return new Long((Integer)getMetadataValue(JsonPresentationFields.ARCHIVE_TIME)); + } + return (Long)archiveTime; + } + + public void setArchiveTime(Long archiveTime) { setMetadataValue(JsonPresentationFields.ARCHIVE_TIME, archiveTime); } + + public Boolean isVspArchived() { return (Boolean) getMetadataValue(JsonPresentationFields.IS_VSP_ARCHIVED); } + + public void setVspArchived(Boolean vspArchived) { setMetadataValue(JsonPresentationFields.IS_VSP_ARCHIVED, vspArchived); } + + public String getCreatorUserId() { + return creatorUserId; + } + + public void setCreatorUserId(String creatorUserId) { + this.creatorUserId = creatorUserId; + } + + public String getCreatorFullName() { + return creatorFullName; + } + + public void setCreatorFullName(String creatorFullName) { + this.creatorFullName = creatorFullName; + } + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } + + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } + + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } + + public void generateUUID() { + String prevUUID = getUUID(); + String version = getVersion(); + if ((prevUUID == null && NodeTypeOperation.uuidNormativeNewVersion.matcher(version).matches()) || NodeTypeOperation.uuidNewVersion.matcher(version).matches()) { + UUID uuid = UUID.randomUUID(); + setUUID(uuid.toString()); + MDC.put("serviceInstanceID", uuid.toString()); + } + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElementTypeEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElementTypeEnum.java new file mode 100644 index 0000000000..1e3620ba14 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElementTypeEnum.java @@ -0,0 +1,49 @@ +/*- + * ============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.jsonjanusgraph.datamodel; + +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; + +public enum ToscaElementTypeEnum { + NODE_TYPE("node_type"), + TOPOLOGY_TEMPLATE("topology_template"); + + String value; + private ToscaElementTypeEnum(String value){ + this.value = value; + } + + public static VertexTypeEnum getVertexTypeByToscaType(ToscaElementTypeEnum toscaType ){ + switch ( toscaType ){ + case NODE_TYPE : + return VertexTypeEnum.NODE_TYPE; + case TOPOLOGY_TEMPLATE : + return VertexTypeEnum.TOPOLOGY_TEMPLATE; + default : + return null; + } + } + + public String getValue() { + return value; + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/enums/JsonConstantKeysEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/enums/JsonConstantKeysEnum.java new file mode 100644 index 0000000000..308f2db445 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/enums/JsonConstantKeysEnum.java @@ -0,0 +1,42 @@ +/*- + * ============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.jsonjanusgraph.enums; + +public enum JsonConstantKeysEnum { + + COMPOSITION("composition"), + CAPABILITIES("capabilities"), + REQUIREMENTS("requirements"), + PROPERTIES("properties"), + INPUTS("inputs"), + GROUPS("groups"), + INSTANCE_PROPERIES("instanceProperties"); + + private String value; + + private JsonConstantKeysEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperation.java new file mode 100644 index 0000000000..3f2b41e3b5 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperation.java @@ -0,0 +1,292 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum; +import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArchiveOperation.Action.ARCHIVE; +import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArchiveOperation.Action.RESTORE; + +/** + * Created by yavivi on 25/03/2018. + */ +@Component +public class ArchiveOperation extends BaseOperation { + + private static final Logger log = Logger.getLogger(ArchiveOperation.class.getName()); + + @Autowired + private IGraphLockOperation graphLockOperation; + + public enum Action { + ARCHIVE, RESTORE; + } + + public ArchiveOperation(JanusGraphDao janusGraphDao, IGraphLockOperation graphLockOperation){ + this.janusGraphDao = janusGraphDao; + this.graphLockOperation = graphLockOperation; + } + + public Either, ActionStatus> archiveComponent(String componentId) { + final Either vertexResult = this.janusGraphDao.getVertexById(componentId); + if (vertexResult.isLeft()){ + return doAction(ARCHIVE, vertexResult.left().value()); + } else { + return Either.right(onError(ARCHIVE.name(), componentId, vertexResult.right().value())); + } + } + + public Either, ActionStatus> restoreComponent(String componentId) { + final Either vertexResult = this.janusGraphDao.getVertexById(componentId); + if (vertexResult.isLeft()){ + return doAction(RESTORE, vertexResult.left().value()); + } else { + return Either.right(onError(RESTORE.name(), componentId, vertexResult.right().value())); + } + } + + public ActionStatus onVspRestored(String csarId){ + return onVspStateChanged(RESTORE, csarId); + } + + public ActionStatus onVspArchived(String csarId){ + return onVspStateChanged(ARCHIVE, csarId); + } + + private ActionStatus onVspStateChanged(Action action, String csarId) { + Map props = new HashMap<>(); + props.put(GraphPropertyEnum.CSAR_UUID, csarId); + Either, JanusGraphOperationStatus> vfsE = janusGraphDao + .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props); + return vfsE.either(vList -> setVspArchived(action, vList), s -> onError("VSP_"+action.name(), csarId, s)); + } + + private ActionStatus setVspArchived(Action action, List vList) { + if (!vList.isEmpty()) { + //Find & Lock the highest version component + GraphVertex highestVersion = this.getHighestVersionFrom(vList.get(0)); + StorageOperationStatus lockStatus = this.graphLockOperation.lockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType()); + if (lockStatus != StorageOperationStatus.OK){ + return onError(action.name(), highestVersion.getUniqueId(), JanusGraphOperationStatus.ALREADY_LOCKED); + } + + try { + //Set isVspArchived flag + for (GraphVertex v : vList) { + boolean val = action == ARCHIVE ? true : false; + v.setJsonMetadataField(JsonPresentationFields.IS_VSP_ARCHIVED, val); + v.addMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED, val); + janusGraphDao.updateVertex(v); + } + return commitAndCheck("VSP_"+action.name(), vList.toString()); + } finally { + this.graphLockOperation.unlockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType()); + } + + } + return ActionStatus.OK; + } + + public List setArchivedOriginsFlagInComponentInstances(GraphVertex compositionService) { + List ciUidsWithArchivedOrigins = new LinkedList(); + Either, JanusGraphOperationStatus> instanceOfVerticesE = janusGraphDao + .getChildrenVertecies(compositionService, EdgeLabelEnum.INSTANCE_OF, JsonParseFlagEnum.NoParse); + Either, JanusGraphOperationStatus> proxyOfVerticesE = janusGraphDao + .getChildrenVertecies(compositionService, EdgeLabelEnum.PROXY_OF, JsonParseFlagEnum.NoParse); + + List all = new LinkedList<>(); + if (instanceOfVerticesE.isLeft()){ + all.addAll(instanceOfVerticesE.left().value()); + } + if (proxyOfVerticesE.isLeft()){ + all.addAll(proxyOfVerticesE.left().value()); + } + + List archivedOrigins = all.stream().filter(v -> Boolean.TRUE.equals(v.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED))).collect(Collectors.toList()); + List archivedOriginsUids = archivedOrigins.stream().map(GraphVertex::getUniqueId).collect(Collectors.toList()); + + Map compositionsJson = (Map) compositionService.getJson(); + + if (compositionsJson != null) { + CompositionDataDefinition composition = compositionsJson.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + if (composition != null) { + + //Get all component instances from composition + Map componentInstances = composition.getComponentInstances(); + + //Extract component instances uids that has archived origins + ciUidsWithArchivedOrigins = componentInstances. + values(). + stream(). + //filter CIs whose origins are marked as archived (componentUid is in archivedOriginsUids) the second condition handles the PROXY_OF case) + filter(ci -> archivedOriginsUids.contains(ci.getComponentUid()) || archivedOriginsUids.contains(ci.getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID))). + map(ComponentInstanceDataDefinition::getUniqueId).collect(Collectors.toList()); + + //set archived origins flag + componentInstances. + values(). + stream(). + filter(ci -> archivedOriginsUids.contains(ci.getComponentUid()) || archivedOriginsUids.contains(ci.getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID))). + forEach( ci -> ci.setOriginArchived(true)); + + } + } + + return ciUidsWithArchivedOrigins; + } + + private Either, ActionStatus> doAction(Action action, GraphVertex componentVertex){ + + GraphVertex highestVersion = this.getHighestVersionFrom(componentVertex); + + if (action.equals(ARCHIVE) && isInCheckoutState(highestVersion)) { + return Either.right(ActionStatus.INVALID_SERVICE_STATE); + } + + //Lock the Highest Version + StorageOperationStatus lockStatus = this.graphLockOperation.lockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType()); + if (lockStatus != StorageOperationStatus.OK){ + return Either.right(onError(action.name(), componentVertex.getUniqueId(), JanusGraphOperationStatus.ALREADY_LOCKED)); + } + + //Refetch latest version with full parsing + highestVersion = this.janusGraphDao + .getVertexById(highestVersion.getUniqueId(), JsonParseFlagEnum.ParseAll).left().value(); + + try { + //Get Catalog and Archive Roots + GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT).left().value(); + GraphVertex archiveRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.ARCHIVE_ROOT).left().value(); + + if (action == ARCHIVE) { + archiveEdges(catalogRoot, archiveRoot, highestVersion); + } else if (action == RESTORE) { + restoreEdges(catalogRoot, archiveRoot, highestVersion); + } + setPropertiesByAction(highestVersion, action); + janusGraphDao.updateVertex(highestVersion); + + List affectedComponentIds = handleParents(highestVersion, catalogRoot, archiveRoot, action); + ActionStatus sc = commitAndCheck(action.name(), highestVersion.getUniqueId()); + return sc == ActionStatus.OK ? Either.left(affectedComponentIds) : Either.right(sc); + } finally { + this.graphLockOperation.unlockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType()); + } + } + + private ActionStatus commitAndCheck(String action, String componentId) { + JanusGraphOperationStatus status = janusGraphDao.commit(); + if (!status.equals(JanusGraphOperationStatus.OK)){ + return onError(action, componentId, status); + } + return ActionStatus.OK; + } + + private boolean isInCheckoutState(GraphVertex v) { + if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name().equals(v.getMetadataProperty(GraphPropertyEnum.STATE))){ + return true; + } + return false; + } + + /** + * Walks on children until highest version is reached + * @param v + * @return + */ + private GraphVertex getHighestVersionFrom(GraphVertex v) { + Either childVertexE = janusGraphDao + .getChildVertex(v, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + GraphVertex highestVersionVertex = v; + + while (childVertexE.isLeft()) { + highestVersionVertex = childVertexE.left().value(); + childVertexE = janusGraphDao + .getChildVertex(highestVersionVertex, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + } + return highestVersionVertex; + } + + private boolean isHighestVersion(GraphVertex v){ + Boolean highest = (Boolean) v.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); + return highest != null && highest; + } + + private List handleParents(GraphVertex v, GraphVertex catalogRoot, GraphVertex archiveRoot, Action action) { + Either parentVertexE = janusGraphDao + .getParentVertex(v, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll); + List affectedCompIds = new ArrayList(); + affectedCompIds.add(v.getUniqueId()); + + while (parentVertexE.isLeft()){ + GraphVertex cv = parentVertexE.left().value(); + affectedCompIds.add(cv.getUniqueId()); + boolean isHighestVersion = isHighestVersion(cv); + if (isHighestVersion){ + if (action == ARCHIVE) { + archiveEdges(catalogRoot, archiveRoot, cv); + } else { + restoreEdges(catalogRoot, archiveRoot, cv); + } + } + setPropertiesByAction(cv, action); + janusGraphDao.updateVertex(cv); + parentVertexE = janusGraphDao + .getParentVertex(cv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll); + } + return affectedCompIds; + } + + private void archiveEdges(GraphVertex catalogRoot, GraphVertex archiveRoot, GraphVertex v) { + janusGraphDao.deleteAllEdges(catalogRoot, v, EdgeLabelEnum.CATALOG_ELEMENT); + janusGraphDao.createEdge(archiveRoot, v, EdgeLabelEnum.ARCHIVE_ELEMENT, null); + setPropertiesByAction(v, ARCHIVE); + } + + private void restoreEdges(GraphVertex catalogRoot, GraphVertex archiveRoot, GraphVertex v) { + janusGraphDao.deleteAllEdges(archiveRoot, v, EdgeLabelEnum.ARCHIVE_ELEMENT); + janusGraphDao.createEdge(catalogRoot, v, EdgeLabelEnum.CATALOG_ELEMENT, null); + setPropertiesByAction(v, RESTORE); + } + + private void setPropertiesByAction(GraphVertex v, Action action) { + long now = System.currentTimeMillis(); + + boolean isArchived = action == ARCHIVE ? true : false; + v.addMetadataProperty(GraphPropertyEnum.IS_ARCHIVED, isArchived); + v.addMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME, now); + v.setJsonMetadataField(JsonPresentationFields.IS_ARCHIVED, isArchived); + v.setJsonMetadataField(JsonPresentationFields.ARCHIVE_TIME, now); + } + + private ActionStatus onError(String action, String componentId, JanusGraphOperationStatus s) { + ActionStatus ret = ActionStatus.GENERAL_ERROR; + if (s == JanusGraphOperationStatus.NOT_FOUND){ + ret = ActionStatus.RESOURCE_NOT_FOUND; + } else if (s == JanusGraphOperationStatus.ALREADY_LOCKED) { + ret = ActionStatus.COMPONENT_IN_USE; + } + String retCodeVal = ret.name(); + log.error("error occurred when trying to {} {}. Return code is: {}", action, componentId, retCodeVal); + return ret; + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperations.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperations.java new file mode 100644 index 0000000000..46617a563d --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperations.java @@ -0,0 +1,760 @@ +/*- + * ============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.jsonjanusgraph.operations; + +import fj.data.Either; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.tuple.ImmutableTriple; +import org.apache.commons.lang3.tuple.Triple; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.HeatParameterDefinition; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.slf4j.MDC; + +import java.util.*; +import java.util.Map.Entry; +import java.util.stream.Collectors; + +@org.springframework.stereotype.Component("artifacts-operations") + +public class ArtifactsOperations extends BaseOperation { + private static final String FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR = "failed to fetch {} for tosca element with id {}, error {}"; + private static final Logger log = Logger.getLogger(ArtifactsOperations.class.getName()); + + public Either addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, String instanceId) { + + String artifactId = artifactInfo.getUniqueId(); + if (artifactId == null && artifactInfo.getEsId() != null) { + artifactId = artifactInfo.getEsId(); + } + Either status = updateArtifactOnGraph(parentId, artifactInfo, type, artifactId, instanceId, false, false); + if (status.isRight()) { + + log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), parentId, status.right().value()); + BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value())); + return Either.right(status.right().value()); + } else { + + ArtifactDataDefinition artifactData = status.left().value(); + + ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactInfo, artifactData); + log.debug("The returned ArtifactDefintion is {}", artifactDefResult); + return Either.left(artifactDefResult); + } + + } + + public Either updateArtifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId, NodeTypeEnum type, String instanceId) { + + Either status = updateArtifactOnGraph(id, artifactInfo, type, artifactId, instanceId, true, false); + if (status.isRight()) { + + log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), id, status.right().value()); + BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value())); + return Either.right(status.right().value()); + } else { + + ArtifactDataDefinition artifactData = status.left().value(); + + ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactInfo, artifactData); + log.debug("The returned ArtifactDefintion is {}", artifactDefResult); + return Either.left(artifactDefResult); + } + } + + public Either isCloneNeeded(String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum type) { + ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); + + Triple triple = getEdgeLabelEnumFromArtifactGroupType(groupType, type); + EdgeLabelEnum edgeLabelEnum = triple.getLeft(); + return super.isCloneNeeded(parentId, edgeLabelEnum); + } + + public Either getArtifactById(String parentId, String id) { + return getArtifactById(parentId, id, null, null); + } + + public Either getArtifactById(String parentId, String id, ComponentTypeEnum componentType, String containerId) { + Either result = null; + ArtifactDataDefinition foundArtifact = null; + if (componentType != null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + foundArtifact = getInstanceArtifactByLabelAndId(parentId, id, containerId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + if (foundArtifact == null) { + foundArtifact = getInstanceArtifactByLabelAndId(parentId, id, containerId, EdgeLabelEnum.INSTANCE_ARTIFACTS); + } + } + if (foundArtifact == null) { + foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); + } + if (foundArtifact == null) { + foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.TOSCA_ARTIFACTS); + } + + if (foundArtifact == null) { + foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.ARTIFACTS); + } + + if (foundArtifact == null) { + foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.SERVICE_API_ARTIFACTS); + } + if (foundArtifact == null) { + foundArtifact = findInterfaceArtifact(parentId, id); + + } + + if (foundArtifact == null) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + return result; + } + + ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(null, foundArtifact); + return Either.left(artifactDefResult); + + } + private ArtifactDataDefinition findInterfaceArtifact(String parentId, String id) { + Either, JanusGraphOperationStatus> dataFromGraph = getDataFromGraph(parentId, EdgeLabelEnum.INTERFACE); + if (dataFromGraph.isRight()){ + log.debug("failed to fetch interfaces {} for tosca element with id {}, error {}", id, parentId ,dataFromGraph.right().value()); + return null; + } + + Map interfaceDefinitionMap = dataFromGraph.left().value(); + if(interfaceDefinitionMap == null) { + return null; + } + Collection interfaces = interfaceDefinitionMap.values(); + if (interfaces == null){ + return null; + } + for (InterfaceDataDefinition interfaceDataDefinition : interfaces){ + Map operationsMap = interfaceDataDefinition.getOperations(); + if (operationsMap == null) { + return null; + } + ArtifactDataDefinition implementationArtifact = getArtifactDataDefinition(id, operationsMap); + if (implementationArtifact != null) + return implementationArtifact; + } + return null; + } + + private ArtifactDataDefinition getArtifactDataDefinition(String id, + Map operationsMap) { + for(OperationDataDefinition operationDataDefinition : operationsMap.values()){ + ArtifactDataDefinition implementationArtifact = operationDataDefinition.getImplementation(); + if(implementationArtifact != null){ + String uniqueId = implementationArtifact.getUniqueId(); + if (id.equals(uniqueId)) { + return implementationArtifact; + } + } + } + return null; + } + + + public Either removeArifactFromResource(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { + Either status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact); + + if (status.isRight()) { + + log.debug("Failed to delete artifact {} of resource {}", artifactId, id); + + BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete Artifact", artifactId, String.valueOf(status.right().value())); + return Either.right(status.right().value()); + } else { + + return Either.left(status.left().value()); + } + } + + public Either, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) { + + Triple triple = getEdgeLabelEnumFromArtifactGroupType(groupType, parentType); + EdgeLabelEnum edgeLabelEnum = triple.getLeft(); + + Either, JanusGraphOperationStatus> foundArtifact = null; + Map resMap = new HashMap<>(); + foundArtifact = getArtifactByLabel(parentId, instanceId, edgeLabelEnum); + if (foundArtifact.isRight()) { + log.debug("Failed to find artifact in component {} with label {} ", parentId, edgeLabelEnum); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(foundArtifact.right().value())); + } + + resMap.putAll(foundArtifact.left().value()); + + return Either.left(resMap); + } + + /** + * @param parentId the id of the instance container + * @param instanceId the id of the instance of which to return its artifacts + * @return instance and instance deployment artifacts mapped by artifact label name + */ + public Either, StorageOperationStatus> getAllInstanceArtifacts(String parentId, String instanceId) { + Map resMap = new HashMap<>(); + Either, JanusGraphOperationStatus> instArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INSTANCE_ARTIFACTS); + if (instArtifacts.isRight()) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(instArtifacts.right().value())); + } + Either, JanusGraphOperationStatus> deployInstArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + if (deployInstArtifacts.isRight()) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(deployInstArtifacts.right().value())); + } + resMap.putAll(instArtifacts.left().value()); + resMap.putAll(deployInstArtifacts.left().value()); + return Either.left(convertArtifactMapToArtifactDefinitionMap(resMap)); + } + + public Either, StorageOperationStatus> getArtifacts(String parentId) { + + Either, JanusGraphOperationStatus> foundArtifact = null; + Map resMap = new HashMap<>(); + foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.ARTIFACTS); + if (foundArtifact.isLeft()) { + resMap.putAll(foundArtifact.left().value()); + + } + foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); + if (foundArtifact.isLeft()) { + resMap.putAll(foundArtifact.left().value()); + + } + foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.TOSCA_ARTIFACTS); + if (foundArtifact.isLeft()) { + resMap.putAll(foundArtifact.left().value()); + + } + + return Either.left(resMap); + + } + + public Either removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { + + Either artifactData = this.getArtifactById(id, artifactId); + if (artifactData.isRight()) { + log.debug("Failed to find artifact in component {} with id {} ", id, artifactId); + return Either.right(artifactData.right().value()); + } + ArtifactDataDefinition artifactDefinition = artifactData.left().value(); + boolean isMandatory = false; + if ((artifactDefinition.getMandatory() || artifactDefinition.getServiceApi()) && !deleteMandatoryArtifact) { + // return Either.left(artifactData.left().value()); + isMandatory = true; + } + + Triple triple = getEdgeLabelEnumFromArtifactGroupType(artifactDefinition.getArtifactGroupType(), type); + EdgeLabelEnum edgeLabelEnum = triple.getLeft(); + VertexTypeEnum vertexTypeEnum = triple.getRight(); + + if (!isMandatory) { + StorageOperationStatus status = deleteToscaDataElement(id, edgeLabelEnum, vertexTypeEnum, artifactDefinition.getArtifactLabel(), JsonPresentationFields.ARTIFACT_LABEL); + if (status != StorageOperationStatus.OK) + return Either.right(status); + } + + return Either.left(artifactData.left().value()); + + } + + public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion, boolean isUpdate, EdgeLabelEnum edgeLabel) { + if (oldVesrion == null || oldVesrion.isEmpty()) + oldVesrion = "0"; + + String currentChecksum = artifactData.getArtifactChecksum(); + + if (isUpdate) { + ArtifactTypeEnum type = ArtifactTypeEnum.findType(artifactData.getArtifactType()); + switch (type) { + case HEAT_ENV: + if (edgeLabel == EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS) { + generateUUID(artifactData, oldVesrion); + } else { + updateVersionAndDate(artifactData, oldVesrion); + } + break; + case HEAT: + case HEAT_NET: + case HEAT_VOL: + generateUUID(artifactData, oldVesrion); + break; + default: + if (oldChecksum == null || oldChecksum.isEmpty()) { + if (currentChecksum != null) { + generateUUID(artifactData, oldVesrion); + } + } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) { + generateUUID(artifactData, oldVesrion); + } + break; + } + } else { + if (oldChecksum == null || oldChecksum.isEmpty()) { + if (currentChecksum != null) { + generateUUID(artifactData, oldVesrion); + } + } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) { + generateUUID(artifactData, oldVesrion); + } + } + } + + // @TODO add implementation + + public Either, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType) { + return null; + } + + public Either addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String componentId, NodeTypeEnum parentType, boolean failIfExist, String instanceId) { + artifactHeatEnv.setGeneratedFromId(artifactHeat.getUniqueId()); + return addArifactToComponent(artifactHeatEnv, componentId, parentType, failIfExist, instanceId); + } + + public Either getHeatArtifactByHeatEnvId(String parentId, ArtifactDefinition heatEnv, NodeTypeEnum parentType, String containerId, ComponentTypeEnum componentType) { + String id = heatEnv.getGeneratedFromId(); + ComponentTypeEnum compType; + switch (parentType) { + case ResourceInstance: + compType = ComponentTypeEnum.RESOURCE_INSTANCE; + break; + default: + compType = componentType; + } + return getArtifactById(parentId, id, compType, containerId); + } + + public Either updateHeatEnvArtifact(String id, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, String instanceId) { + + Either, JanusGraphOperationStatus> artifactsEither = getArtifactByLabel(id, instanceId, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); + if (artifactsEither.isRight()) { + log.debug("Failed to find artifacts in component {} with id {} ", id, artifactsEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(artifactsEither.right().value())); + } + + Map artifacts = artifactsEither.left().value(); + List envList = artifacts.values().stream().filter(a -> a.getGeneratedFromId() != null && a.getGeneratedFromId().equals(artifactId)).collect(Collectors.toList()); + if (envList != null && !envList.isEmpty()) { + envList.forEach(a -> { + a.setGeneratedFromId(newArtifactId); + updateArtifactOnResource(a, id, a.getUniqueId(), type, instanceId); + + }); + + } + return Either.left(artifactEnvInfo); + } + + public Either updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type) { + return updateArtifactOnResource(artifactInfo, parentId, artifactInfo.getUniqueId(), type, null); + } + + + ///////////////////////////////////////////// private methods //////////////////////////////////////////////////// + + protected ArtifactDefinition convertArtifactDataToArtifactDefinition(ArtifactDefinition artifactInfo, ArtifactDataDefinition artifactDefResult) { + log.debug("The object returned after create property is {}", artifactDefResult); + + ArtifactDefinition propertyDefResult = new ArtifactDefinition(artifactDefResult); + if (artifactInfo != null) + propertyDefResult.setPayload(artifactInfo.getPayloadData()); + + List parameters = new ArrayList<>(); + /* + * StorageOperationStatus heatParametersOfNode = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefResult.getUniqueId().toString(), parameters); if ((heatParametersOfNode.equals(StorageOperationStatus.OK)) + * && !parameters.isEmpty()) { propertyDefResult.setHeatParameters(parameters); } + */ + return propertyDefResult; + } + + private ArtifactDataDefinition getInstanceArtifactByLabelAndId(String parentId, String id, String containerId, EdgeLabelEnum edgeLabelEnum) { + ArtifactDataDefinition foundArtifact = null; + Either, JanusGraphOperationStatus> artifactsEither = getDataFromGraph(containerId, edgeLabelEnum); + if (artifactsEither.isRight()) { + log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, containerId, artifactsEither.right().value()); + return null; + } + + Map artifacts = artifactsEither.left().value(); + + MapArtifactDataDefinition artifactsPerInstance = artifacts.get(parentId); + if (artifactsPerInstance == null) { + log.debug("failed to fetch artifacts for instance {} in tosca element with id {}, error {}", parentId, containerId, artifactsEither.right().value()); + return null; + } + Optional op = artifactsPerInstance.getMapToscaDataDefinition().values().stream().filter(p -> p.getUniqueId().equals(id)).findAny(); + if (op.isPresent()) { + foundArtifact = op.get(); + } + return foundArtifact; + } + + private ArtifactDataDefinition getArtifactByLabelAndId(String parentId, String id, EdgeLabelEnum edgeLabelEnum) { + ArtifactDataDefinition foundArtifact = null; + Either, JanusGraphOperationStatus> artifactsEither = getDataFromGraph(parentId, edgeLabelEnum); + if (artifactsEither.isRight()) { + log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, parentId, artifactsEither.right().value()); + return null; + } + + Map artifacts = artifactsEither.left().value(); + Optional op = artifacts.values().stream().filter(p -> p.getUniqueId().equals(id)).findAny(); + if (op.isPresent()) { + foundArtifact = op.get(); + } + return foundArtifact; + } + + private Either, JanusGraphOperationStatus> getArtifactByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { + Either, JanusGraphOperationStatus> artifactsEither = getArtifactsDataByLabel(parentId, instanceId, edgeLabelEnum); + if (artifactsEither.isRight()) { + log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, parentId, artifactsEither.right().value()); + return Either.right(artifactsEither.right().value()); + } + Map artifactDataMap = artifactsEither.left().value(); + return Either.left(convertArtifactMapToArtifactDefinitionMap(artifactDataMap)); + } + + private Either, JanusGraphOperationStatus> getArtifactsDataByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { + return edgeLabelEnum.isInstanceArtifactsLabel() ? getInstanceArtifactsByLabel(parentId, instanceId, edgeLabelEnum) : getDataFromGraph(parentId, edgeLabelEnum); + } + + private Map convertArtifactMapToArtifactDefinitionMap(Map artifactDataMap) { + Map artMap = new HashMap<>(); + if (artifactDataMap != null && !artifactDataMap.isEmpty()) { + artMap = artifactDataMap.entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> convertArtifactDataToArtifactDefinition(null, e.getValue()))); + } + return artMap; + } + + private Either, JanusGraphOperationStatus> getInstanceArtifactsByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { + Either, JanusGraphOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum); + if (resultEither.isRight()) { + log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, parentId, resultEither.right().value()); + return Either.right(resultEither.right().value()); + } + Map mapArtifacts = resultEither.left().value(); + MapArtifactDataDefinition artifactPerInstance = mapArtifacts.get(instanceId); + return artifactPerInstance != null ? Either.left(artifactPerInstance.getMapToscaDataDefinition()) : Either.left(new HashMap<>()); + } + + private Triple getEdgeLabelEnumFromArtifactGroupType(ArtifactGroupTypeEnum groupType, NodeTypeEnum nodeType) { + EdgeLabelEnum edgeLabelEnum; + VertexTypeEnum vertexTypeEnum; + Boolean isDeepElement = false; + /* + * if (nodeType == NodeTypeEnum.ResourceInstance) { edgeLabelEnum = EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS; vertexTypeEnum = VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS; isDeepElement = true; } else { + */ + switch (groupType) { + case TOSCA: + edgeLabelEnum = EdgeLabelEnum.TOSCA_ARTIFACTS; + vertexTypeEnum = VertexTypeEnum.TOSCA_ARTIFACTS; + break; + case DEPLOYMENT: + if (nodeType == NodeTypeEnum.ResourceInstance) { + edgeLabelEnum = EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS; + vertexTypeEnum = VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS; + isDeepElement = true; + } else { + edgeLabelEnum = EdgeLabelEnum.DEPLOYMENT_ARTIFACTS; + vertexTypeEnum = VertexTypeEnum.DEPLOYMENT_ARTIFACTS; + } + break; + case SERVICE_API: + edgeLabelEnum = EdgeLabelEnum.SERVICE_API_ARTIFACTS; + vertexTypeEnum = VertexTypeEnum.SERVICE_API_ARTIFACTS; + break; + default: + if (nodeType == NodeTypeEnum.ResourceInstance) { + edgeLabelEnum = EdgeLabelEnum.INSTANCE_ARTIFACTS; + vertexTypeEnum = VertexTypeEnum.INSTANCE_ARTIFACTS; + isDeepElement = true; + } else { + edgeLabelEnum = EdgeLabelEnum.ARTIFACTS; + vertexTypeEnum = VertexTypeEnum.ARTIFACTS; + } + break; + } + // } + return new ImmutableTriple<>(edgeLabelEnum, isDeepElement, vertexTypeEnum); + + } + + public Either updateArtifactOnGraph(String componentId, ArtifactDefinition artifactInfo, NodeTypeEnum type, String artifactId, String instanceId, boolean isUpdate, boolean isDeletePlaceholder) { + Either res = null; + ArtifactDataDefinition artifactToUpdate = new ArtifactDataDefinition(artifactInfo); + ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); + + Triple triple = getEdgeLabelEnumFromArtifactGroupType(groupType, type); + EdgeLabelEnum edgeLabelEnum = triple.getLeft(); + VertexTypeEnum vertexTypeEnum = triple.getRight(); + + Either isNeedToCloneEither = isCloneNeeded(componentId, edgeLabelEnum); + if (isNeedToCloneEither.isRight()) { + log.debug("Failed check is clone needed {}", componentId); + return Either.right(isNeedToCloneEither.right().value()); + + } + boolean isNeedToClone = isNeedToCloneEither.left().value(); + + if (artifactId == null || isNeedToClone) { + String uniqueId; + if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { + uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, artifactToUpdate.getArtifactLabel()); + } else { + uniqueId = UniqueIdBuilder.buildInstanceArtifactUniqueId(componentId, instanceId, artifactToUpdate.getArtifactLabel()); + } + artifactToUpdate.setUniqueId(uniqueId); + if (!isDeletePlaceholder) + artifactToUpdate.setEsId(uniqueId); + } else + artifactToUpdate.setUniqueId(artifactId); + + Map artifacts = new HashMap<>(); + Map artifactInst = null; + if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { + + Either, JanusGraphOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum); + + if (artifactsEither.isLeft() && artifactsEither.left().value() != null && !artifactsEither.left().value().isEmpty()) { + artifacts = artifactsEither.left().value(); + if (isNeedToClone && artifacts != null) { + artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE)); + } + } + } else { + + Either, JanusGraphOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum); + if (artifactsEither.isLeft()) { + artifactInst = artifactsEither.left().value(); + if (isNeedToClone && artifactInst != null) { + artifactInst.values().forEach(ma -> ma.getMapToscaDataDefinition().values().forEach(a -> a.setDuplicated(Boolean.TRUE))); + } + MapArtifactDataDefinition artifatcsOnInstance = artifactInst.get(instanceId); + if (artifatcsOnInstance != null) { + artifacts = artifatcsOnInstance.getMapToscaDataDefinition(); + } + } + } + String oldChecksum = null; + String oldVersion = null; + if (artifacts != null && artifacts.containsKey(artifactInfo.getArtifactLabel())) { + ArtifactDataDefinition oldArtifactData = artifacts.get(artifactInfo.getArtifactLabel()); + oldChecksum = oldArtifactData.getArtifactChecksum(); + oldVersion = oldArtifactData.getArtifactVersion(); + //duplicated flag didn't receive from UI, take from DB + artifactToUpdate.setDuplicated(oldArtifactData.getDuplicated()); + + if (isNeedToClone) + artifactToUpdate.setDuplicated(Boolean.FALSE); + else { + if (artifactToUpdate.getDuplicated()) { + String uniqueId = ""; + if(type != NodeTypeEnum.ResourceInstance) + uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, artifactToUpdate.getArtifactLabel()); + else + uniqueId = UniqueIdBuilder.buildInstanceArtifactUniqueId(componentId, instanceId, artifactToUpdate.getArtifactLabel()); + + artifactToUpdate.setUniqueId(uniqueId); + if (!isDeletePlaceholder) + artifactToUpdate.setEsId(uniqueId); + artifactToUpdate.setDuplicated(Boolean.FALSE); + } + } + } + updateUUID(artifactToUpdate, oldChecksum, oldVersion, isUpdate, edgeLabelEnum); + + if (artifactInfo.getPayloadData() == null) { + if (!artifactToUpdate.getMandatory() || artifactToUpdate.getEsId() != null) { + artifactToUpdate.setEsId(artifactToUpdate.getUniqueId()); + } + } else { + if (artifactToUpdate.getEsId() == null) { + artifactToUpdate.setEsId(artifactToUpdate.getUniqueId()); + } + } + + StorageOperationStatus status = StorageOperationStatus.OK; + if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { + List toscaDataList = new ArrayList<>(); + toscaDataList.add(artifactToUpdate); + + if (isNeedToClone && artifacts != null) { + artifacts.values().stream().filter(a -> !a.getArtifactLabel().equals(artifactToUpdate.getArtifactLabel())).forEach(toscaDataList::add); + } + status = updateToscaDataOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataList, JsonPresentationFields.ARTIFACT_LABEL); + } else { + List toscaDataList = new ArrayList<>(); + toscaDataList.add(artifactToUpdate); + List pathKeys = new ArrayList<>(); + pathKeys.add(instanceId); + if (isNeedToClone) { + MapArtifactDataDefinition artifatcsOnInstance = artifactInst.get(instanceId); + if (artifatcsOnInstance != null) { + artifacts = artifatcsOnInstance.getMapToscaDataDefinition(); + artifacts.put(artifactToUpdate.getArtifactLabel(), artifactToUpdate); + } + + for (Entry e : artifactInst.entrySet()) { + List toscaDataListPerInst = e.getValue().getMapToscaDataDefinition().values().stream().collect(Collectors.toList()); + List pathKeysPerInst = new ArrayList<>(); + pathKeysPerInst.add(e.getKey()); + status = updateToscaDataDeepElementsOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.ARTIFACT_LABEL); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to update atifacts group for instance {} in component {} edge type {} error {}", instanceId, componentId, edgeLabelEnum, status); + res = Either.right(status); + break; + } + } + } else { + status = updateToscaDataDeepElementsOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataList, pathKeys, JsonPresentationFields.ARTIFACT_LABEL); + } + } + if (status == StorageOperationStatus.OK) + res = Either.left(artifactToUpdate); + else + res = Either.right(status); + return res; + } + + public void generateUUID(ArtifactDataDefinition artifactData, String oldVesrion) { + + UUID uuid = UUID.randomUUID(); + artifactData.setArtifactUUID(uuid.toString()); + MDC.put("serviceInstanceID", uuid.toString()); + updateVersionAndDate(artifactData, oldVesrion); + } + + private void updateVersionAndDate(ArtifactDataDefinition artifactData, String oldVesrion) { + if (artifactData.getArtifactChecksum() != null) { + long time = System.currentTimeMillis(); + artifactData.setPayloadUpdateDate(time); + } + int newVersion = new Integer(oldVesrion).intValue(); + newVersion++; + artifactData.setArtifactVersion(String.valueOf(newVersion)); + } + + public Either removeArtifactOnGraph(ArtifactDefinition artifactFromGraph, String componentId, String instanceId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { + + Triple triple = getEdgeLabelEnumFromArtifactGroupType(artifactFromGraph.getArtifactGroupType(), type); + EdgeLabelEnum edgeLabelEnum = triple.getLeft(); + VertexTypeEnum vertexTypeEnum = triple.getRight(); + + if (deleteMandatoryArtifact || !(artifactFromGraph.getMandatory() || artifactFromGraph.getServiceApi())) { + StorageOperationStatus status; + if (triple.getMiddle()) { + List pathKeys = new ArrayList<>(); + pathKeys.add(instanceId); + status = deleteToscaDataDeepElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(), pathKeys, JsonPresentationFields.ARTIFACT_LABEL); + } else { + status = deleteToscaDataElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(), JsonPresentationFields.ARTIFACT_LABEL); + } + if (status != StorageOperationStatus.OK) + return Either.right(status); + } + return Either.left(artifactFromGraph); + + } + + public Either deleteArtifactWithCloningOnGraph(String componentId, ArtifactDefinition artifactToDelete, NodeTypeEnum type, String instanceId, boolean deleteMandatoryArtifact) { + + Either result = null; + Triple triple = getEdgeLabelEnumFromArtifactGroupType(artifactToDelete.getArtifactGroupType(), type); + EdgeLabelEnum edgeLabel = triple.getLeft(); + VertexTypeEnum vertexLabel = triple.getRight(); + + Boolean deleteElement = deleteMandatoryArtifact || !(artifactToDelete.getMandatory() || artifactToDelete.getServiceApi()); + Map artifacts = null; + GraphVertex parentVertex = null; + Either, JanusGraphOperationStatus> getArtifactsRes = null; + + Either getToscaElementRes = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon getting tosca data from graph. Status is {}. ", componentId, getToscaElementRes.right().value()); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getToscaElementRes.right().value())); + } + if (result == null) { + parentVertex = getToscaElementRes.left().value(); + getArtifactsRes = this.getDataFromGraph(parentVertex, edgeLabel); + if (getArtifactsRes.isRight()) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getArtifactsRes.right().value())); + } + } + if (result == null) { + artifacts = getArtifactsRes.left().value(); + if (triple.getMiddle()) { + artifacts.values().forEach(ma -> ((MapArtifactDataDefinition) ma).getMapToscaDataDefinition().values().forEach(a -> a.setDuplicated(Boolean.TRUE))); + MapArtifactDataDefinition artifatcsOnInstance = (MapArtifactDataDefinition) artifacts.get(instanceId); + if (artifatcsOnInstance != null && deleteElement) { + artifatcsOnInstance.getMapToscaDataDefinition().remove(artifactToDelete.getArtifactLabel()); + } + } else { + if (deleteElement) { + artifacts.remove(artifactToDelete.getArtifactLabel()); + } + artifacts.values().stream().forEach(a -> ((ArtifactDataDefinition) a).setDuplicated(Boolean.TRUE)); + } + artifactToDelete.setDuplicated(Boolean.TRUE); + } + if (artifacts != null) { + JanusGraphOperationStatus + status = janusGraphDao.deleteEdgeByDirection(parentVertex, Direction.OUT, edgeLabel); + if (status != JanusGraphOperationStatus.OK) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } else if (MapUtils.isNotEmpty(artifacts)) { + Either associateResult = associateElementToData(parentVertex, vertexLabel, edgeLabel, artifacts); + if (associateResult.isRight()) { + result = Either.right(associateResult.right().value()); + } + } + } + if (result == null) { + result = Either.left(artifactToDelete); + } + return result; + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/BaseOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/BaseOperation.java new file mode 100644 index 0000000000..a4fe67eb3f --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/BaseOperation.java @@ -0,0 +1,1518 @@ +/*- + * ============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.jsonjanusgraph.operations; + +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.janusgraph.core.JanusGraphVertex; +import org.openecomp.sdc.be.dao.impl.HealingPipelineDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.operations.StorageException; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +/** + * public abstract class BaseOperation provides base operation functionality and common fields + * + */ +public abstract class BaseOperation { + + private static final String FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS = "Failed remove tosca data vertex of the tosca element {} by label {}. Status is {}. "; + private static final String FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS = "Failed to get child vertex of the tosca element {} by label {}. Status is {}. "; + private static final String FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS = "Failed to get tosca element {} upon adding the properties. Status is {}. "; + private static final Logger log = Logger.getLogger(BaseOperation.class.getName()); + public static final String VF_MODULE = "org.openecomp.groups.VfModule"; + + @Autowired + protected JanusGraphDao janusGraphDao; + + @Autowired + protected NodeTypeOperation nodeTypeOperation; + + @Autowired + protected TopologyTemplateOperation topologyTemplateOperation; + +// @Autowired + protected HealingPipelineDao healingPipelineDao; + + public void setJanusGraphDao(JanusGraphDao janusGraphDao) { + this.janusGraphDao = janusGraphDao; + } + /** + * Returns reference to appropriate toscaTemplateOperation + * + * @param componentType + * @return + */ + public ToscaElementOperation getToscaElementOperation(ComponentTypeEnum componentType) { + ToscaElementOperation operation; + switch (componentType) { + case SERVICE: + case RESOURCE: + operation = topologyTemplateOperation; + break; + default: + operation = nodeTypeOperation; + break; + } + return operation; + } + + /** + * Returns reference to appropriate toscaTemplateOperation + * + * @param toscaElementType + * @return + */ + public ToscaElementOperation getToscaElementOperation(ToscaElementTypeEnum toscaElementType) { + ToscaElementOperation operation; + switch (toscaElementType) { + case TOPOLOGY_TEMPLATE: + operation = topologyTemplateOperation; + break; + case NODE_TYPE: + operation = nodeTypeOperation; + break; + default: + operation = null; + break; + } + return operation; + } + + /** + * Returns reference to appropriate toscaTemplateOperation + * + * @param toscaElementType + * @return + */ + public ToscaElementOperation getToscaElementOperation(VertexTypeEnum toscaElementType) { + ToscaElementOperation operation; + switch (toscaElementType) { + case TOPOLOGY_TEMPLATE: + operation = topologyTemplateOperation; + break; + case NODE_TYPE: + operation = nodeTypeOperation; + break; + default: + operation = null; + break; + } + return operation; + } + /** + * Converts received vertex to User object + * + * @param ownerV + * @return + */ + public User convertToUser(Vertex ownerV) { + User owner = new User(); + owner.setUserId((String) ownerV.property(GraphPropertyEnum.USERID.getProperty()).value()); + VertexProperty property = ownerV.property(GraphPropertyEnum.ROLE.getProperty()); + if(property != null && property.isPresent() ){ + owner.setRole((String) property.value()); + } + + property = ownerV.property(GraphPropertyEnum.FIRST_NAME.getProperty()); + if(property != null && property.isPresent() ){ + owner.setFirstName((String) ownerV.property(GraphPropertyEnum.FIRST_NAME.getProperty()).value()); + } + + property = ownerV.property(GraphPropertyEnum.LAST_NAME.getProperty()); + if( property != null && property.isPresent() ){ + owner.setLastName((String) ownerV.property(GraphPropertyEnum.LAST_NAME.getProperty()).value()); + } + + property = ownerV.property(GraphPropertyEnum.EMAIL.getProperty()); + if( property != null && property.isPresent() ){ + owner.setEmail((String) ownerV.property(GraphPropertyEnum.EMAIL.getProperty()).value()); + } + + property = ownerV.property(GraphPropertyEnum.LAST_LOGIN_TIME.getProperty()); + if( property != null && property.isPresent() ){ + owner.setLastLoginTime((Long) ownerV.property(GraphPropertyEnum.LAST_LOGIN_TIME.getProperty()).value()); + } + return owner; + } + + protected Either, JanusGraphOperationStatus> getDataFromGraph(GraphVertex componentV, EdgeLabelEnum edgelabel) { + Either>, JanusGraphOperationStatus> dataVertex = getDataAndVertexFromGraph(componentV, edgelabel); + if (dataVertex.isRight()) { + return Either.right(dataVertex.right().value()); + } + Map properties = dataVertex.left().value().getRight(); + return Either.left(properties); + } + + @SuppressWarnings("unchecked") + protected Either>, JanusGraphOperationStatus> getDataAndVertexFromGraph(GraphVertex componentV, EdgeLabelEnum edgelabel) { + Either dataVertex = getDataVertex(componentV, edgelabel); + if (dataVertex.isRight()) { + return Either.right(dataVertex.right().value()); + } + GraphVertex propV = dataVertex.left().value(); + Map properties = (Map) propV.getJson(); + Pair> pair = new ImmutablePair<>(propV, properties); + return Either.left(pair); + } + + protected Either getDataVertex(GraphVertex componentV, EdgeLabelEnum edgelabel) { + Either childVertex = janusGraphDao + .getChildVertex(componentV, edgelabel, JsonParseFlagEnum.ParseJson); + if (childVertex.isRight()) { + if (childVertex.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", edgelabel, componentV.getUniqueId(), childVertex.right().value()); + } + return Either.right(childVertex.right().value()); + } + GraphVertex propV = childVertex.left().value(); + return Either.left(propV); + } + + /** + * Returns tosca data belonging to tosca element specified by uid according received label + * + * @param toscaElementUid + * @param edgelabel + * @return + */ + public Either, JanusGraphOperationStatus> getDataFromGraph(String toscaElementUid, EdgeLabelEnum edgelabel) { + + Either, JanusGraphOperationStatus> result = null; + Either getToscaElementRes; + + getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + JanusGraphOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon getting tosca data from graph. Status is {}. ", toscaElementUid, status); + result = Either.right(status); + } + if (result == null) { + result = getDataFromGraph(getToscaElementRes.left().value(), edgelabel); + } + return result; + } + + public Either findUserVertex(String userId) { + return janusGraphDao + .getVertexByPropertyAndLabel(GraphPropertyEnum.USERID, userId, VertexTypeEnum.USER, JsonParseFlagEnum.NoParse); + } + + /** + * + * @param elemementId + * @param label + * @return + */ + public Either isCloneNeeded(String elemementId, EdgeLabelEnum label) { + Either vertexById = janusGraphDao.getVertexById(elemementId); + if (vertexById.isRight()) { + log.debug("Failed to fetch element by id {} error {}", elemementId, vertexById.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexById.right().value())); + } + GraphVertex toscaElementVertex = vertexById.left().value(); + Either childVertex = janusGraphDao + .getChildVertex(toscaElementVertex, label, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + if (childVertex.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", label, toscaElementVertex.getUniqueId(), childVertex.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value())); + } + return Either.left(Boolean.FALSE); + } + GraphVertex dataVertex = childVertex.left().value(); + Iterator edges = dataVertex.getVertex().edges(Direction.IN, label.name()); + int edgeCount = 0; + while (edges.hasNext()) { + edges.next(); + ++edgeCount; + } + if (edgeCount > 1) { + return Either.left(Boolean.TRUE); + } else { + return Either.left(Boolean.FALSE); + } + } + + protected Either updateOrCopyOnUpdate(GraphVertex dataVertex, GraphVertex toscaElementVertex, EdgeLabelEnum label) { +// healingPipelineDao.setHealingVersion(dataVertex); + Iterator edges = dataVertex.getVertex().edges(Direction.IN, label.name()); + int edgeCount = 0; + Edge edgeToRemove = null; + while (edges.hasNext()) { + Edge edge = edges.next(); + ++edgeCount; + Vertex outVertex = edge.outVertex(); + String outId = (String) janusGraphDao + .getProperty((JanusGraphVertex) outVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()); + if (toscaElementVertex.getUniqueId().equals(outId)) { + edgeToRemove = edge; + } + } + if (edgeToRemove == null) { + log.debug("No edges {} from vertex {} to vertex {}", label, toscaElementVertex.getUniqueId(), dataVertex.getUniqueId()); + return Either.right(JanusGraphOperationStatus.GENERAL_ERROR); + } + switch (edgeCount) { + case 0: + // error + log.debug("No edges {} to vertex {}", label, dataVertex.getUniqueId()); + return Either.right(JanusGraphOperationStatus.GENERAL_ERROR); + case 1: + // update + log.trace("Only one edge {} to vertex {}. Update vertex", label, dataVertex.getUniqueId()); + return janusGraphDao.updateVertex(dataVertex); + default: + // copy on update + log.trace("More than one edge {} to vertex {}. Need to clone vertex", label, dataVertex.getUniqueId()); + return cloneDataVertex(dataVertex, toscaElementVertex, label, edgeToRemove); + } + } + + private Either cloneDataVertex(GraphVertex dataVertex, GraphVertex toscaElementVertex, EdgeLabelEnum label, Edge edgeToRemove) { + GraphVertex newDataVertex = new GraphVertex(dataVertex.getLabel()); + String id = IdBuilderUtils.generateChildId(toscaElementVertex.getUniqueId(), dataVertex.getLabel()); + newDataVertex.cloneData(dataVertex); + newDataVertex.setUniqueId(id); + + Either createVertex = janusGraphDao.createVertex(newDataVertex); + if (createVertex.isRight()) { + log.debug("Failed to clone data vertex for {} error {}", dataVertex.getUniqueId(), createVertex.right().value()); + return createVertex; + } + newDataVertex = createVertex.left().value(); + JanusGraphOperationStatus + createEdge = janusGraphDao + .createEdge(toscaElementVertex, newDataVertex, label, janusGraphDao.getEdgeProperties(edgeToRemove)); + if (createEdge != JanusGraphOperationStatus.OK) { + log.debug("Failed to associate vertex {} to vertex {}, error {}", toscaElementVertex.getUniqueId(), newDataVertex.getUniqueId(), createEdge); + return Either.right(createEdge); + } + edgeToRemove.remove(); + return Either.left(newDataVertex); + } + + public Either associateElementToData(GraphVertex element, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, Map data) { + GraphVertex dataV = new GraphVertex(vertexLabel); + String id = IdBuilderUtils.generateChildId(element.getUniqueId(), vertexLabel); + dataV.setUniqueId(id); + dataV.setJson(data); + Either createVertex = janusGraphDao.createVertex(dataV); + if (createVertex.isRight()) { + log.trace("Failed to create {} vertex for type node {}", vertexLabel, element.getUniqueId()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createVertex.right().value())); + } + dataV = createVertex.left().value(); + JanusGraphOperationStatus + createEdgeStatus = janusGraphDao + .createEdge(element.getVertex(), dataV.getVertex(), edgeLabel, new HashMap<>()); + if (createEdgeStatus != JanusGraphOperationStatus.OK) { + log.trace("Failed to create {} vertex for type node {}", vertexLabel, element.getUniqueId()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdgeStatus)); + } + return Either.left(dataV); + } + + /** + * Adds tosca data element to tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaData + * @param mapKeyField + * @return + */ + public StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { + + List toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return addToscaDataToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField); + } + + /** + * Adds tosca data deep element to tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaData + * @param pathKeys + * @param mapKeyField + * @return + */ + public StorageOperationStatus addToscaDataDeepElementToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List pathKeys, + JsonPresentationFields mapKeyField) { + + List toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return addToscaDataDeepElementsToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); + } + + /** + * Converts recieved map of tosca data deep elements to list and adds it to tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaDataMap + * @param pathKeys + * @param mapKeyField + * @return + */ + public StorageOperationStatus addToscaDataDeepElementsToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map toscaDataMap, List pathKeys, + JsonPresentationFields mapKeyField) { + + if (toscaDataMap != null) { + return addToscaDataDeepElementsToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataMap.values().stream().collect(Collectors.toList()), pathKeys, mapKeyField); + } + return StorageOperationStatus.OK; + } + + /** + * Adds list of tosca data deep elements to tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaDataList + * @param pathKeys + * @param mapKeyField + * @return + */ + public StorageOperationStatus addToscaDataDeepElementsToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, List pathKeys, + JsonPresentationFields mapKeyField) { + + return updateOrAddToscaDataDeepElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField, false); + } + + /** + * Updates list of tosca data elements of tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaData + * @param mapKeyField + * @return + */ + public StorageOperationStatus updateToscaDataOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { + List toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return updateToscaDataOfToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField); + } + + /** + * Updates tosca data deep element of tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaData + * @param pathKeys + * @param mapKeyField + * @return + */ + public StorageOperationStatus updateToscaDataDeepElementOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List pathKeys, + JsonPresentationFields mapKeyField) { + List toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return updateToscaDataDeepElementsOfToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); + } + + /** + * Updates tosca data deep elements of tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaDataList + * @param pathKeys + * @param mapKeyField + * @return + */ + public StorageOperationStatus updateToscaDataDeepElementsOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, List pathKeys, + JsonPresentationFields mapKeyField) { + + return updateOrAddToscaDataDeepElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField, true); + } + + /** + * Adds tosca data element to tosca element with specified uid according received labels + * + * @param toscaElementUid + * @param toscaData + * @param edgeLabel + * @param vertexLabel + * @param mapKeyField + * @return + */ + public StorageOperationStatus addToscaDataToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { + + List toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return addToscaDataToToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, mapKeyField); + } + + /** + * Adds tosca data deep element to tosca element with specified uid according received labels + * + * @param toscaElementUid + * @param edgeLabel + * @param vertexLabel + * @param toscaData + * @param pathKeys + * @param mapKeyField + * @return + */ + public StorageOperationStatus addToscaDataDeepElementToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List pathKeys, + JsonPresentationFields mapKeyField) { + + List toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return addToscaDataDeepElementsToToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); + } + + public StorageOperationStatus updateToscaDataDeepElementOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List pathKeys, + JsonPresentationFields mapKeyField) { + + List toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return updateToscaDataDeepElementsOfToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); + } + + public StorageOperationStatus updateToscaDataDeepElementsOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, List pathKeys, + JsonPresentationFields mapKeyField) { + + StorageOperationStatus statusRes = null; + Either getToscaElementRes; + + getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + JanusGraphOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { + statusRes = updateToscaDataDeepElementsOfToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); + } + if (statusRes == null) { + statusRes = StorageOperationStatus.OK; + } + return statusRes; + } + + StorageOperationStatus overrideToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, Map toscaData) { + return janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse) + .left() + .bind(graphVertex -> overrideToscaElementData(graphVertex, toscaData, edgeLabel)) + .either(graphVertex -> StorageOperationStatus.OK, + DaoStatusConverter::convertJanusGraphStatusToStorageStatus); + } + + private Either overrideToscaElementData(GraphVertex toscaElement, Map toscaData, EdgeLabelEnum edgeLabelEnum) { + return janusGraphDao.getChildVertex(toscaElement, edgeLabelEnum, JsonParseFlagEnum.ParseJson) + .left() + .bind(dataVertex -> overrideToscaElementData(dataVertex, toscaElement, toscaData, edgeLabelEnum)) + .right() + .map(err -> logAndReturn(err, "failed to override tosca data for element {} of type {}. status: {}", toscaElement.getUniqueId(), edgeLabelEnum, err)); + } + + private Either overrideToscaElementData(GraphVertex dataElement, GraphVertex toscaElement, Map toscaData, EdgeLabelEnum edgeLabelEnum) { + dataElement.setJson(toscaData); + return updateOrCopyOnUpdate(dataElement, toscaElement, edgeLabelEnum); + } + + /** + * Adds list of tosca data deep elements to tosca element with specified uid according received labels + * + * @param toscaElementUid + * @param edgeLabel + * @param vertexLabel + * @param toscaDataList + * @param pathKeys + * @param mapKeyField + * @return + */ + public StorageOperationStatus addToscaDataDeepElementsToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, List pathKeys, + JsonPresentationFields mapKeyField) { + + StorageOperationStatus statusRes = null; + Either getToscaElementRes; + + getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + JanusGraphOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { + statusRes = addToscaDataDeepElementsToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); + } + if (statusRes == null) { + statusRes = StorageOperationStatus.OK; + } + return statusRes; + } + + public StorageOperationStatus deleteToscaDataDeepElementsBlockOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String key) { + + StorageOperationStatus statusRes = null; + Either getToscaElementRes; + + getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + JanusGraphOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + if (statusRes == null) { + statusRes = deleteToscaDataDeepElementsBlockToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, key); + } + if (statusRes == null) { + statusRes = StorageOperationStatus.OK; + } + return statusRes; + } + + public StorageOperationStatus deleteToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String key) { + + StorageOperationStatus result = null; + GraphVertex toscaDataVertex = null; + Either toscaDataVertexRes = janusGraphDao + .getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight()) { + JanusGraphOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null) { + toscaDataVertex = toscaDataVertexRes.left().value(); + result = deleteDeepElementsBlock(toscaDataVertex, key); + } + if (result == null) { + Either updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); + if (updateOrCopyRes.isRight()) { + JanusGraphOperationStatus status = updateOrCopyRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete tosca data block {} from the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + @SuppressWarnings("rawtypes") + public StorageOperationStatus addToscaDataDeepElementsBlockToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, MapDataDefinition toscaDataMap, String key) { + + StorageOperationStatus statusRes = null; + Either getToscaElementRes; + + getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + JanusGraphOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + if (statusRes == null && toscaDataMap != null) { + statusRes = addToscaDataDeepElementsBlockToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataMap, key); + } + if (statusRes == null) { + statusRes = StorageOperationStatus.OK; + } + return statusRes; + } + + @SuppressWarnings("rawtypes") + public StorageOperationStatus addToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, MapDataDefinition toscaDataMap, String key) { + + StorageOperationStatus result = null; + GraphVertex toscaDataVertex = null; + Either toscaDataVertexRes = janusGraphDao + .getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null && toscaDataVertexRes.isLeft()) { + toscaDataVertex = toscaDataVertexRes.left().value(); + result = addDeepElementsBlock(toscaDataVertex, toscaDataMap, key); + + } + if (result == null) { + if (toscaDataVertex != null) { + Either updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); + if (updateOrCopyRes.isRight()) { + JanusGraphOperationStatus status = updateOrCopyRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data {} to the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + } else { + Map data = new HashMap<>(); + data.put(key, toscaDataMap); + Either createRes = associateElementToData(toscaElement, vertexLabel, edgeLabel, data); + if (createRes.isRight()) { + StorageOperationStatus status = createRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to assosiate tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); + result = status; + } + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + /** + * + * @param toscaElementId the id of the tosca element data container + * @param edgeLabel the edge label of the data type to update + * @param toscaDataMap the data to update + * @param key the key in the json object where the map object block resides + * @return the status of the update operation + */ + public StorageOperationStatus updateToscaDataDeepElementsBlockToToscaElement(String toscaElementId, EdgeLabelEnum edgeLabel, MapDataDefinition toscaDataMap, String key) { + return janusGraphDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse) + .either(toscaElement -> updateToscaDataDeepElementsBlockToToscaElement(toscaElement, edgeLabel, toscaDataMap, key), + DaoStatusConverter::convertJanusGraphStatusToStorageStatus); + } + + private StorageOperationStatus updateToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, MapDataDefinition toscaDataMap, String key) { + return janusGraphDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson) + .left() + .bind(dataVertex -> updateToscaDataDeepElementsBlockToToscaElement(toscaElement, dataVertex, edgeLabel, toscaDataMap, key)) + .either(updatedVertex -> StorageOperationStatus.OK, + DaoStatusConverter::convertJanusGraphStatusToStorageStatus); + } + + private Either updateToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, GraphVertex dataElement, EdgeLabelEnum edgeLabel, MapDataDefinition toscaDataMap, String key) { + Map mapToscaDataDefinition = toscaDataMap.getMapToscaDataDefinition(); + updateDeepElements(dataElement, mapToscaDataDefinition, Collections.singletonList(key)); + return updateOrCopyOnUpdate(dataElement, toscaElement, edgeLabel) + .right() + .map(err -> logAndReturn(err, "failed while trying to update data vertex from tosca element {}, of type {} . status {}", toscaElement.getUniqueId(), edgeLabel, err)); + } + + /** + * Updates tosca data element of tosca element by specified uid according received labels + * + * @param toscaElementUid + * @param edgeLabel + * @param vertexLabel + * @param toscaData + * @param mapKeyField + * @return + */ + public StorageOperationStatus updateToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { + + List toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return updateToscaDataOfToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, mapKeyField); + } + + /** + * Updates list of tosca data elements belonging to tosca element with specified uid according received labels + * + * @param toscaElementUid + * @param edgeLabel + * @param vertexLabel + * @param toscaDataList + * @param mapKeyField + * @return + */ + public StorageOperationStatus updateToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, JsonPresentationFields mapKeyField) { + + StorageOperationStatus statusRes = null; + Either getToscaElementRes; + + getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + JanusGraphOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { + statusRes = updateToscaDataOfToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, mapKeyField); + } + if (statusRes == null) { + statusRes = StorageOperationStatus.OK; + } + return statusRes; + } + + /** + * Adds list of tosca data elements to tosca element with specified uid according received labels + * + * @param toscaElementUid + * @param edgeLabel + * @param vertexLabel + * @param toscaDataList + * @param mapKeyField + * @return + */ + public StorageOperationStatus addToscaDataToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, JsonPresentationFields mapKeyField) { + + StorageOperationStatus statusRes = null; + Either getToscaElementRes; + + getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + JanusGraphOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { + statusRes = addToscaDataToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, mapKeyField); + } + if (statusRes == null) { + statusRes = StorageOperationStatus.OK; + } + return statusRes; + } + + /** + * Converts recieved map of tosca data elements to list and adds it to tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaDataMap + * @param mapKeyField + * @return + */ + public StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map toscaDataMap, JsonPresentationFields mapKeyField) { + + return addToscaDataToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataMap.values().stream().collect(Collectors.toList()), mapKeyField); + } + + /** + * Adds list of tosca data elements to tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaDataList + * @param mapKeyField + * @return + */ + public StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, JsonPresentationFields mapKeyField) { + + return updateOrAddToscaData(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField, false); + } + + /** + * Updates list of tosca data elements belonging to tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaDataList + * @param mapKeyField + * @return + */ + public StorageOperationStatus updateToscaDataOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, JsonPresentationFields mapKeyField) { + + return updateOrAddToscaData(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField, true); + } + + public boolean hasEdgeOfType(GraphVertex toscaElement, EdgeLabelEnum edgeLabel) { + Either vertex = janusGraphDao + .getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + return vertex.isLeft(); + } + + @SuppressWarnings("unchecked") + private StorageOperationStatus updateOrAddToscaData(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, JsonPresentationFields mapKeyField, boolean isUpdate) { + StorageOperationStatus result = null; + GraphVertex toscaDataVertex = null; + Map existingToscaDataMap = null; + Either, StorageOperationStatus> validateRes = null; + Map mergedToscaDataMap; + Either toscaDataVertexRes = janusGraphDao + .getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null) { + if (toscaDataVertexRes.isLeft()) { + toscaDataVertex = toscaDataVertexRes.left().value(); + existingToscaDataMap = (Map) toscaDataVertex.getJson(); + } + + validateRes = validateMergeToscaData(toscaElement, toscaDataList, mapKeyField, existingToscaDataMap, isUpdate); + if (validateRes.isRight()) { + result = validateRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed validate tosca data upon adding to tosca element {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result); + } + } + if (result == null) { + mergedToscaDataMap = validateRes.left().value(); + result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, mergedToscaDataMap); + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + + } + + @SuppressWarnings("unchecked") + public StorageOperationStatus updateFullToscaData(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map toscaData) { + StorageOperationStatus result = null; + GraphVertex toscaDataVertex = null; + Map existingToscaDataMap = null; + + Either toscaDataVertexRes = janusGraphDao + .getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null) { + if (toscaDataVertexRes.isLeft()) { + toscaDataVertex = toscaDataVertexRes.left().value(); + existingToscaDataMap = (Map) toscaDataVertex.getJson(); + } + + + } + if (result == null) { + + result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, toscaData); + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private StorageOperationStatus updateOrAddToscaDataDeepElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, List pathKeys, + JsonPresentationFields mapKeyField, boolean isUpdate) { + + StorageOperationStatus result = null; + GraphVertex toscaDataVertex = null; + Map existingDeepElementsMap = null; + Either, StorageOperationStatus> validateRes = null; + Either toscaDataVertexRes = janusGraphDao + .getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null) { + if (toscaDataVertexRes.isLeft()) { + toscaDataVertex = toscaDataVertexRes.left().value(); + existingDeepElementsMap = getDeepElements(toscaDataVertex, pathKeys); + } + validateRes = validateMergeToscaData(toscaElement, toscaDataList, mapKeyField, existingDeepElementsMap, isUpdate); + if (validateRes.isRight()) { + result = validateRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed validate tosca data upon adding to tosca element {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result); + } + } + if (result == null) { + updateDeepElements(toscaDataVertex, validateRes.left().value(), pathKeys); + Map toscaDataToHandle; + if(toscaDataVertex == null){ + toscaDataToHandle = new HashMap<>(); + Map currMap = toscaDataToHandle; + for (int i = 1; i < pathKeys.size()-1; ++i) { + currMap.put(pathKeys.get(i), (K) new MapDataDefinition()); + currMap = (Map) ((MapDataDefinition) currMap).getMapToscaDataDefinition().get(pathKeys.get(i)); + } + toscaDataToHandle.put(pathKeys.get(pathKeys.size()-1), (K) new MapDataDefinition(validateRes.left().value())); + + } else { + toscaDataToHandle = (Map) toscaDataVertex.getJson(); + } + result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, toscaDataToHandle); + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private void updateDeepElements(GraphVertex toscaDataVertex, Map mergedDeepElementMap, List pathKeys) { + + if (toscaDataVertex != null && MapUtils.isNotEmpty(mergedDeepElementMap)) { + Map currMap = (Map) toscaDataVertex.getJson(); + if(!currMap.containsKey(pathKeys.get(0))){ + currMap.put(pathKeys.get(0), new MapDataDefinition<>()); + } + MapDataDefinition currDeepElement = currMap.get(pathKeys.get(0)); + + for (int i = 1; i < pathKeys.size(); ++i) { + if(currDeepElement.findByKey(pathKeys.get(i)) == null){ + currDeepElement.put(pathKeys.get(i), new MapDataDefinition<>()); + } + currDeepElement = (MapDataDefinition) currDeepElement.findByKey(pathKeys.get(i)); + } + if(currDeepElement != null){ + for (Map.Entry elementEntry : mergedDeepElementMap.entrySet()) { + currDeepElement.put(elementEntry.getKey(), elementEntry.getValue()); + } + } + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private Map getDeepElements(GraphVertex toscaDataVertex, List pathKeys) { + Map result = null; + Map currMap = (Map) toscaDataVertex.getJson(); + MapDataDefinition currDeepElement = (MapDataDefinition) currMap.get(pathKeys.get(0)); + for (int i = 1; i < pathKeys.size(); ++i) { + currDeepElement = (MapDataDefinition) currDeepElement.findByKey(pathKeys.get(i)); + } + if(currDeepElement != null){ + result = (Map) currDeepElement.getMapToscaDataDefinition(); + } + return result; + } + + @SuppressWarnings("unchecked") + private StorageOperationStatus addDeepElementsBlock(GraphVertex toscaDataVertex, T toscaDataBlock, String key) { + + StorageOperationStatus result = null; + Map currMap = (Map) toscaDataVertex.getJson(); + if (currMap.containsKey(key)) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add block of deep tosca data elements by label {}." + " The block element with the same key {} already exists. ", toscaDataVertex.getLabel(), key); + result = StorageOperationStatus.ENTITY_ALREADY_EXISTS; + } + if (result == null) { + currMap.put(key, toscaDataBlock); + } + return result; + } + + @SuppressWarnings("unchecked") + private StorageOperationStatus deleteDeepElementsBlock(GraphVertex toscaDataVertex, String key) { + + StorageOperationStatus result = null; + Map currMap = (Map) toscaDataVertex.getJson(); + if (!currMap.containsKey(key)) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete block of deep tosca data elements by label {}." + " The block element with the same key {} doesn't exist. ", toscaDataVertex.getLabel(), key); + result = StorageOperationStatus.NOT_FOUND; + } + if (result == null) { + currMap.remove(key); + } + return null; + } + + /** + * Removes tosca data vertex belonging to tosca element specified by uid according label + * + * @param toscaElementUid + * @param edgeLabel + * @param vertexLabel + * @return + */ + public StorageOperationStatus removeToscaData(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) { + + StorageOperationStatus statusRes = StorageOperationStatus.OK; + Either getToscaElementRes; + + getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + JanusGraphOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + if (statusRes == StorageOperationStatus.OK) { + statusRes = removeToscaDataVertex(getToscaElementRes.left().value(), edgeLabel, vertexLabel); + } + return statusRes; + } + + /** + * Removes tosca data vertex belonging to tosca element according label + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @return + */ + public StorageOperationStatus removeToscaDataVertex(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) { + StorageOperationStatus result = null; + GraphVertex toscaDataVertex = null; + Iterator edges = null; + int edgeCounter = 0; + Edge edge = null; + Edge edgeToDelete = null; + Either toscaDataVertexRes = janusGraphDao + .getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight()) { + JanusGraphOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null) { + toscaDataVertex = toscaDataVertexRes.left().value(); + edges = toscaDataVertex.getVertex().edges(Direction.IN); + if (edges == null || !edges.hasNext()) { + result = StorageOperationStatus.NOT_FOUND; + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, result); + } + } + if (result == null) { + if (edges!=null) { + while (edges.hasNext()) { + ++edgeCounter; + edge = edges.next(); + if (edge.outVertex().id().equals(toscaElement.getVertex().id())) { + edgeToDelete = edge; + break; + } + } + } + if (edgeToDelete == null) { + result = StorageOperationStatus.NOT_FOUND; + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, result); + } + } + if (result == null) { + if (edgeCounter > 1 && edgeToDelete!=null) { + edgeToDelete.remove(); + } else { + toscaDataVertex.getVertex().remove(); + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + /** + * Deletes tosca data elements belonging to tosca element specified by uid according label + * + * @param toscaElementUid + * @param edgeLabel + * @param uniqueKeys + * @return + */ + public StorageOperationStatus deleteToscaDataElements(String toscaElementUid, EdgeLabelEnum edgeLabel, List uniqueKeys) { + + StorageOperationStatus statusRes = StorageOperationStatus.OK; + Either getToscaElementRes; + + getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + JanusGraphOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + if (statusRes == StorageOperationStatus.OK) { + statusRes = deleteToscaDataElements(getToscaElementRes.left().value(), edgeLabel, uniqueKeys); + } + return statusRes; + } + + /** + * Deletes tosca data element belonging to tosca element specified by uid according label + * + * @param toscaElementUid + * @param edgeLabel + * @param vertexLabel + * @param uniqueKey + * @param mapKeyField + * @return + */ + public StorageOperationStatus deleteToscaDataElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, JsonPresentationFields mapKeyField) { + + StorageOperationStatus statusRes = StorageOperationStatus.OK; + Either getToscaElementRes; + + getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + JanusGraphOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + if (statusRes == StorageOperationStatus.OK) { + statusRes = deleteToscaDataElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKey, mapKeyField); + } + return statusRes; + + } + + /** + * Deletes tosca data deep element belonging to tosca element specified by uid according label + * + * @param toscaElementUid + * @param edgeLabel + * @param vertexLabel + * @param uniqueKey + * @param pathKeys + * @param mapKeyField + * @return + */ + public StorageOperationStatus deleteToscaDataDeepElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, List pathKeys, JsonPresentationFields mapKeyField) { + + StorageOperationStatus statusRes = StorageOperationStatus.OK; + Either getToscaElementRes; + + getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + JanusGraphOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + if (statusRes == StorageOperationStatus.OK) { + statusRes = deleteToscaDataDeepElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKey, pathKeys, mapKeyField); + } + return statusRes; + + } + + /** + * Deletes tosca data deep element belonging to tosca element according label + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param uniqueKey + * @param pathKeys + * @param mapKeyField + * @return + */ + public StorageOperationStatus deleteToscaDataDeepElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, List pathKeys, JsonPresentationFields mapKeyField) { + + List uniqueKeys = new ArrayList<>(); + uniqueKeys.add(uniqueKey); + return deleteToscaDataDeepElements(toscaElement, edgeLabel, vertexLabel, uniqueKeys, pathKeys, mapKeyField); + } + + public StorageOperationStatus deleteToscaDataDeepElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List uniqueKeys, List pathKeys, JsonPresentationFields mapKeyField) { + + StorageOperationStatus result = null; + GraphVertex toscaDataVertex; + Map existingToscaDataMap = null; + Either toscaDataVertexRes = janusGraphDao + .getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight()) { + JanusGraphOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null) { + toscaDataVertex = toscaDataVertexRes.left().value(); + existingToscaDataMap = getDeepElements(toscaDataVertexRes.left().value(), pathKeys); + result = deleteElementsFromDataVertex(toscaElement, edgeLabel, uniqueKeys, toscaDataVertex, existingToscaDataMap); + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private StorageOperationStatus deleteElementsFromDataVertex(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, List uniqueKeys, GraphVertex toscaDataVertex, Map existingToscaDataMap) { + StorageOperationStatus result; + for (String uniqueKey : uniqueKeys) { + result = removeKeyFromDataVertex(uniqueKey, existingToscaDataMap); + if (result != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete tosca data element of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result); + break; + } + } + result = updateToscaDataElement(toscaElement, edgeLabel, toscaDataVertex); + return result; + } + + /** + * Deletes tosca data element belonging to tosca element according label + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param uniqueKey + * @param mapKeyField + * @return + */ + public StorageOperationStatus deleteToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, JsonPresentationFields mapKeyField) { + + List uniqueKeys = new ArrayList<>(); + uniqueKeys.add(uniqueKey); + return deleteToscaDataElements(toscaElement, edgeLabel, uniqueKeys); + } + + @SuppressWarnings("unchecked") +/** + * Deletes tosca data elements belonging to tosca element according label + * @param toscaElement + * @param edgeLabel + * @param uniqueKeys + * @return + */ + public StorageOperationStatus deleteToscaDataElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, List uniqueKeys) { + StorageOperationStatus result = null; + GraphVertex toscaDataVertex; + Map existingToscaDataMap; + Either toscaDataVertexRes = janusGraphDao + .getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight()) { + JanusGraphOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null) { + toscaDataVertex = toscaDataVertexRes.left().value(); + existingToscaDataMap = (Map) toscaDataVertex.getJson(); + result = deleteElementsFromDataVertex(toscaElement, edgeLabel, uniqueKeys, toscaDataVertex, existingToscaDataMap); + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + /** + * Adds the map data entry to the graph vertex of the specified type, related with the specified edge to the component specified by ID + * @param componentId The uniqueId of the component + * @param vertexTypeEnum The type of the vertex + * @param edgeLabelEnum The type of the edge + * @param mapDataEntry The map data entry + * @param + * @return The status of the operation result + */ + public StorageOperationStatus addElementToComponent(String componentId, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map.Entry mapDataEntry){ + if(MapUtils.isNotEmpty(mapDataEntry.getValue().getMapToscaDataDefinition())) + return addToscaDataDeepElementsBlockToToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, mapDataEntry.getValue(), mapDataEntry.getKey()); + return StorageOperationStatus.OK; + } + + private StorageOperationStatus updateToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex) { + StorageOperationStatus result = StorageOperationStatus.OK; + Either updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); + if (updateOrCopyRes.isRight()) { + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateOrCopyRes.right().value()); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), result); + } + return result; + } + + private StorageOperationStatus removeKeyFromDataVertex(String uniqueKey, Map existingToscaDataMap) { + if (!existingToscaDataMap.containsKey(uniqueKey)) { + return StorageOperationStatus.NOT_FOUND; + } + existingToscaDataMap.remove(uniqueKey); + return StorageOperationStatus.OK; + } + + protected StorageOperationStatus handleToscaData(GraphVertex toscaElement, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex, Map mergedToscaDataMap) { + + StorageOperationStatus result = StorageOperationStatus.OK; + if (toscaDataVertex == null) { + + Either createRes = associateElementToData(toscaElement, vertexLabel, edgeLabel, mergedToscaDataMap); + if (createRes.isRight()) { + StorageOperationStatus status = createRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to assosiate tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); + result = status; + } + } else { + toscaDataVertex.setJson(mergedToscaDataMap); + Either updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); + if (updateOrCopyRes.isRight()) { + JanusGraphOperationStatus status = updateOrCopyRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data {} to the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + } + return result; + } + + private Either, StorageOperationStatus> validateMergeToscaData(GraphVertex toscaElement, List toscaDataList, JsonPresentationFields mapKeyField, Map existingToscaDataMap, + boolean isUpdate) { + + Map mergedToscaDataMap = new HashMap<>(); + StorageOperationStatus status; + Either, StorageOperationStatus> result = Either.left(mergedToscaDataMap); + if (MapUtils.isNotEmpty(existingToscaDataMap)) { + mergedToscaDataMap.putAll(existingToscaDataMap); + } + for (T toscaDataElement : toscaDataList) { + status = handleToscaDataElement(toscaElement, mapKeyField, mergedToscaDataMap, toscaDataElement, isUpdate); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + break; + } + } + return result; + } + + private StorageOperationStatus handleToscaDataElement(GraphVertex toscaElement, JsonPresentationFields mapKeyField, Map mergedToscaDataMap, T toscaDataElement, boolean isUpdate) { + + StorageOperationStatus status = StorageOperationStatus.OK; + String currKey = (String) toscaDataElement.getToscaPresentationValue(mapKeyField); + + if(StringUtils.isEmpty(currKey) && toscaDataElement instanceof ListDataDefinition) { + ToscaDataDefinition toscaDataDefinition = ((ListDataDefinition) toscaDataElement) + .getListToscaDataDefinition().get(0); + if(toscaDataDefinition != null) { + currKey = (String) toscaDataDefinition.getToscaPresentationValue(mapKeyField); + } + } + + if (StringUtils.isEmpty(currKey)) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data to tosca element {}. The key is empty. "); + status = StorageOperationStatus.BAD_REQUEST; + } else if (!isUpdate && mergedToscaDataMap.containsKey(currKey)) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data to tosca element {}. The element with the same key {} already exists. ", toscaElement.getUniqueId(), currKey); + status = StorageOperationStatus.BAD_REQUEST; + } + mergedToscaDataMap.put(currKey, toscaDataElement); + return status; + } + +// public StorageOperationStatus updateDataOnGraph(GraphVertex dataVertex) { +// Either updateVertex = janusGraphDao.updateVertex(dataVertex); +// if (updateVertex.isRight()) { +// return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateVertex.right().value()); +// } +// return StorageOperationStatus.OK; +// } + + protected GroupInstanceDataDefinition buildGroupInstanceDataDefinition(GroupDataDefinition group, ComponentInstanceDataDefinition componentInstance, Map instDeplArtifMap) { + + String componentInstanceName = componentInstance.getName(); + Long creationDate = System.currentTimeMillis(); + GroupInstanceDataDefinition groupInstance = new GroupInstanceDataDefinition(); + String groupUid = group.getUniqueId(); + + groupInstance.setGroupUid(groupUid); + groupInstance.setType(group.getType()); + groupInstance.setCustomizationUUID(generateCustomizationUUID()); + groupInstance.setCreationTime(creationDate); + groupInstance.setModificationTime(creationDate); + groupInstance.setName(buildGroupInstanceName(componentInstanceName, group.getName())); + groupInstance.setGroupName(group.getName()); + groupInstance.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(groupInstance.getName())); + groupInstance.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(componentInstance.getUniqueId(), groupUid, groupInstance.getNormalizedName())); + groupInstance.setArtifacts(group.getArtifacts()); + +// List fixedArtifactsUuid; +// List artifactsUuid = group.getArtifactsUuid(); +// if (instDeplArtifMap != null) { +// fixedArtifactsUuid = new ArrayList<>(); +// artifactsUuid.forEach(u -> { +// Optional findFirst = instDeplArtifMap.values().stream().filter(a -> u.equals(a.getUniqueId())).findFirst(); +// if (findFirst.isPresent()) { +// fixedArtifactsUuid.add(findFirst.get().getArtifactUUID()); +// } else { +// fixedArtifactsUuid.add(u); +// } +// }); +// } else { +// fixedArtifactsUuid = artifactsUuid; +// } + groupInstance.setArtifactsUuid(group.getArtifactsUuid()); + groupInstance.setProperties(group.getProperties()); + convertPropertiesToInstanceProperties(groupInstance.getProperties()); + groupInstance.setInvariantUUID(group.getInvariantUUID()); + groupInstance.setGroupUUID(group.getGroupUUID()); + groupInstance.setVersion(group.getVersion()); + + return groupInstance; + } + + + protected String buildGroupInstanceName(String instanceName, String groupName) { + return ValidationUtils.normalizeComponentInstanceName(instanceName) + ".." + groupName; + } + + protected String generateCustomizationUUID() { + return UUID.randomUUID().toString(); + } + + protected void convertPropertiesToInstanceProperties(List properties){ + properties.forEach(PropertyDataDefinition::convertPropertyDataToInstancePropertyData); + } + + private JanusGraphOperationStatus logAndReturn(JanusGraphOperationStatus janusGraphOperationStatus, String logMsg, Object ... logParams) { + log.debug(logMsg, logParams); + return janusGraphOperationStatus; + } + + protected GraphVertex throwStorageException(JanusGraphOperationStatus status) { + throw new StorageException(status); + } + + public void setHealingPipelineDao(HealingPipelineDao healingPipelineDao) { + this.healingPipelineDao = healingPipelineDao; + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ByToscaNameDerivedNodeTypeResolver.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ByToscaNameDerivedNodeTypeResolver.java new file mode 100644 index 0000000000..a34dd7e920 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ByToscaNameDerivedNodeTypeResolver.java @@ -0,0 +1,56 @@ +/*- + * ============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.jsonjanusgraph.operations; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.model.DerivedNodeTypeResolver; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Component("derived-resource-resolver") +public class ByToscaNameDerivedNodeTypeResolver implements DerivedNodeTypeResolver { + + @Autowired + private JanusGraphDao janusGraphDao; + + @Override + public Either, JanusGraphOperationStatus> findDerivedResources(String parentResource) { + Map propertiesToMatch = new HashMap<>(); + propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + + propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, parentResource); + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + return janusGraphDao + .getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, JsonParseFlagEnum.NoParse); + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CapabilitiesOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CapabilitiesOperation.java new file mode 100644 index 0000000000..3b544aaa39 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CapabilitiesOperation.java @@ -0,0 +1,156 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * 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. + */ + +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.operations.StorageException; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +@org.springframework.stereotype.Component("capabilities-operation") +public class CapabilitiesOperation extends BaseOperation { + private static final Logger LOGGER = LoggerFactory.getLogger(CapabilitiesOperation.class); + + public Either, StorageOperationStatus> addCapabilities(String componentId, + List capabilityDefinitions) { + return addOrUpdateCapabilities(componentId, capabilityDefinitions, false); + } + + public Either, StorageOperationStatus> updateCapabilities(String componentId, + List capabilityDefinitions) { + return addOrUpdateCapabilities(componentId, capabilityDefinitions, true); + } + + private Either, StorageOperationStatus> addOrUpdateCapabilities(String componentId, + List capabilityDefinitions, + boolean isUpdateAction) { + StorageOperationStatus statusRes = performUpdateToscaAction(isUpdateAction, + componentId, Collections.singletonList(convertToListCapabilityDataDefinition(capabilityDefinitions))); + if (!statusRes.equals(StorageOperationStatus.OK)) { + LOGGER.error("Failed to find the parent capability of capability type {}." + " status is {}", componentId, + statusRes); + return Either.right(statusRes); + } + return Either.left(capabilityDefinitions); + } + + public StorageOperationStatus deleteCapabilities(Component component, String capabilityIdToDelete) { + return deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.CAPABILITIES, + Collections.singletonList(capabilityIdToDelete)); + } + + public StorageOperationStatus deleteCapabilityProperties(Component component, String capabilityPropIdToDelete) { + return deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.CAPABILITIES_PROPERTIES, + Collections.singletonList(capabilityPropIdToDelete)); + } + + private static ListCapabilityDataDefinition convertToListCapabilityDataDefinition(List capabilities) { + List capabilityDefinitions = new ArrayList<>(capabilities); + return new ListCapabilityDataDefinition(capabilityDefinitions); + } + + private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, String componentId, + List toscaDataList) { + if (isUpdate) { + return updateToscaDataOfToscaElement(componentId, EdgeLabelEnum.CAPABILITIES, + VertexTypeEnum.CAPABILITIES, toscaDataList, JsonPresentationFields.TYPE); + } else { + return addToscaDataToToscaElement(componentId, EdgeLabelEnum.CAPABILITIES, + VertexTypeEnum.CAPABILITIES, toscaDataList, JsonPresentationFields.TYPE); + } + } + + private StorageOperationStatus createOrUpdateCapabilityProperties(String componentId, TopologyTemplate toscaElement, + Map propertiesMap) { + GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum + .NoParse) + .left().on(this::throwStorageException); + Map capabilitiesProperties = toscaElement.getCapabilitiesProperties(); + if(MapUtils.isNotEmpty(capabilitiesProperties)) { + + capabilitiesProperties.forEach((key, val) -> { + Map mapToscaDataDefinition = val.getMapToscaDataDefinition(); + mapToscaDataDefinition.forEach((key1, val1) -> { + + propertiesMap.forEach((propKey, propVal) -> { + Map propValMapToscaDataDefinition = propVal.getMapToscaDataDefinition(); + propValMapToscaDataDefinition.forEach((propKey1, propVal1) -> { + if(propKey1.equals(key1) && val1.getUniqueId().equals(propVal1.getUniqueId())) { + ToscaDataDefinition.mergeDataMaps(mapToscaDataDefinition, propValMapToscaDataDefinition); + } + }); + }); + }); + }); + + ToscaDataDefinition.mergeDataMaps(propertiesMap, capabilitiesProperties); + } + + return topologyTemplateOperation.updateFullToscaData(toscaElementV, + EdgeLabelEnum.CAPABILITIES_PROPERTIES, VertexTypeEnum.CAPABILITIES_PROPERTIES, propertiesMap); + } + + public StorageOperationStatus createOrUpdateCapabilityProperties(String componentId, + Map propertiesMap) { + StorageOperationStatus propertiesStatusRes = null; + if(MapUtils.isNotEmpty(propertiesMap)) { + propertiesStatusRes = createOrUpdateCapabilityProperties(componentId, getTopologyTemplate(componentId), + propertiesMap); + } + + return propertiesStatusRes; + } + + private TopologyTemplate getTopologyTemplate(String componentId) { + return (TopologyTemplate)topologyTemplateOperation + .getToscaElement(componentId, getFilterComponentWithCapProperties()) + .left() + .on(this::throwStorageException); + } + private ComponentParametersView getFilterComponentWithCapProperties() { + ComponentParametersView filter = new ComponentParametersView(); + filter.setIgnoreCapabiltyProperties(false); + return filter; + } + + private ToscaElement throwStorageException(StorageOperationStatus status) { + throw new StorageException(status); + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CategoryOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CategoryOperation.java new file mode 100644 index 0000000000..7603657b9a --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CategoryOperation.java @@ -0,0 +1,94 @@ +/*- + * ============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.jsonjanusgraph.operations; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.ValidationUtils; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@org.springframework.stereotype.Component("category-operation") +public class CategoryOperation extends BaseOperation{ + + private static final Logger log = Logger.getLogger(CategoryOperation.class.getName()); + + /** + * + * @param name + * @param type + * @return + */ + public Either getCategory(String name, VertexTypeEnum type) { + if (name != null) { + String categoryUid = UniqueIdBuilder.buildComponentCategoryUid(name, type); + Map props = new HashMap<>(); + props.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(name)); + Either, JanusGraphOperationStatus> either = janusGraphDao + .getByCriteria(type, props); + + if (either.isRight()) { + JanusGraphOperationStatus janusGraphOperationStatus = either.right().value(); + log.debug("Problem while geting category with id {}. reason - {}", categoryUid, janusGraphOperationStatus + .name()); + if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) { + return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); + } else { + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + } + return Either.left(either.left().value().get(0)); + } else { + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + } + /** + * + * @param categoryV + * @param name + * @return + */ + public Either getSubCategoryForCategory(GraphVertex categoryV, String name ) { + Either, JanusGraphOperationStatus> childrenVertecies = janusGraphDao + .getChildrenVertecies(categoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); + if ( childrenVertecies.isRight() ){ + log.debug("Failed to fetch children verticies for category {} error {}", categoryV.getUniqueId(), childrenVertecies.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childrenVertecies.right().value())); + } + for ( GraphVertex childV : childrenVertecies.left().value() ){ + if ( childV.getMetadataProperty(GraphPropertyEnum.NAME).equals(name) ){ + return Either.left(childV); + } + } + return Either.right(StorageOperationStatus.NOT_FOUND); + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperation.java new file mode 100644 index 0000000000..6079c5ef15 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperation.java @@ -0,0 +1,297 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + + +import fj.data.Either; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.MapComponentInstanceExternalRefs; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.IdMapper; +import org.openecomp.sdc.be.model.operations.impl.OperationUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.*; + +import static java.util.Collections.emptyMap; + +/** + * Created by yavivi on 26/01/2018. + */ +@Component +public class ExternalReferencesOperation extends BaseOperation { + + @Autowired + private IdMapper idMapper; + + @Autowired + private OperationUtils operationUtils; + + + /** + * Constructor + */ + public ExternalReferencesOperation(JanusGraphDao janusGraphDao, NodeTypeOperation nto, TopologyTemplateOperation tto, IdMapper idMapper){ + this.janusGraphDao = janusGraphDao; + this.topologyTemplateOperation = tto; + this.nodeTypeOperation = nto; + this.idMapper = idMapper; + } + + public Either addExternalReferenceWithCommit(String serviceUuid, String componentInstanceName, String objectType, String reference) { + Either addResult = addExternalReference(serviceUuid, componentInstanceName, objectType, reference); + janusGraphDao.commit(); + return addResult; + } + + public Either deleteExternalReferenceWithCommit(String serviceUuid, String componentInstanceName, String objectType, String reference) { + Either result = deleteExternalReference(serviceUuid, componentInstanceName, objectType, reference); + janusGraphDao.commit(); + return result; + } + + public Either updateExternalReferenceWithCommit(String serviceVertexUuid, String componentInstanceName, String objectType, String oldRef, String newRef) { + Either updateResult = updateExternalReference(serviceVertexUuid, componentInstanceName, objectType, oldRef, newRef); + janusGraphDao.commit(); + return updateResult; + } + + public Either addExternalReference(String assetUuid, String componentInstanceName, String objectType, String reference) { + + //Get Container vertex + Either vertexById = janusGraphDao.getVertexById(assetUuid); + if (vertexById.isRight()){ + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + + GraphVertex serviceVertex = vertexById.left().value(); + + final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex); + if (compInstanceUniqueId == null) { + return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); + } + + //Get the external references map vertex + final Either dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + + //Check whether data vertex found + GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; + + //instanceId -> externalRefsMap + Map externalReferencesFullData; + if (externalRefsVertex == null) { + //External Refs vertex does not exist, create its map. + externalReferencesFullData = new HashMap<>(); + externalReferencesFullData.put(compInstanceUniqueId, new MapComponentInstanceExternalRefs()); + } else { + externalReferencesFullData = (Map) externalRefsVertex.getJson(); + externalReferencesFullData.computeIfAbsent(compInstanceUniqueId, k -> new MapComponentInstanceExternalRefs()); + } + + boolean isAdded = addExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, reference); + updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); + + return isAdded ? Either.left(reference) : Either.right(ActionStatus.EXT_REF_ALREADY_EXIST); + } + + public Either deleteExternalReference(String assetUuid, String componentInstanceName, String objectType, String reference){ + //Get Service vertex + Either vertexById = janusGraphDao.getVertexById(assetUuid); + if (vertexById.isRight()){ + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + GraphVertex serviceVertex = vertexById.left().value(); + + final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex); + if (compInstanceUniqueId == null) { + return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); + } + + //Get the external references map vertex + final Either dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + + //Check whether data vertex found + GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; + boolean refDeleted = false; + if (externalRefsVertex != null) { + Map externalReferencesFullData = (Map) externalRefsVertex.getJson(); + if (externalReferencesFullData != null) { + refDeleted = deleteExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, reference); + updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); + } + } + + if (refDeleted) { + return Either.left(reference); + } else { + return Either.right(ActionStatus.EXT_REF_NOT_FOUND); + } + } + + public Either updateExternalReference(String assetUuid, String componentInstanceName, String objectType, String oldRef, String newRef) { + //Get Service vertex + Either vertexById = janusGraphDao.getVertexById(assetUuid); + if (vertexById.isRight()){ + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + + GraphVertex serviceVertex = vertexById.left().value(); + + //Map instance_name -> uuid + final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex); + if (compInstanceUniqueId == null) { + return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); + } + + //Get the external references map vertex + final Either dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + + //Check whether data vertex found + GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; + boolean refReplaced = false; + if (externalRefsVertex != null) { + Map externalReferencesFullData = (Map) externalRefsVertex.getJson(); + if (externalReferencesFullData != null) { + refReplaced = updateExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, oldRef, newRef); + updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); + } + } + if (refReplaced) { + return Either.left(newRef); + } else { + return Either.right(ActionStatus.EXT_REF_NOT_FOUND); + } + } + + public Either>, ActionStatus> getExternalReferences(String assetUuid, String objectType) { + //Get Service vertex + Either vertexById = janusGraphDao.getVertexById(assetUuid); + if (vertexById.isRight()){ + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + + GraphVertex serviceVertex = vertexById.left().value(); + + Map> result = new HashMap(); + + //Get the external references map vertex + final Either dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + //Check whether data vertex found + GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; + if (externalRefsVertex != null) { + Map externalReferencesFullData = (Map) externalRefsVertex.getJson(); + if (externalReferencesFullData != null) { + externalReferencesFullData.entrySet().forEach( + s -> { + List externalRefsByObjectType = externalReferencesFullData.get(s.getKey()).getExternalRefsByObjectType(objectType); + List refList = externalRefsByObjectType == null ? new ArrayList<>() : externalRefsByObjectType; + String key = idMapper.mapUniqueIdToComponentNameTo(s.getKey(), serviceVertex); + result.put(key, refList); + } + ); + return Either.left(result); + } + } + //No external References Node found on this asset + return Either.left(new HashMap<>()); + } + + public void addAllExternalReferences(String containerUniqueId, + String compInstanceUniqueId, + Map> instanceExternalReferences) { + + GraphVertex serviceVertex = janusGraphDao.getVertexById(containerUniqueId) + .left() + .on(operationUtils::onJanusGraphOperationFailure); + Either dataVertex = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + Map externalReferencesFullData; + if (dataVertex.isLeft()) { + externalReferencesFullData = (Map) dataVertex.left().value().getJson(); + } else { + externalReferencesFullData = new HashMap<>(); + } + externalReferencesFullData.put(compInstanceUniqueId, new MapComponentInstanceExternalRefs(instanceExternalReferences)); + updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); + } + + public Map> getAllExternalReferences(String containerUniqueId, + String compInstanceUniqueId) { + GraphVertex serviceVertex = janusGraphDao.getVertexById(containerUniqueId) + .left() + .on(operationUtils::onJanusGraphOperationFailure); + + Either dataVertex = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + if (dataVertex.isRight()) { + return new HashMap<>(); + } + GraphVertex externalRefsVertex = dataVertex.left().value(); + Map externalReferencesFullData = externalRefsVertex == null ? null : (Map) externalRefsVertex.getJson(); + if (externalReferencesFullData != null) { + return externalReferencesFullData + .getOrDefault(compInstanceUniqueId, new MapComponentInstanceExternalRefs()) + .getComponentInstanceExternalRefs(); + } + return emptyMap(); + } + + public Either, ActionStatus> getExternalReferences(String assetUuid, String componentInstanceName, String objectType) { + //Get Service vertex + Either vertexById = janusGraphDao.getVertexById(assetUuid); + if (vertexById.isRight()){ + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + + GraphVertex serviceVertex = vertexById.left().value(); + final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex); + if (compInstanceUniqueId == null) { + return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); + } + + //Get the external references map vertex + final Either dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + + //Check whether data vertex found + GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; + if (externalRefsVertex != null) { + Map externalReferencesFullData = (Map) externalRefsVertex.getJson(); + if (externalReferencesFullData != null) { + return Either.left(getExternalReferencesByObjectId(externalReferencesFullData, compInstanceUniqueId, objectType)); + } + } + + //No external References Node found on this asset + return Either.left(new LinkedList()); + } + + public IdMapper getIdMapper() { + return idMapper; + } + + public void setIdMapper(IdMapper idMapper) { + this.idMapper = idMapper; + } + + private List getExternalReferencesByObjectId(Map externalReferencesFullData, String componentInstanceId, String objectType) { + MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId); + List externalRefsByObjectType = externalRefsMap.getExternalRefsByObjectType(objectType); + return externalRefsByObjectType != null ? externalRefsByObjectType : new LinkedList<>(); + } + + private boolean updateExternalRef(Map externalReferencesFullData, String componentInstanceId, String objectType, String oldRef, String newRef) { + MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId); + return externalRefsMap.replaceExternalRef(objectType, oldRef, newRef); + } + + private boolean deleteExternalRef(Map externalReferencesFullData, String componentInstanceId, String objectType, String reference) { + MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId); + return externalRefsMap.deleteExternalRef(objectType, reference); + } + + private boolean addExternalRef(Map externalReferencesFullData, String componentInstanceId, String objectType, String reference) { + MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId); + return externalRefsMap.addExternalRef(objectType, reference); + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ForwardingPathOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ForwardingPathOperation.java new file mode 100644 index 0000000000..f7372a6e28 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ForwardingPathOperation.java @@ -0,0 +1,118 @@ +/*- + * ============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.jsonjanusgraph.operations; + +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; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.util.*; + +@org.springframework.stereotype.Component("forwarding-paths-operations") +public class ForwardingPathOperation extends BaseOperation { + private static final Logger log = Logger.getLogger(ForwardingPathOperation.class.getName()); + + + public Either, StorageOperationStatus> deleteForwardingPath(Service service, Set forwardingPathsToDelete) { + Either, StorageOperationStatus> result = null; + Either getComponentVertex; + StorageOperationStatus status = null; + + if (result == null) { + getComponentVertex = janusGraphDao + .getVertexById(service.getUniqueId(), JsonParseFlagEnum.NoParse); + if (getComponentVertex.isRight()) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value())); + } + } + if (result == null) { + + status = deleteToscaDataElements(service.getUniqueId(), EdgeLabelEnum.FORWARDING_PATH,new ArrayList<>(forwardingPathsToDelete)); + + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } + + if (result == null) { + result = Either.left(forwardingPathsToDelete); + } + return result; + } + + public Either addForwardingPath(String serviceId, ForwardingPathDataDefinition currentPath) { + return addOrUpdateForwardingPath(false, serviceId, currentPath); + } + + public Either updateForwardingPath(String serviceId, ForwardingPathDataDefinition currentPath) { + return addOrUpdateForwardingPath(true, serviceId, currentPath); + } + + private Either addOrUpdateForwardingPath(boolean isUpdateAction, String serviceId, ForwardingPathDataDefinition currentPath) { + + StorageOperationStatus statusRes; + Either getToscaElementRes; + + getToscaElementRes = janusGraphDao.getVertexById(serviceId, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + JanusGraphOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, CommonUtility.LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", serviceId, status); + statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + return Either.right(statusRes); + } + GraphVertex serviceVertex = getToscaElementRes.left().value(); + if (!isUpdateAction){ + currentPath.setUniqueId(UUID.randomUUID().toString()); + } + statusRes = performUpdateToscaAction(isUpdateAction, serviceVertex, Arrays.asList(currentPath), JsonPresentationFields.FORWARDING_PATH); + { + if (!statusRes.equals(StorageOperationStatus.OK)) { + log.error("Failed to find the parent capability of capability type {}. status is {}", serviceId, statusRes); + return Either.right(statusRes); + } + return Either.left(currentPath); + } + + } + + + private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, GraphVertex graphVertex, List toscaDataList, JsonPresentationFields mapKeyField) { + if (isUpdate) { + return updateToscaDataOfToscaElement(graphVertex, EdgeLabelEnum.FORWARDING_PATH, VertexTypeEnum.FORWARDING_PATH, toscaDataList, JsonPresentationFields.UNIQUE_ID); + } else { + return addToscaDataToToscaElement(graphVertex, EdgeLabelEnum.FORWARDING_PATH, VertexTypeEnum.FORWARDING_PATH, toscaDataList, JsonPresentationFields.UNIQUE_ID); + } + } + +} + + + diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperation.java new file mode 100644 index 0000000000..03bab3b31e --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperation.java @@ -0,0 +1,397 @@ +/*- + * ============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.jsonjanusgraph.operations; + +import fj.data.Either; +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; +import org.openecomp.sdc.be.model.operations.StorageException; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.stream.Collectors; + +@org.springframework.stereotype.Component("groups-operation") +public class GroupsOperation extends BaseOperation { + + private static final Logger log = Logger.getLogger(GroupsOperation.class.getName()); + + public StorageOperationStatus deleteCalculatedCapabilitiesWithProperties(String componentId, List groupDefinitions) { + Optional error = groupDefinitions.stream().map(g->removeCalculatedCapabilityFromComponent(componentId, g.getUniqueId())).filter(status-> status!=StorageOperationStatus.OK).findFirst(); + if(!error.isPresent()){ + Map extractCapabilityPropertiesFromGroups = ModelConverter.extractCapabilityPropertiesFromGroups(groupDefinitions, false); + error = extractCapabilityPropertiesFromGroups.keySet().stream().map(k->removeCalculatedCapabilityPropertiesFromComponent(componentId, k)).filter(status-> status!=StorageOperationStatus.OK).findFirst(); + } + if(error.isPresent()){ + return error.get(); + } + return StorageOperationStatus.OK; + } + + /** + * Adds the map of the calculated capabilities and the map of the calculated capabilities properties the the component on the graph + * @param componentId + * @param calculatedCapabilities + * @param calculatedCapabilitiesProperties + * @return status of the result the operation + */ + public StorageOperationStatus addCalculatedCapabilitiesWithProperties(String componentId, Map calculatedCapabilities, Map calculatedCapabilitiesProperties) { + + Optional error = calculatedCapabilities.entrySet().stream().map(e-> addElementToComponent(componentId, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst(); + if(!error.isPresent()){ + error = calculatedCapabilitiesProperties.entrySet().stream().map(e->addCalculatedCapabilityPropertiesToComponent(componentId, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst(); + } + if(error.isPresent()){ + return error.get(); + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus updateCalculatedCapabilitiesWithProperties(String componentId, Map calculatedCapabilities, Map calculatedCapabilitiesProperties) { + + Optional error = calculatedCapabilities.entrySet().stream().map(e->updateCalculatedCapabilityOfComponent(componentId, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst(); + if(!error.isPresent()){ + error = calculatedCapabilitiesProperties.entrySet().stream().map(e->updateCalculatedCapabilityPropertiesOnComponent(componentId, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst(); + } + if(error.isPresent()){ + return error.get(); + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus updateCalculatedCapabilityOfComponent(String componentId, Entry capabilities){ + if(MapUtils.isNotEmpty(capabilities.getValue().getMapToscaDataDefinition())) + return updateToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAPABILITIES, capabilities.getValue(), capabilities.getKey()); + return StorageOperationStatus.OK; + } + + private StorageOperationStatus addCalculatedCapabilityPropertiesToComponent(String componentId, Entry properties){ + if(MapUtils.isNotEmpty(properties.getValue().getMapToscaDataDefinition())) + return addToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, properties.getValue(), properties.getKey()); + return StorageOperationStatus.OK; + } + + private StorageOperationStatus updateCalculatedCapabilityPropertiesOnComponent(String componentId, Entry properties){ + if(MapUtils.isNotEmpty(properties.getValue().getMapToscaDataDefinition())) + return updateToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, properties.getValue(), properties.getKey()); + return StorageOperationStatus.OK; + } + + private StorageOperationStatus removeCalculatedCapabilityFromComponent(String componentId, String groupId){ + return deleteToscaDataDeepElementsBlockOfToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, groupId); + } + + private StorageOperationStatus removeCalculatedCapabilityPropertiesFromComponent(String componentId, String groupId){ + return deleteToscaDataDeepElementsBlockOfToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, groupId); + } + + + public Either, StorageOperationStatus> createGroups(Component component, Map groups) { + + Either, StorageOperationStatus> result = null; + Either getComponentVertex = null; + StorageOperationStatus status = null; + + getComponentVertex = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); + if (getComponentVertex.isRight()) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value())); + } + if (result == null) { + status = topologyTemplateOperation.associateGroupsToComponent(getComponentVertex.left().value(), groups); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } + if (result == null) { + result = Either.left(ModelConverter.convertToGroupDefinitions(groups)); + } + return result; + } + + public Either, StorageOperationStatus> addGroups(Component component, List groups) { + Either, StorageOperationStatus> result = null; + Either getComponentVertex; + StorageOperationStatus status; + + getComponentVertex = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); + if (getComponentVertex.isRight()) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value())); + } + if (result == null) { + status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.NAME); + + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } + + if (result == null) { + Map mapGroup = groups.stream().collect(Collectors.toMap(GroupDataDefinition::getName, x->x)); + result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup)); + } + return result; + } + + public Either, StorageOperationStatus> deleteGroups(Component component, List groups) { + Either, StorageOperationStatus> result = null; + Either getComponentVertex = null; + StorageOperationStatus status = null; + + getComponentVertex = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); + if (getComponentVertex.isRight()) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value())); + } + if (result == null) { + List groupName = groups.stream().map(GroupDataDefinition::getName).collect(Collectors.toList()); + status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.GROUPS, groupName); + + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } + + if (result == null) { + Map mapGroup = groups.stream().collect(Collectors.toMap( GroupDataDefinition::getName, x->x)); + result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup)); + } + return result; + } + + public Either, StorageOperationStatus> updateGroups(Component component, List groups, boolean promoteVersion) { + Either, StorageOperationStatus> result = null; + Either getComponentVertex = null; + StorageOperationStatus status = null; + + getComponentVertex = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); + if (getComponentVertex.isRight()) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value())); + } + if (result == null) { + groups.forEach(gr -> { + updateVersion(promoteVersion, gr); + String groupUUID = UniqueIdBuilder.generateUUID(); + gr.setGroupUUID(groupUUID); + }); + + status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.NAME); + + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } + + if (result == null) { + Map mapGroup = groups.stream().collect(Collectors.toMap( GroupDataDefinition::getName, x->x)); + result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup)); + } + return result; + } + + private void updateVersion(boolean promoteVersion, T group) { + if(promoteVersion) { + String version = group.getVersion(); + String newVersion = increaseMajorVersion(version); + group.setVersion(newVersion); + } + } + + public void updateGroupOnComponent(String componentId, GroupDefinition groupDefinition) { + GraphVertex componentVertex = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata) + .left() + .on(this::onJanusGraphError); + + StorageOperationStatus updateToscaResult = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition, + JsonPresentationFields.NAME); + + if (StorageOperationStatus.OK != updateToscaResult) { + throw new StorageException(updateToscaResult, groupDefinition.getUniqueId()); + } + + updateLastUpdateDate(componentVertex); + } + + private void updateLastUpdateDate(GraphVertex componentVertex) { + componentVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + janusGraphDao.updateVertex(componentVertex) + .left() + .on(this::onJanusGraphError); + } + + GraphVertex onJanusGraphError(JanusGraphOperationStatus janusGraphOperationStatus) { + throw new StorageException( + DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus)); + } + + public Either, StorageOperationStatus> updateGroupPropertiesOnComponent(String componentId, GroupDefinition group, List newGroupProperties) { + + Either, StorageOperationStatus> result = null; + Either getComponentVertex = null; + GraphVertex componentVertex = null; + + getComponentVertex = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); + if (getComponentVertex.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value())); + } + if (result == null) { + componentVertex = getComponentVertex.left().value(); + //update + List properties = group.getProperties(); + newGroupProperties.forEach(np -> { + Optional currentProp = properties.stream().filter(p -> p.getName().equals(np.getName())).findAny(); + if (currentProp.isPresent()) { + currentProp.get().setValue(np.getValue()); + } + }); + + StorageOperationStatus updateDataRes = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, group, JsonPresentationFields.NAME); + if (updateDataRes != StorageOperationStatus.OK) { + log.debug("Failed to update properties for group {} error {}", group.getName(), updateDataRes); + result = Either.right(updateDataRes); + } + } + if (result == null) { + componentVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + Either updateRes = janusGraphDao.updateVertex(componentVertex); + if (updateRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the component {}. Status is {} ", componentId, updateRes.right().value()); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateRes.right().value())); + } + } + if (result == null) { + result = Either.left(newGroupProperties); + } + return result; + } + + /** + * The version of the group is an integer. In order to support BC, we might get a version in a float format. + * + * @param version + * @return + */ + private String increaseMajorVersion(String version) { + + String[] versionParts = version.split(ToscaElementLifecycleOperation.VERSION_DELIMITER_REGEXP); + Integer majorVersion = Integer.parseInt(versionParts[0]); + + majorVersion++; + + return String.valueOf(majorVersion); + + } + + public Either, StorageOperationStatus> updateGroupInstances(Component component, String instanceId, List updatedGroupInstances) { + + Either, StorageOperationStatus> result = null; + StorageOperationStatus status = null; + + Either getComponentVertex = janusGraphDao + .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); + if (getComponentVertex.isRight()) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value())); + } + if (result == null) { + List pathKeys = new ArrayList<>(); + pathKeys.add(instanceId); + status = updateToscaDataDeepElementsOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, updatedGroupInstances, pathKeys, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } + if (result == null) { + result = Either.left(updatedGroupInstances); + } + return result; + } + + public Either updateGroup(Component component, GroupDefinition currentGroup) { + StorageOperationStatus status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroup, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status); + return Either.right(status); + } + return Either.left(currentGroup); + } + + public StorageOperationStatus deleteGroup(Component component, String currentGroupName) { + StorageOperationStatus status = deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroupName, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group {} of component {}. The status is}. ", currentGroupName, component.getName(), status); + } + return status; + } + + public Either addGroup(Component component, GroupDefinition currentGroup) { + StorageOperationStatus status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroup, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status); + return Either.right(status); + } + return Either.left(currentGroup); + } + + public Either updateGroupInstancePropertyValuesOnGraph(String componentId, String instanceId, GroupInstance oldGroupInstance, List newProperties) { + + Either getComponentVertex = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); + if (getComponentVertex.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value())); + } + + List propertiesOld = oldGroupInstance.getProperties(); + newProperties.forEach(np -> { + Optional prop = propertiesOld.stream().filter(p -> p.getName().equals(np.getName())).findFirst(); + if (prop.isPresent()) { + prop.get().setValue(np.getValue()); + } + }); + GroupInstanceDataDefinition groupInstanceDataDefinition = new GroupInstanceDataDefinition(oldGroupInstance); + List pathKeys = new ArrayList<>(); + pathKeys.add(instanceId); + StorageOperationStatus updateDataRes = updateToscaDataDeepElementOfToscaElement(componentId, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, groupInstanceDataDefinition, pathKeys, JsonPresentationFields.NAME); + if (updateDataRes != StorageOperationStatus.OK) { + log.debug("Failed to update properties for group instance {} error {}", oldGroupInstance.getName(), updateDataRes); + return Either.right(updateDataRes); + } + return Either.left(oldGroupInstance); + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InstancesOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InstancesOperation.java new file mode 100644 index 0000000000..3378e03318 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InstancesOperation.java @@ -0,0 +1,25 @@ +/*- + * ============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.jsonjanusgraph.operations; + +public class InstancesOperation extends BaseOperation { + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InterfaceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InterfaceOperation.java new file mode 100644 index 0000000000..0b6f48f051 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InterfaceOperation.java @@ -0,0 +1,98 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * 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. + */ + +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; + +@org.springframework.stereotype.Component("interfaces-operation") +public class InterfaceOperation extends BaseOperation { + + public Either, StorageOperationStatus> addInterfaces(String componentId, + List interfaceDefinitions) { + return addOrUpdateInterfaces(false, componentId, interfaceDefinitions); + } + + private Either, StorageOperationStatus> addOrUpdateInterfaces(boolean isUpdateAction, + String componentId, List interfaceDefinitions) { + + List interfaceDataDefinitions = + interfaceDefinitions.stream().map(InterfaceDataDefinition::new).collect(Collectors.toList()); + StorageOperationStatus statusRes = + performUpdateToscaAction(isUpdateAction, componentId, interfaceDataDefinitions, EdgeLabelEnum.INTERFACE, + VertexTypeEnum.INTERFACE); + if (!statusRes.equals(StorageOperationStatus.OK)) { + return Either.right(statusRes); + } + return Either.left(interfaceDefinitions); + } + + private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, String componentId, + List toscaDataList, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) { + if (isUpdate) { + return updateToscaDataOfToscaElement(componentId, edgeLabel, vertexLabel, toscaDataList, + JsonPresentationFields.UNIQUE_ID); + } else { + return addToscaDataToToscaElement(componentId, edgeLabel, vertexLabel, toscaDataList, + JsonPresentationFields.UNIQUE_ID); + } + } + + public Either, StorageOperationStatus> updateInterfaces(String componentId, + List interfaceDefinitions) { + return addOrUpdateInterfaces(true, componentId, interfaceDefinitions); + } + + public Either deleteInterface(String componentId, String interfacesToDelete) { + + StorageOperationStatus statusRes = deleteToscaDataElements(componentId, EdgeLabelEnum.INTERFACE, + Collections.singletonList(interfacesToDelete)); + if (!statusRes.equals(StorageOperationStatus.OK)) { + return Either.right(statusRes); + } + + Either, JanusGraphOperationStatus> componentEither = + getDataFromGraph(componentId, EdgeLabelEnum.INTERFACE); + if (componentEither.isRight()) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(componentEither.right().value())); + } + + Map interfaceDataDefinitionMap = componentEither.left().value(); + if (MapUtils.isEmpty(interfaceDataDefinitionMap)) { + statusRes = removeToscaData(componentId, EdgeLabelEnum.INTERFACE, VertexTypeEnum.INTERFACE); + if (!statusRes.equals(StorageOperationStatus.OK)) { + return Either.right(statusRes); + } + } + + return Either.left(interfacesToDelete); + } + +} \ No newline at end of file diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeFilterOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeFilterOperation.java new file mode 100644 index 0000000000..13ad534bbb --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeFilterOperation.java @@ -0,0 +1,176 @@ +/*- + * ============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.jsonjanusgraph.operations; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import fj.data.Either; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterPropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.log.wrappers.Logger; + +@org.springframework.stereotype.Component("service-filter-operations") +public class NodeFilterOperation extends BaseOperation { + + private static Logger logger = Logger.getLogger(NodeFilterOperation.class); + + public Either, StorageOperationStatus> deleteNodeFilters(Service service, + Set componentInstanceIds) { + Either getComponentVertex; + Either getNodeFilterVertex; + StorageOperationStatus status; + + getComponentVertex = janusGraphDao.getVertexById(service.getUniqueId(), JsonParseFlagEnum.NoParse); + if (getComponentVertex.isRight()) { + return Either.right( + DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value())); + } + + getNodeFilterVertex = + janusGraphDao.getChildVertex(getComponentVertex.left().value(), EdgeLabelEnum.NODE_FILTER_TEMPLATE, + JsonParseFlagEnum.NoParse); + if (getNodeFilterVertex.isLeft()) { + status = deleteToscaDataElements(service.getUniqueId(), EdgeLabelEnum.NODE_FILTER_TEMPLATE, + new ArrayList<>(componentInstanceIds)); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + } + + return Either.left(componentInstanceIds); + } + + + public Either deleteNodeFilter(Service service, String componentInstanceId) { + final Either, StorageOperationStatus> listStorageOperationStatusEither = + deleteNodeFilters(service, ImmutableSet.of(componentInstanceId)); + if (listStorageOperationStatusEither.isRight()) { + return Either.right(listStorageOperationStatusEither.right().value()); + } + return Either.left(componentInstanceId); + } + + + public Either createNodeFilter(String serviceId, + String componentInstanceId) { + CINodeFilterDataDefinition nodeFilterDataDefinition = new CINodeFilterDataDefinition(); + return addOrUpdateNodeFilter(false, serviceId, componentInstanceId, nodeFilterDataDefinition); + } + + public Either deleteConstraint(String serviceId, + String componentInstanceId, CINodeFilterDataDefinition nodeFilterDataDefinition, int propertyIndex) { + ListDataDefinition properties = + nodeFilterDataDefinition.getProperties(); + properties.getListToscaDataDefinition().remove(propertyIndex); + nodeFilterDataDefinition.setProperties(properties); + return addOrUpdateNodeFilter(true, serviceId, componentInstanceId, nodeFilterDataDefinition); + } + + public Either addNewProperty(String serviceId, + String componentInstanceId, CINodeFilterDataDefinition nodeFilterDataDefinition, + RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition) { + ListDataDefinition properties = + nodeFilterDataDefinition.getProperties(); + if (properties == null) { + properties = new ListDataDefinition<>(); + nodeFilterDataDefinition.setProperties(properties); + } + properties.getListToscaDataDefinition().add(requirementNodeFilterPropertyDataDefinition); + nodeFilterDataDefinition.setProperties(properties); + return addOrUpdateNodeFilter(true, serviceId, componentInstanceId, nodeFilterDataDefinition); + } + + public Either updateProperties(String serviceId, + String componentInstanceId, CINodeFilterDataDefinition nodeFilterDataDefinition, + List requirementNodeFilterPropertyDataDefinition) { + ListDataDefinition properties = + nodeFilterDataDefinition.getProperties(); + properties.getListToscaDataDefinition().clear(); + properties.getListToscaDataDefinition().addAll(requirementNodeFilterPropertyDataDefinition); + nodeFilterDataDefinition.setProperties(properties); + return addOrUpdateNodeFilter(true, serviceId, componentInstanceId, nodeFilterDataDefinition); + } + + public Either updateNodeFilter(String serviceId, + String componentInstanceId, CINodeFilterDataDefinition ciNodeFilterDataDefinition) { + return addOrUpdateNodeFilter(true, serviceId, componentInstanceId, ciNodeFilterDataDefinition); + } + + private Either addOrUpdateNodeFilter(boolean isUpdateAction, + String serviceId, String componentInstanceId, CINodeFilterDataDefinition ciNodeFilterDataDefinition) { + + StorageOperationStatus statusRes; + Either getToscaElementRes; + + getToscaElementRes = janusGraphDao.getVertexById(serviceId, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + JanusGraphOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(logger, CommonUtility.LogLevelEnum.DEBUG, + "Failed to get tosca element {} upon adding the properties. Status is {}. ", serviceId, status); + statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + return Either.right(statusRes); + } + GraphVertex serviceVertex = getToscaElementRes.left().value(); + ciNodeFilterDataDefinition.setID(componentInstanceId); + statusRes = performUpdateToscaAction(isUpdateAction, serviceVertex, ImmutableList.of(ciNodeFilterDataDefinition)); + if (!statusRes.equals(StorageOperationStatus.OK)) { + janusGraphDao.rollback(); + logger.error( + " Failed to perform tosca update for node filter in service {} , component instance {}. status is {}", + serviceId, componentInstanceId, statusRes); + return Either.right(statusRes); + } + janusGraphDao.commit(); + return Either.left(ciNodeFilterDataDefinition); + + } + + + private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, GraphVertex graphVertex, + List toscaDataList) { + if (isUpdate) { + return updateToscaDataOfToscaElement(graphVertex, EdgeLabelEnum.NODE_FILTER_TEMPLATE, + VertexTypeEnum.NODE_FILTER_TEMPLATE, toscaDataList, JsonPresentationFields.UNIQUE_ID); + } else { + return addToscaDataToToscaElement(graphVertex, EdgeLabelEnum.NODE_FILTER_TEMPLATE, + VertexTypeEnum.NODE_FILTER_TEMPLATE, toscaDataList, JsonPresentationFields.UNIQUE_ID); + } + } + +} + + + diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperation.java new file mode 100644 index 0000000000..2861337aec --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperation.java @@ -0,0 +1,2417 @@ +/*- + * ============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.jsonjanusgraph.operations; + +import org.janusgraph.core.JanusGraphVertex; +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.RelationshipImpl; +import org.openecomp.sdc.be.model.RelationshipInfo; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.NodeType; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.ValidationUtils; + +import java.io.IOException; +import java.util.*; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.BiPredicate; +import java.util.stream.Collectors; + +@org.springframework.stereotype.Component("node-template-operation") +public class NodeTemplateOperation extends BaseOperation { + private static final String FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR = "Failed to fetch container vertex {} error {}"; + private static final String FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE = "Failed to update topology template {} with new component instance {}. "; + private static final String ARTIFACT_PLACEHOLDER_TYPE = "type"; + private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName"; + private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description"; + public static final String HEAT_ENV_NAME = "heatEnv"; + public static final String HEAT_VF_ENV_NAME = "VfHeatEnv"; + public static final String HEAT_ENV_SUFFIX = "env"; + private static Integer defaultHeatTimeout; + public static final Integer NON_HEAT_TIMEOUT = 0; + + private static final Logger log = Logger.getLogger(NodeTemplateOperation.class.getName()); + + public NodeTemplateOperation() { + defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); + if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) { + defaultHeatTimeout = 60; + } + } + + public static Integer getDefaultHeatTimeout() { + return defaultHeatTimeout; + } + + public Either, StorageOperationStatus> addComponentInstanceToTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, String instanceNumberSuffix, ComponentInstance componentInstance, + boolean allowDeleted, User user) { + + Either, StorageOperationStatus> result = null; + Either addComponentInstanceRes = null; + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to create component instance {} in component {}", componentInstance, container.getUniqueId()); + ComponentInstanceDataDefinition componentInstanceData = null; + Either newInstanceNameRes = null; + + Either metadataVertex = janusGraphDao + .getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseJson); + if (metadataVertex.isRight()) { + JanusGraphOperationStatus status = metadataVertex.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; + } + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + + if (result == null) { + + newInstanceNameRes = buildValidateInstanceName(container, originToscaElement, componentInstance, instanceNumberSuffix); + if (newInstanceNameRes.isRight()) { + result = Either.right(newInstanceNameRes.right().value()); + } + } + if (result == null) { + componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(), newInstanceNameRes.left().value(), true, originToscaElement); + + addComponentInstanceRes = addComponentInstanceToTopologyTemplate(container, originToscaElement, componentInstanceData, metadataVertex.left().value(), allowDeleted, user); + + if (addComponentInstanceRes.isRight()) { + StorageOperationStatus status = addComponentInstanceRes.right().value(); + if (status == StorageOperationStatus.NOT_FOUND) { + status = StorageOperationStatus.INVALID_ID; + } + result = Either.right(status); + } + if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { + TopologyTemplate updatedContainer = addComponentInstanceRes.left().value(); + result = addServerCapAndReqToProxyServerInstance(updatedContainer, componentInstance, componentInstanceData); + if(result.isRight()) { + return result; + } + + result = addServiceInstancePropertiesToProxyServiceInstance(updatedContainer, componentInstance); + if(result.isRight()) { + return result; + } + + result = addServiceInstanceInputsToProxyServiceInstance(updatedContainer, componentInstance); + if(result.isRight()) { + return result; + } + + result = addServiceInstanceInterfacesToProxyServiceInstance(updatedContainer, componentInstance); + if(result.isRight()) { + return result; + } + + } + } + if (result == null) { + result = Either.left(new ImmutablePair<>(addComponentInstanceRes.left().value(), componentInstanceData.getUniqueId())); + } + return result; + } + + private Either, StorageOperationStatus> addServerCapAndReqToProxyServerInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance, + + ComponentInstanceDataDefinition componentInstanceData) { + + Either, StorageOperationStatus> result; + + Map calcCap = updatedContainer.getCalculatedCapabilities(); + Map calcReg = updatedContainer.getCalculatedRequirements(); + Map calcCapProp = updatedContainer.getCalculatedCapabilitiesProperties(); + + Map> additionalCap = componentInstance.getCapabilities(); + Map> additionalReq = componentInstance.getRequirements(); + + MapListCapabilityDataDefinition allCalculatedCap = calcCap == null || !calcCap.containsKey(componentInstanceData.getUniqueId()) ? new MapListCapabilityDataDefinition() : calcCap.get(componentInstanceData.getUniqueId()); + /******** capability ****************************/ + StorageOperationStatus status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, componentInstanceData.getUniqueId()); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status); + return Either.right(status); + } + + if (additionalCap != null && !additionalCap.isEmpty()) { + + Map serverCap = additionalCap.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, en -> new ListCapabilityDataDefinition(en.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())))); + + serverCap.entrySet().forEach(entryPerType -> + entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> { + cap.addToPath(componentInstance.getUniqueId()); + allCalculatedCap.add(entryPerType.getKey(), cap); + })); + + + addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, componentInstance.getUniqueId()); + + /******** capability property ****************************/ + status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, componentInstanceData.getUniqueId()); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty properties for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status); + return Either.right(status); + } + + MapCapabilityProperty allCalculatedCapProp = calcCapProp == null || !calcCapProp.containsKey(componentInstanceData.getUniqueId()) ? new MapCapabilityProperty() : calcCapProp.get(componentInstanceData.getUniqueId()); + + additionalCap.forEach(new BiConsumer>() { + @Override + public void accept(String s, List caps) { + + if (caps != null && !caps.isEmpty()) { + + MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); + + for (CapabilityDefinition cap : caps) { + List capPrps = cap.getProperties(); + if (capPrps != null) { + + for (ComponentInstanceProperty cip : capPrps) { + dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip)); + } + + StringBuilder sb = new StringBuilder(componentInstance.getUniqueId()); + sb.append(ModelConverter.CAP_PROP_DELIM); + + sb.append(cap.getOwnerId()); + + sb.append(ModelConverter.CAP_PROP_DELIM).append(s).append(ModelConverter.CAP_PROP_DELIM).append(cap.getName()); + allCalculatedCapProp.put(sb.toString(), dataToCreate); + } + } + + } + + } + }); + + addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, allCalculatedCapProp, componentInstance.getUniqueId()); + } + + /******** Requirements property ****************************/ + if (additionalReq != null && !additionalReq.isEmpty()) { + + MapListRequirementDataDefinition allCalculatedReq = calcReg == null || !calcReg.containsKey(componentInstanceData.getUniqueId()) ? new MapListRequirementDataDefinition() : calcReg.get(componentInstanceData.getUniqueId()); + status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceData.getUniqueId()); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated Requirements for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status); + return Either.right(status); + } + + Map serverReq = additionalReq.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, en -> new ListRequirementDataDefinition(en.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())))); + + serverReq.entrySet().forEach(entryPerType -> + entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> { + cap.addToPath(componentInstance.getUniqueId()); + allCalculatedReq.add(entryPerType.getKey(), cap); + })); + + + addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, componentInstance.getUniqueId()); + + } + + Either updatedComponentInstanceRes = topologyTemplateOperation.getToscaElement(updatedContainer.getUniqueId()); + if (updatedComponentInstanceRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ", updatedContainer.getName(), componentInstance.getName()); + result = Either.right(updatedComponentInstanceRes.right().value()); + } + result = Either.left(new ImmutablePair<>((TopologyTemplate) updatedComponentInstanceRes.left().value(), componentInstanceData.getUniqueId())); + return result; + } + + private Either buildValidateInstanceName(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance, String instanceNumberSuffix) { + + Either result = null; + String instanceName = componentInstance.getName(); + if (StringUtils.isEmpty(instanceName) || instanceName.equalsIgnoreCase(originToscaElement.getName()) || componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { + instanceName = buildComponentInstanceName(instanceNumberSuffix, instanceName); + } else if (!isUniqueInstanceName(container, componentInstance.getName())) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create component instance with name {} on component container {}. The instance with the same name already exists. ", componentInstance.getName(), container.getName()); + result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS); + } + if (result == null) { + result = Either.left(instanceName); + } + return result; + } + + private Either, StorageOperationStatus> addServiceInstancePropertiesToProxyServiceInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance) { + + List propertiesList = componentInstance.getProperties(); + + if (propertiesList != null && !propertiesList.isEmpty()) { + Map propertiesMap = propertiesList.stream().map(PropertyDataDefinition::new) + .collect(Collectors.toMap( + PropertyDataDefinition::getName, i -> i)); + MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(propertiesMap); + Map instPropertiesMap = new HashMap<>(); + instPropertiesMap.put(componentInstance.getUniqueId(), instProperties); + updatedContainer.setInstProperties(instPropertiesMap); + Either getToscaElementRes = janusGraphDao + .getVertexById(updatedContainer.getUniqueId(), JsonParseFlagEnum.NoParse); + if(getToscaElementRes.isLeft()){ + deleteToscaDataDeepElementsBlockToToscaElement(getToscaElementRes.left().value(), EdgeLabelEnum.INST_PROPERTIES, + VertexTypeEnum.INST_PROPERTIES, componentInstance.getUniqueId()); + } + StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), + EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, instProperties, + componentInstance.getUniqueId()); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + + + } + return Either.left(new ImmutablePair<>(updatedContainer, componentInstance.getUniqueId())); + } + + private Either, StorageOperationStatus> addServiceInstanceInputsToProxyServiceInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance) { + + List inputsList = componentInstance.getInputs(); + + if (CollectionUtils.isNotEmpty(inputsList)) { + Map inputsMap = inputsList.stream().map( + PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, i -> i)); + MapPropertiesDataDefinition instInputs = new MapPropertiesDataDefinition(inputsMap); + Map instInputsMap = new HashMap<>(); + instInputsMap.put(componentInstance.getUniqueId(), instInputs); + updatedContainer.setInstInputs(instInputsMap); + + StorageOperationStatus status = + addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), + EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, instInputs, + componentInstance.getUniqueId()); + if(status != StorageOperationStatus.OK) { + return Either.right(status); + } + } + + return Either.left(new ImmutablePair<>(updatedContainer, componentInstance.getUniqueId())); + } + + private Either, StorageOperationStatus> addServiceInstanceInterfacesToProxyServiceInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance) { + Map interfaces = componentInstance.getInterfaces(); + + if(MapUtils.isNotEmpty(interfaces)){ + Map interfacesMap = interfaces.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> (InterfaceDataDefinition) e.getValue())); + MapInterfaceDataDefinition instInterfaces = new MapInterfaceDataDefinition(interfacesMap); + + Map instInterfacesMap = new HashMap<>(); + instInterfacesMap.put(componentInstance.getUniqueId(), instInterfaces); + updatedContainer.setComponentInstInterfaces(instInterfacesMap); + + StorageOperationStatus status = + addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), + EdgeLabelEnum.INST_INTERFACES, VertexTypeEnum.INST_INTERFACES, instInterfaces, + componentInstance.getUniqueId()); + + if(status != StorageOperationStatus.OK) { + return Either.right(status); + } + } + + return Either.left(new ImmutablePair<>(updatedContainer, componentInstance.getUniqueId())); + } + + public Either addComponentInstanceToTopologyTemplate( + TopologyTemplate container, ToscaElement originToscaElement, + ComponentInstanceDataDefinition componentInstance, GraphVertex metadataVertex, boolean allowDeleted, + User user) { + + Either result = null; + Either updateContainerComponentRes = null; + String containerComponentId = container.getUniqueId(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to create component instance {} in component {}", componentInstance, containerComponentId); + String instOriginComponentId = componentInstance.getComponentUid(); + Either updateElement = null; + + Boolean isDeleted = (Boolean) originToscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED); + + if (!allowDeleted && (isDeleted != null) && isDeleted) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance", instOriginComponentId); + result = Either.right(StorageOperationStatus.INVALID_ID); + } + Boolean isArchived = originToscaElement.isArchived(); + if ( isArchived != null && isArchived ){ + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create instance {}. Origin {} component is archived . ", componentInstance.getName(), originToscaElement.getName()); + result = Either.right(StorageOperationStatus.COMPONENT_IS_ARCHIVED); + } + + if (result == null) { + container.addComponentInstance(componentInstance); + metadataVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + topologyTemplateOperation.fillToscaElementVertexData(metadataVertex, container, JsonParseFlagEnum.ParseAll); + updateElement = janusGraphDao.updateVertex(metadataVertex); + if (updateElement.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(), componentInstance.getName()); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value())); + } + } + if (result == null) { + Either addToscaDataRes = addComponentInstanceToscaDataToContainerComponent(originToscaElement, componentInstance, updateElement.left().value(), user); + if (addToscaDataRes.isRight()) { + result = Either.right(addToscaDataRes.right().value()); + } + } + if (result == null) { + StorageOperationStatus createInstanceEdge = createInstanceEdge(metadataVertex, componentInstance); + result = createInstanceEdge == StorageOperationStatus.OK ? null : Either.right(createInstanceEdge); + } + + if (result == null) { + updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId); + if (updateContainerComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ", container.getName(), componentInstance.getName()); + result = Either.right(updateContainerComponentRes.right().value()); + } + } + if (result == null) { + result = Either.left((TopologyTemplate) updateContainerComponentRes.left().value()); + } + return result; + } + + public Either, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance) { + + Either, StorageOperationStatus> result = null; + Either updateContainerComponentRes = null; + + String containerComponentId = container.getUniqueId(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstance, containerComponentId); + ComponentInstanceDataDefinition componentInstanceData = null; + + Either metadataVertex = janusGraphDao + .getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata); + if (metadataVertex.isRight()) { + JanusGraphOperationStatus status = metadataVertex.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; + } + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + if (result == null) { + componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(), componentInstance.getName(), false, originToscaElement); + container.addComponentInstance(componentInstanceData); + metadataVertex.left().value().setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + topologyTemplateOperation.fillToscaElementVertexData(metadataVertex.left().value(), container, JsonParseFlagEnum.ParseAll); + Either updateElement = janusGraphDao + .updateVertex(metadataVertex.left().value()); + if (updateElement.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(), componentInstance.getName()); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value())); + } + } + if (result == null) { + updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId); + if (updateContainerComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", container.getName(), componentInstance.getName()); + result = Either.right(updateContainerComponentRes.right().value()); + } + } + if (result == null) { + result = Either.left(new ImmutablePair<>((TopologyTemplate) updateContainerComponentRes.left().value(), componentInstanceData.getUniqueId())); + } + return result; + } + + public Either updateComponentInstanceMetadataOfTopologyTemplate(TopologyTemplate container, ComponentParametersView filter) { + + Either result = null; + Either updateContainerComponentRes = null; + + String containerComponentId = container.getUniqueId(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata of container component {}", containerComponentId); + + Either metadataVertex = janusGraphDao + .getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata); + if (metadataVertex.isRight()) { + JanusGraphOperationStatus status = metadataVertex.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; + } + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + if (result == null) { + metadataVertex.left().value().setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + topologyTemplateOperation.fillToscaElementVertexData(metadataVertex.left().value(), container, JsonParseFlagEnum.ParseAll); + Either updateElement = janusGraphDao + .updateVertex(metadataVertex.left().value()); + if (updateElement.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {}. ", container.getName()); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value())); + } + } + if (result == null) { + updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId, filter); + if (updateContainerComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {}. ", container.getName()); + result = Either.right(updateContainerComponentRes.right().value()); + } + } + if (result == null) { + result = Either.left((TopologyTemplate) updateContainerComponentRes.left().value()); + } + return result; + } + + public Either, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(TopologyTemplate container, String componentInstanceId) { + + Either, StorageOperationStatus> result = null; + Either updateContainerComponentRes = null; + + String containerComponentId = container.getUniqueId(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstanceId, containerComponentId); + + Either metadataVertex = janusGraphDao + .getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata); + if (metadataVertex.isRight()) { + JanusGraphOperationStatus status = metadataVertex.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; + } + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + GraphVertex containerV = null; + ComponentInstanceDataDefinition removedComponentInstance = null; + if (result == null) { + removedComponentInstance = container.getComponentInstances().remove(componentInstanceId); + containerV = metadataVertex.left().value(); + StorageOperationStatus status = removeRelationsOfInstance(container, componentInstanceId, containerV); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete relation for component instance {} in container. error {}", componentInstanceId, container.getUniqueId(), status); + result = Either.right(status); + } + + containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + topologyTemplateOperation.fillToscaElementVertexData(containerV, container, JsonParseFlagEnum.ParseAll); + Either updateElement = janusGraphDao.updateVertex(containerV); + if (updateElement.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(), componentInstanceId); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value())); + } + } + if (result == null) { + StorageOperationStatus status = deleteComponentInstanceToscaDataFromContainerComponent(containerV, componentInstanceId); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete data for instance {} in container {}. error {] ", componentInstanceId, container.getUniqueId(), status); + return Either.right(status); + } + ComponentInstance componentInstance = new ComponentInstance(removedComponentInstance); + StorageOperationStatus createInstanceEdge = removeInstanceEdge(containerV, componentInstance); + result = createInstanceEdge == StorageOperationStatus.OK ? null : Either.right(createInstanceEdge); + } + if (result == null) { + updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId); + if (updateContainerComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} after deleting the component instance {}. ", container.getName(), componentInstanceId); + result = Either.right(updateContainerComponentRes.right().value()); + } + } + if (result == null) { + result = Either.left(new ImmutablePair<>((TopologyTemplate) updateContainerComponentRes.left().value(), componentInstanceId)); + } + return result; + } + + private StorageOperationStatus removeRelationsOfInstance(TopologyTemplate container, String ciToRemove, GraphVertex containerV) { + CompositionDataDefinition composition = container.getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()); + if (composition != null) { + Map relations = composition.getRelations(); + if (MapUtils.isNotEmpty(relations)) { + Either>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); + if (capResult.isRight()) { + return capResult.right().value(); + + } + Map calculatedCapabilty = capResult.left().value().getRight(); + + Either>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); + if (capFullResult.isRight()) { + return capFullResult.right().value(); + + } + Map fullFilledCapabilty = capFullResult.left().value().getRight(); + + Either>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); + if (reqResult.isRight()) { + return reqResult.right().value(); + } + Map calculatedRequirement = reqResult.left().value().getRight(); + + Either>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); + if (reqResult.isRight()) { + return reqResult.right().value(); + } + Map fullfilledRequirement = reqFullResult.left().value().getRight(); + + Iterator> iterator = relations.entrySet().iterator(); + while (iterator.hasNext()) { + Entry relation = iterator.next(); + RelationshipInstDataDefinition relationToDelete = relation.getValue(); + if (relationToDelete.getFromId().equals(ciToRemove) || relationToDelete.getToId().equals(ciToRemove)) { + iterator.remove(); + if (relationToDelete.getFromId().equals(ciToRemove)) { + updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, ciToRemove, relationToDelete, null); + updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, relationToDelete.getToId(), relationToDelete, null); + } + if (relationToDelete.getToId().equals(ciToRemove)) { + updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, relationToDelete.getFromId(), relationToDelete, null); + updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, ciToRemove, relationToDelete, null); + } + } + } + return updateAllAndCalculatedCapReqOnGraph(container.getUniqueId(), containerV, capResult, capFullResult, reqResult, reqFullResult); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus deleteComponentInstanceToscaDataFromContainerComponent(GraphVertex containerV, String componentInstanceId) { + StorageOperationStatus status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty properties for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove fullfilled capabilities for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove attributes for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove properties for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance inputs for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance deployment artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INSTANCE_ARTIFACTS, VertexTypeEnum.INSTANCE_ARTIFACTS, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance external refs for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_INTERFACES, + VertexTypeEnum.INST_INTERFACES, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, + "Failed to remove service instance interfaces for instance {} in container {}. " + + "error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + return StorageOperationStatus.OK; + } + + protected Either addComponentInstanceToscaDataToContainerComponent(ToscaElement originToscaElement, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user) { + + Either result; + StorageOperationStatus status; + if (originToscaElement.getToscaType() == ToscaElementTypeEnum.NODE_TYPE) { + status = addComponentInstanceToscaDataToNodeTypeContainer((NodeType) originToscaElement, componentInstance, updatedContainerVertex); + } else { + status = addComponentInstanceToscaDataToTopologyTemplateContainer((TopologyTemplate) originToscaElement, componentInstance, updatedContainerVertex); + } + if (status == StorageOperationStatus.OK) { + result = Either.left(updatedContainerVertex); + } else { + result = Either.right(status); + } + return result; + } + + private StorageOperationStatus addComponentInstanceToscaDataToTopologyTemplateContainer(TopologyTemplate originTopologyTemplate, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) { + + StorageOperationStatus status; + + status = addCalculatedCapReqFromTopologyTemplate(originTopologyTemplate, componentInstance, updatedContainerVertex); + + if (status != StorageOperationStatus.OK) { + + return status; + } + + MapPropertiesDataDefinition instInputs = new MapPropertiesDataDefinition(originTopologyTemplate.getInputs()); + MapPropertiesDataDefinition instInputsAsProperties = turnInputsIntoProperties(instInputs); + + status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, instInputsAsProperties, componentInstance.getUniqueId()); + if (status != StorageOperationStatus.OK) { + return status; + } + + return status; + } + + private MapPropertiesDataDefinition turnInputsIntoProperties(MapPropertiesDataDefinition instInput){ + if (instInput.getMapToscaDataDefinition() != null) { + for (PropertyDataDefinition currProp : instInput.getMapToscaDataDefinition().values()){ + String temp = currProp.getValue(); + currProp.setValue(currProp.getDefaultValue()); + currProp.setDefaultValue(temp); + } + } + return instInput; + } + + private MapListCapabilityDataDefinition prepareCalculatedCapabiltyForTopologyTemplate( + Map capabilities, + ComponentInstanceDataDefinition componentInstance, + MapListCapabilityDataDefinition calculatedCap) { + MapListCapabilityDataDefinition allCalculatedCap = + new MapListCapabilityDataDefinition(calculatedCap); + populateCapability(capabilities, componentInstance, allCalculatedCap); + return allCalculatedCap; + } + + private void populateCapability(Map capabilities, + ComponentInstanceDataDefinition componentInstance, + MapListCapabilityDataDefinition allCalculatedCap) { + capabilities.forEach((key, value) -> { + List listCapabilities = value.getListToscaDataDefinition() + .stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()); + listCapabilities.forEach(cap -> { + cap.setSource(componentInstance.getComponentUid()); + cap.addToPath(componentInstance.getUniqueId()); + cap.setOwnerId(componentInstance.getUniqueId()); + cap.setOwnerName(componentInstance.getName()); + cap.setLeftOccurrences(cap.getMaxOccurrences()); + allCalculatedCap.add(key, cap); + }); + }); + } + + private MapListRequirementDataDefinition prepareCalculatedRequirementForTopologyTemplate( + Map requirements, + ComponentInstanceDataDefinition componentInstance, + MapListRequirementDataDefinition calculatedReqs) { + MapListRequirementDataDefinition allCalculatedReq = + new MapListRequirementDataDefinition(calculatedReqs); + + populateRequirement(requirements, componentInstance, allCalculatedReq); + return allCalculatedReq; + } + private void populateRequirement(Map requirements, + ComponentInstanceDataDefinition componentInstance, + MapListRequirementDataDefinition allCalculatedReq) { + requirements.forEach((key, value) -> { + List listRequirements = value.getListToscaDataDefinition() + .stream().map(RequirementDataDefinition::new).collect(Collectors.toList()); + listRequirements.forEach(req -> { + req.setSource(componentInstance.getComponentUid()); + req.addToPath(componentInstance.getUniqueId()); + req.setOwnerId(componentInstance.getUniqueId()); + req.setOwnerName(componentInstance.getName()); + req.setLeftOccurrences(req.getMaxOccurrences()); + allCalculatedReq.add(key, req); + }); + }); + } + + + + private StorageOperationStatus addCalculatedCapReqFromTopologyTemplate(TopologyTemplate originTopologyTemplate, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) { + Map calculatedCapabilities = originTopologyTemplate.getCalculatedCapabilities(); + + MapListCapabilityDataDefinition allCalculatedCap = new MapListCapabilityDataDefinition(); + if (calculatedCapabilities != null) { + calculatedCapabilities.forEach((key1, value1) -> { + Map mapByType = value1.getMapToscaDataDefinition(); + mapByType.forEach((key, value) -> value.getListToscaDataDefinition().forEach(cap -> { + cap.addToPath(componentInstance.getUniqueId()); + allCalculatedCap.add(key, cap); + })); + }); + } + MapListCapabilityDataDefinition allCaps; + Map capabilities = originTopologyTemplate.getCapabilities(); + if (MapUtils.isNotEmpty(capabilities)) { + allCaps = prepareCalculatedCapabiltyForTopologyTemplate(capabilities, componentInstance, + allCalculatedCap); + } else { + allCaps = new MapListCapabilityDataDefinition(allCalculatedCap); + } + if(!allCaps.isEmpty()) { + StorageOperationStatus calculatedCapabilitiesResult = + addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, + EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, + allCaps, componentInstance.getUniqueId()); + if (calculatedCapabilitiesResult != StorageOperationStatus.OK) { + return calculatedCapabilitiesResult; + } + MapListCapabilityDataDefinition fullCalculatedCap = new MapListCapabilityDataDefinition(); + calculatedCapabilitiesResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, + EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, + fullCalculatedCap, componentInstance.getUniqueId()); + if (calculatedCapabilitiesResult != StorageOperationStatus.OK) { + return calculatedCapabilitiesResult; + } + } + Map calculatedRequirements = + originTopologyTemplate.getCalculatedRequirements(); + MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition(); + if (calculatedRequirements != null) { + calculatedRequirements.forEach((key, value) -> { + Map mapByType = + value.getMapToscaDataDefinition(); + mapByType.forEach((key1, value1) -> value1.getListToscaDataDefinition().forEach(req -> { + req.addToPath(componentInstance.getUniqueId()); + allCalculatedReq.add(key1, req); + })); + }); + + } + + MapListRequirementDataDefinition allReqs; + Map requirements = originTopologyTemplate.getRequirements(); + if (MapUtils.isNotEmpty(requirements)) { + allReqs = prepareCalculatedRequirementForTopologyTemplate(requirements, + componentInstance, allCalculatedReq); + } else + allReqs = new MapListRequirementDataDefinition(allCalculatedReq); + + if(!allReqs.isEmpty()) { + StorageOperationStatus calculatedRequirementResult = + addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, + EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, + allReqs, componentInstance.getUniqueId()); + if (calculatedRequirementResult != StorageOperationStatus.OK) { + return calculatedRequirementResult; + } + MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition(); + calculatedRequirementResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, + EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, + fullCalculatedReq, + componentInstance.getUniqueId()); + if (calculatedRequirementResult != StorageOperationStatus.OK) { + return calculatedRequirementResult; + } + } + Map calculatedCapabilitiesProperties = originTopologyTemplate.getCalculatedCapabilitiesProperties(); + Map updateKeyMap = new HashMap<>(); + + if (calculatedCapabilitiesProperties != null && !calculatedCapabilitiesProperties.isEmpty()) { + for (MapCapabilityProperty map : calculatedCapabilitiesProperties.values()) { + for (Entry entry : map.getMapToscaDataDefinition().entrySet()) { + String newKey = (componentInstance.getUniqueId() + ModelConverter.CAP_PROP_DELIM + entry.getKey()); + updateKeyMap.put(newKey, entry.getValue()); + } + } + } + Map capabilitiesProperties = + originTopologyTemplate.getCapabilitiesProperties(); + Map updateKeyMapCapabilitiesProperties; + if (MapUtils.isNotEmpty(capabilitiesProperties)) { + updateKeyMapCapabilitiesProperties = capabilitiesProperties.entrySet().stream() + .collect(Collectors.toMap(e -> createCapPropertyKey(e.getKey(), + componentInstance.getUniqueId()), Entry::getValue)); + } + else { + updateKeyMapCapabilitiesProperties = new HashMap<>(); + } + updateKeyMap.putAll(updateKeyMapCapabilitiesProperties); + MapCapabilityProperty mapCapabilityProperty = new MapCapabilityProperty(updateKeyMap); + + if(MapUtils.isNotEmpty(capabilitiesProperties) || MapUtils.isNotEmpty(calculatedCapabilitiesProperties )) { + StorageOperationStatus calculatedResult = + addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, + EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, + VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabilityProperty, + componentInstance.getUniqueId()); + if (calculatedResult != StorageOperationStatus.OK) { + return calculatedResult; + } + } + return StorageOperationStatus.OK; + } + private StorageOperationStatus addComponentInstanceToscaDataToNodeTypeContainer(NodeType originNodeType, + ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) { + + StorageOperationStatus status; + + if(MapUtils.isNotEmpty(originNodeType.getProperties())){ + MapPropertiesDataDefinition instProperties = + new MapPropertiesDataDefinition(originNodeType.getProperties()); + status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_PROPERTIES, + VertexTypeEnum.INST_PROPERTIES, instProperties, componentInstance.getUniqueId()); + if (status != StorageOperationStatus.OK) { + return status; + } + } + + if(MapUtils.isNotEmpty(originNodeType.getAttributes())){ + MapPropertiesDataDefinition instAttributes = + new MapPropertiesDataDefinition(originNodeType.getAttributes()); + status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_ATTRIBUTES, + VertexTypeEnum.INST_ATTRIBUTES, instAttributes, componentInstance.getUniqueId()); + if (status != StorageOperationStatus.OK) { + return status; + } + } + + return addCalculatedCapReqFromNodeType(originNodeType, componentInstance, updatedContainerVertex); + } + + public MapArtifactDataDefinition prepareInstDeploymentArtifactPerInstance(Map deploymentArtifacts, String componentInstanceId, User user, String envType) { + if (deploymentArtifacts != null && envType.equals(HEAT_VF_ENV_NAME)) { + Map instDeploymentArtifacts = new HashMap<>(); + + deploymentArtifacts.entrySet().forEach(e -> { + ArtifactDataDefinition artifact = e.getValue(); + String type = artifact.getArtifactType(); + if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { + ArtifactDataDefinition artifactEnv = createArtifactPlaceHolderInfo(artifact, componentInstanceId, user, envType); + instDeploymentArtifacts.put(artifactEnv.getArtifactLabel(), artifactEnv); + } + }); + + deploymentArtifacts.putAll(instDeploymentArtifacts); + + return new MapArtifactDataDefinition(deploymentArtifacts); + + } + return null; + } + + @SuppressWarnings({ "unchecked" }) + private ArtifactDataDefinition createArtifactPlaceHolderInfo(ArtifactDataDefinition artifactHeat, String componentId, User user, String heatEnvType) { + Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); + if (deploymentResourceArtifacts == null) { + log.debug("no deployment artifacts are configured for generated artifacts"); + return null; + } + Map placeHolderData = (Map) deploymentResourceArtifacts.get(heatEnvType); + if (placeHolderData == null) { + log.debug("no env type {} are configured for generated artifacts", heatEnvType); + return null; + } + + String envLabel = (artifactHeat.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase(); + + ArtifactDataDefinition artifactInfo = new ArtifactDataDefinition(); + + String artifactName = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME); + String artifactType = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_TYPE); + String artifactDescription = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_DESCRIPTION); + + artifactInfo.setArtifactDisplayName(artifactName); + artifactInfo.setArtifactLabel(envLabel); + artifactInfo.setArtifactType(artifactType); + artifactInfo.setDescription(artifactDescription); + artifactInfo.setArtifactGroupType(artifactHeat.getArtifactGroupType()); + setDefaultArtifactTimeout(artifactHeat.getArtifactGroupType(), artifactInfo); + artifactInfo.setGeneratedFromId(artifactHeat.getUniqueId()); + // clone heat parameters in case of heat env only not VF heat env + if (heatEnvType.equals(HEAT_ENV_NAME)) { + artifactInfo.setHeatParameters(artifactHeat.getHeatParameters()); + } + setArtifactPlaceholderCommonFields(componentId, user, artifactInfo); + + return artifactInfo; + } + + public void setDefaultArtifactTimeout(ArtifactGroupTypeEnum groupType, ArtifactDataDefinition artifactInfo) { + if (groupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) { + artifactInfo.setTimeout(defaultHeatTimeout); + } else { + artifactInfo.setTimeout(NON_HEAT_TIMEOUT); + } + } + + private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDataDefinition artifactInfo) { + String uniqueId = null; + + if (resourceId != null) { + uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase()); + artifactInfo.setUniqueId(uniqueId); + } + artifactInfo.setUserIdCreator(user.getUserId()); + String fullName = user.getFullName(); + artifactInfo.setUpdaterFullName(fullName); + + long time = System.currentTimeMillis(); + + artifactInfo.setCreatorFullName(fullName); + artifactInfo.setCreationDate(time); + + artifactInfo.setLastUpdateDate(time); + artifactInfo.setUserIdLastUpdater(user.getUserId()); + + artifactInfo.setMandatory(true); + } + + /** + * + * @param originNodeType + * @param componentInstance + * @param updatedContainerVertex + * @return + */ + private StorageOperationStatus addCalculatedCapReqFromNodeType(NodeType originNodeType, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) { + + Map capabilities = originNodeType.getCapabilities(); + MapListCapabilityDataDefinition allCalculatedCap = prepareCalculatedCapabiltyForNodeType(capabilities, componentInstance); + StorageOperationStatus calculatedResult; + if (allCalculatedCap != null) { + calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, componentInstance.getUniqueId()); + + if (calculatedResult != StorageOperationStatus.OK) { + return calculatedResult; + } + } + Map capabiltiesProperties = originNodeType.getCapabilitiesProperties(); + if (capabiltiesProperties != null) { + Map updateKeyMap = capabiltiesProperties.entrySet().stream().collect(Collectors.toMap(e -> createCapPropertyKey(e.getKey(), componentInstance.getUniqueId()), Entry::getValue)); + MapCapabilityProperty mapCapabilityProperty = new MapCapabilityProperty(updateKeyMap); + calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabilityProperty, componentInstance.getUniqueId()); + if (calculatedResult != StorageOperationStatus.OK) { + return calculatedResult; + } + } + + MapListCapabilityDataDefinition fullCalculatedCap = new MapListCapabilityDataDefinition(); + calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, fullCalculatedCap, componentInstance.getUniqueId()); + + if (calculatedResult != StorageOperationStatus.OK) { + return calculatedResult; + } + + Map requirements = originNodeType.getRequirements(); + + MapListRequirementDataDefinition allCalculatedReq = prepareCalculatedRequirementForNodeType(requirements, componentInstance); + + StorageOperationStatus status; + if (allCalculatedReq != null) { + status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, componentInstance.getUniqueId()); + if (status != StorageOperationStatus.OK) { + return status; + } + } + MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition(); + addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, fullCalculatedReq, componentInstance.getUniqueId()); + return StorageOperationStatus.OK; + + } + + public static String createCapPropertyKey(String key, String instanceId) { + StringBuilder sb = new StringBuilder(instanceId); + sb.append(ModelConverter.CAP_PROP_DELIM).append(instanceId).append(ModelConverter.CAP_PROP_DELIM).append(key); + return sb.toString(); + } + + /** + * Prepares a map of capabilities lists Produces a deep copy of the received map of capabilities Sets values to the specific fields according to received component instance + * + * @param capabilities + * @param componentInstance + * @return + */ + public MapListCapabilityDataDefinition prepareCalculatedCapabiltyForNodeType(Map capabilities, ComponentInstanceDataDefinition componentInstance) { + if (capabilities != null) { + MapListCapabilityDataDefinition allCalculatedCap = new MapListCapabilityDataDefinition(); + + populateCapability(capabilities, componentInstance, allCalculatedCap); + return allCalculatedCap; + } + return null; + } + + /** + * Prepares a map of requirements lists Produces a deep copy of the received map of requirements Sets values to the specific fields according to received component instance + * + * @param requirements + * @param componentInstance + * @return + */ + public MapListRequirementDataDefinition prepareCalculatedRequirementForNodeType(Map requirements, ComponentInstanceDataDefinition componentInstance) { + if (requirements != null) { + MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition(); + + populateRequirement(requirements, componentInstance, allCalculatedReq); + return allCalculatedReq; + } + return null; + } + + public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstanceDataDefinition componentInstance, List groups, Map> groupInstancesArtifacts) { + + StorageOperationStatus result = null; + Map groupInstanceToCreate = new HashMap<>(); + if (groupInstancesArtifacts != null && CollectionUtils.isNotEmpty(groups)) { + for (Map.Entry> groupArtifacts : groupInstancesArtifacts.entrySet()) { + Optional groupOptional = groups.stream().filter(g -> g.getUniqueId().equals(groupArtifacts.getKey())).findFirst(); + if (groupOptional.isPresent()) { + GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition((GroupDataDefinition) groupOptional.get(), (ComponentInstanceDataDefinition) componentInstance, null); + groupInstance.setGroupInstanceArtifacts(groupArtifacts.getValue().stream().map(ArtifactDataDefinition::getUniqueId).collect(Collectors.toList())); + groupInstance.setGroupInstanceArtifactsUuid(groupArtifacts.getValue().stream().map(ArtifactDataDefinition::getArtifactUUID).collect(Collectors.toList())); + groupInstanceToCreate.put(groupInstance.getName(), groupInstance); + } + } + } + if (MapUtils.isNotEmpty(groupInstanceToCreate)) { + result = addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, new MapDataDefinition<>(groupInstanceToCreate), componentInstance.getUniqueId()); + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private ComponentInstanceDataDefinition buildComponentInstanceDataDefinition(ComponentInstance resourceInstance, String containerComponentId, String instanceNewName, boolean generateUid, ToscaElement originToscaElement) { + String ciOriginComponentUid = resourceInstance.getComponentUid(); + + if (!ValidationUtils.validateStringNotEmpty(resourceInstance.getCustomizationUUID())) { + resourceInstance.setCustomizationUUID(generateCustomizationUUID()); + } + ComponentInstanceDataDefinition dataDefinition = new ComponentInstanceDataDefinition(resourceInstance); + + Long creationDate = resourceInstance.getCreationTime(); + Long modificationTime; + if (creationDate == null) { + creationDate = System.currentTimeMillis(); + modificationTime = creationDate; + } else { + modificationTime = System.currentTimeMillis(); + } + dataDefinition.setComponentUid(ciOriginComponentUid); + dataDefinition.setCreationTime(creationDate); + dataDefinition.setModificationTime(modificationTime); + if (StringUtils.isNotEmpty(instanceNewName)) { + dataDefinition.setName(instanceNewName); + resourceInstance.setName(instanceNewName); + } + if (StringUtils.isNotEmpty(dataDefinition.getName())) + dataDefinition.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(dataDefinition.getName())); + dataDefinition.setIcon(resourceInstance.getIcon()); + if (generateUid) { + dataDefinition.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(containerComponentId, ciOriginComponentUid, dataDefinition.getNormalizedName())); + resourceInstance.setUniqueId(dataDefinition.getUniqueId()); + } + if (StringUtils.isEmpty(dataDefinition.getComponentVersion()) && originToscaElement != null) + dataDefinition.setComponentVersion((String) originToscaElement.getMetadataValue(JsonPresentationFields.VERSION)); + if (StringUtils.isEmpty(dataDefinition.getComponentName()) && originToscaElement != null) + dataDefinition.setComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.NAME)); + if (originToscaElement != null && dataDefinition.getToscaComponentName() == null) + dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); + if (dataDefinition.getOriginType() == null && originToscaElement != null) { + ResourceTypeEnum resourceType = originToscaElement.getResourceType(); + OriginTypeEnum originType = OriginTypeEnum.findByValue(resourceType.name()); + dataDefinition.setOriginType(originType); + } + if (dataDefinition.getOriginType() == OriginTypeEnum.ServiceProxy) + dataDefinition.setIsProxy(true); + + return dataDefinition; + } + + private Boolean isUniqueInstanceName(TopologyTemplate container, String instanceName) { + Boolean isUniqueName = true; + try { + isUniqueName = !container.getComponentInstances().values().stream().filter(ci -> ci.getName() != null && ci.getName().equals(instanceName)).findAny().isPresent(); + + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during fetching component instance with name {} from component container {}. {} ", instanceName, container.getName(), e.getMessage()); + } + return isUniqueName; + } + + private String buildComponentInstanceName(String instanceSuffixNumber, String instanceName) { + return instanceName + " " + (instanceSuffixNumber == null ? 0 : instanceSuffixNumber); + } + + public Either associateResourceInstances(String componentId, RequirementCapabilityRelDef relation) { + List relations = new ArrayList<>(); + relations.add(relation); + Either, StorageOperationStatus> associateResourceInstances = associateResourceInstances(componentId, relations); + if (associateResourceInstances.isRight()) { + return Either.right(associateResourceInstances.right().value()); + } + return Either.left(associateResourceInstances.left().value().get(0)); + } + + @SuppressWarnings({ "unchecked" }) + public Either, StorageOperationStatus> associateResourceInstances(String componentId, List relations) { + + Either containerVEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (containerVEither.isRight()) { + JanusGraphOperationStatus error = containerVEither.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error)); + } + GraphVertex containerV = containerVEither.left().value(); + Either>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); + if (capResult.isRight()) { + return Either.right(capResult.right().value()); + + } + Map calculatedCapabilty = capResult.left().value().getRight(); + + Either>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); + if (capResult.isRight()) { + return Either.right(capResult.right().value()); + + } + Map fullFilledCapabilty = capFullResult.left().value().getRight(); + + Either>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); + if (reqResult.isRight()) { + return Either.right(reqResult.right().value()); + } + Map calculatedRequirement = reqResult.left().value().getRight(); + + Either>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); + if (reqResult.isRight()) { + return Either.right(reqResult.right().value()); + } + Map fullfilledRequirement = reqFullResult.left().value().getRight(); + + Map jsonComposition = (Map) containerV.getJson(); + CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + + StorageOperationStatus status; + List relationsList = new ArrayList<>(); + for (RequirementCapabilityRelDef relation : relations) { + List relationshipsResult = new ArrayList<>(); + String fromNode = relation.getFromNode(); + String toNode = relation.getToNode(); + List relationships = relation.getRelationships(); + if (relationships == null || relationships.isEmpty()) { + BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement definition sent in order to set the relation between {} to {}", fromNode, toNode); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + JanusGraphOperationStatus.ILLEGAL_ARGUMENT)); + } + + for (CapabilityRequirementRelationship immutablePair : relationships) { + String requirement = immutablePair.getRelation().getRequirement(); + + Either, StorageOperationStatus> associateRes = connectInstancesInContainer(fromNode, toNode, immutablePair.getRelation(), relation.isOriginUI(), calculatedCapabilty, calculatedRequirement, + fullFilledCapabilty, fullfilledRequirement, compositionDataDefinition, containerV.getUniqueId()); + + if (associateRes.isRight()) { + status = associateRes.right().value(); + BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to associate resource instance {} to resource instance {}. status is {}", fromNode, toNode, status); + return Either.right(status); + } + + RelationshipInstDataDefinition relationshipInstData = (RelationshipInstDataDefinition) associateRes.left().value().get(JsonPresentationFields.RELATIONSHIP); + RelationshipImpl relationshipImplResult = new RelationshipImpl(); + relationshipImplResult.setType(relationshipInstData.getType()); + RelationshipInfo requirementAndRelationshipPair = new RelationshipInfo(requirement, relationshipImplResult); + requirementAndRelationshipPair.setCapability(immutablePair.getRelation().getCapability()); + requirementAndRelationshipPair.setRequirement(immutablePair.getRelation().getRequirement()); + requirementAndRelationshipPair.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId()); + requirementAndRelationshipPair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId()); + requirementAndRelationshipPair.setCapabilityUid(immutablePair.getRelation().getCapabilityUid()); + requirementAndRelationshipPair.setRequirementUid(immutablePair.getRelation().getRequirementUid()); + requirementAndRelationshipPair.setId(relationshipInstData.getUniqueId()); + CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); + capReqRel.setRelation(requirementAndRelationshipPair); + capReqRel.setCapability((CapabilityDataDefinition) associateRes.left().value().get(JsonPresentationFields.CAPABILITY)); + capReqRel.setRequirement((RequirementDataDefinition) associateRes.left().value().get(JsonPresentationFields.REQUIREMENT)); + relationshipsResult.add(capReqRel); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "update customization UUID for from CI {} and to CI {}", relation.getFromNode(), relation.getToNode()); + status = updateCustomizationUUID(relation.getFromNode(), compositionDataDefinition); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + status = updateCustomizationUUID(relation.getToNode(), compositionDataDefinition); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + } + RequirementCapabilityRelDef reqCapRelDef = new RequirementCapabilityRelDef(relation); + reqCapRelDef.setRelationships(relationshipsResult); + relationsList.add(reqCapRelDef); + } + // update metadata of container and composition json + status = updateAllAndCalculatedCapReqOnGraph(componentId, containerV, capResult, capFullResult, reqResult, reqFullResult); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + + return Either.left(relationsList); + } + + private StorageOperationStatus updateAllAndCalculatedCapReqOnGraph(String componentId, GraphVertex containerV, Either>, StorageOperationStatus> capResult, + Either>, StorageOperationStatus> capFullResult, Either>, StorageOperationStatus> reqResult, + Either>, StorageOperationStatus> reqFullResult) { + containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + Either updateElement = janusGraphDao.updateVertex(containerV); + if (updateElement.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new relations error {}. ", componentId, updateElement.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()); + } + // update cap/req jsons, fulfilled cap/req jsons!!!!! + Either status; + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update calculated capabilty for container {}", containerV.getUniqueId()); + status = updateOrCopyOnUpdate(capResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); + if (status.isRight()) { + JanusGraphOperationStatus error = status.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update calculated capabilty for container {} error {}", containerV.getUniqueId(), error); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error); + } + + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update calculated requirement for container {}", containerV.getUniqueId()); + status = updateOrCopyOnUpdate(reqResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); + if (status.isRight()) { + JanusGraphOperationStatus error = status.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update calculated requiremnt for container {} error {}", containerV.getUniqueId(), error); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error); + } + + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update fullfilled capabilty for container {}", containerV.getUniqueId()); + status = updateOrCopyOnUpdate(capFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); + if (status.isRight()) { + JanusGraphOperationStatus error = status.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update fullfilled capabilty for container {} error {}", containerV.getUniqueId(), error); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error); + } + + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update fullfilled requirement for container {}", containerV.getUniqueId()); + status = updateOrCopyOnUpdate(reqFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); + if (status.isRight()) { + JanusGraphOperationStatus error = status.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update fullfilled requirement for container {} error {}", containerV.getUniqueId(), error); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error); + } + return StorageOperationStatus.OK; + } + + @SuppressWarnings({ "unchecked" }) + public Either dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { + if (requirementDef.getRelationships() == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No relation pair in request [ {} ]", requirementDef); + return Either.right(StorageOperationStatus.BAD_REQUEST); + } + + String fromResInstanceUid = requirementDef.getFromNode(); + String toResInstanceUid = requirementDef.getToNode(); + + Either containerVEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (containerVEither.isRight()) { + JanusGraphOperationStatus error = containerVEither.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error)); + } + GraphVertex containerV = containerVEither.left().value(); + + // DE191707 - validations + Map jsonComposition = (Map) containerV.getJson(); + CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + Map componentInstances = compositionDataDefinition.getComponentInstances(); + ComponentInstanceDataDefinition ciFrom = componentInstances.get(fromResInstanceUid); + if (ciFrom == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "FROM instance {} isn't under container {}", fromResInstanceUid, componentId); + return Either.right(StorageOperationStatus.NOT_FOUND); + + } + ComponentInstanceDataDefinition ciTo = componentInstances.get(toResInstanceUid); + if (ciFrom == ciTo) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "TO instance {} isn't under container {}", toResInstanceUid, componentId); + return Either.right(StorageOperationStatus.NOT_FOUND); + + } + Map relations = compositionDataDefinition.getRelations(); + + List relationPairList = requirementDef.getRelationships(); + Either>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); + if (capResult.isRight()) { + return Either.right(capResult.right().value()); + } + Map calculatedCapability = capResult.left().value().getRight(); + + Either>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); + if (capResult.isRight()) { + return Either.right(capResult.right().value()); + + } + Map fulfilledCapability = capFullResult.left().value().getRight(); + + Either>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); + if (reqResult.isRight()) { + return Either.right(reqResult.right().value()); + } + Map calculatedRequirement = reqResult.left().value().getRight(); + + Either>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); + if (reqResult.isRight()) { + return Either.right(reqResult.right().value()); + } + Map fulfilledRequirement = reqFullResult.left().value().getRight(); + + for (CapabilityRequirementRelationship relationPair : relationPairList) { + Iterator> iterator = relations.entrySet().iterator(); + boolean isDeleted = false; + while (iterator.hasNext()) { + Entry entryInJson = iterator.next(); + RelationshipInstDataDefinition relationInJson = entryInJson.getValue(); + if (relationInJson.getFromId().equals(fromResInstanceUid) && relationInJson.getToId().equals(toResInstanceUid) && relationInJson.getUniqueId().equals(relationPair.getRelation().getId())) { + if (relationPair.getRelation().equalsTo(relationInJson)) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Remove relation from {} to {} capability {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationInJson.getType(), relationInJson.getCapabilityOwnerId(), + relationInJson.getRequirementOwnerId()); + iterator.remove(); + + // update calculated cap/req + StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapability, fulfilledCapability, toResInstanceUid, relationInJson, relationPair); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fulfilledRequirement, fromResInstanceUid, relationInJson, relationPair); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + isDeleted = true; + } + } + } + if (!isDeleted) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No relation to delete from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationPair.getCapability(), + relationPair.getRelation().getCapabilityOwnerId(), relationPair.getRelation().getRequirementOwnerId()); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + } + StorageOperationStatus status = updateCustomizationUUID(fromResInstanceUid, compositionDataDefinition); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + status = updateCustomizationUUID(toResInstanceUid, compositionDataDefinition); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + + // update jsons + // update metadata of container and composition json + status = updateAllAndCalculatedCapReqOnGraph(componentId, containerV, capResult, capFullResult, reqResult, reqFullResult); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + + return Either.left(requirementDef); + } + + /** + * Retrieves fulfilled requirement according to relation and received predicate + * + * @param componentId + * @param instanceId + * @param foundRelation + * @param predicate + * @return + */ + public Either getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef foundRelation, + BiPredicate predicate) { + + Either result = null; + Either>, StorageOperationStatus> reqFullResult = null; + MapListRequirementDataDefinition reqMapOfLists = null; + Optional foundRequirement; + RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation(); + Either containerVEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (containerVEither.isRight()) { + JanusGraphOperationStatus error = containerVEither.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error)); + } + if (result == null) { + GraphVertex containerV = containerVEither.left().value(); + reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); + if (reqFullResult.isRight()) { + result = Either.right(reqFullResult.right().value()); + } + } + if (result == null) { + Map fulfilledRequirement = reqFullResult.left().value().getRight(); + reqMapOfLists = fulfilledRequirement.get(instanceId); + if (reqMapOfLists == null) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + if (result == null && reqMapOfLists != null) { + for (ListRequirementDataDefinition requirements : reqMapOfLists.getMapToscaDataDefinition().values()) { + foundRequirement = requirements.getListToscaDataDefinition().stream().filter(req -> predicate.test(relationshipInfo, req)).findFirst(); + if (foundRequirement.isPresent()) { + result = Either.left(foundRequirement.get()); + } + } + } + return result; + } + + /** + * Retrieves fulfilled capability according to relation and received predicate + * + * @param componentId + * @param instanceId + * @param foundRelation + * @param predicate + * @return + */ + public Either getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef foundRelation, + BiPredicate predicate) { + + Either result = null; + Either>, StorageOperationStatus> capFullResult = null; + MapListCapabilityDataDefinition capMapOfLists = null; + Optional foundRequirement; + + RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation(); + Either containerVEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (containerVEither.isRight()) { + JanusGraphOperationStatus error = containerVEither.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error)); + } + if (result == null) { + GraphVertex containerV = containerVEither.left().value(); + capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); + if (capFullResult.isRight()) { + result = Either.right(capFullResult.right().value()); + } + } + if (result == null) { + Map fulfilledCapability = capFullResult.left().value().getRight(); + capMapOfLists = fulfilledCapability.get(instanceId); + if (capMapOfLists == null) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + if (result == null && capMapOfLists != null) { + for (ListCapabilityDataDefinition capabilities : capMapOfLists.getMapToscaDataDefinition().values()) { + foundRequirement = capabilities.getListToscaDataDefinition().stream().filter(cap -> predicate.test(relationshipInfo, cap)).findFirst(); + if (foundRequirement.isPresent()) { + result = Either.left(foundRequirement.get()); + } + } + } + return result; + } + + private StorageOperationStatus updateCalculatedRequirementsAfterDeleteRelation(Map calculatedRequirement, Map fullFilledRequirement, String fromResInstanceUid, + RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) { + StorageOperationStatus status; + String hereIsTheKey = null; + MapListRequirementDataDefinition reqByInstance = calculatedRequirement.get(fromResInstanceUid); + if (reqByInstance == null || reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()) == null) { + // move from fulfilled + status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey, relationship); + } else { + hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()); + ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey); + Optional requirementOptional = reqByType.getListToscaDataDefinition().stream() + .filter(req -> req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId().equals(relation.getRequirementId())).findFirst(); + + if (requirementOptional.isPresent()) { + + RequirementDataDefinition requirement = requirementOptional.get(); + String leftOccurrences = requirement.getLeftOccurrences(); + if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + Integer leftIntValue = Integer.parseInt(leftOccurrences); + ++leftIntValue; + requirement.setLeftOccurrences(String.valueOf(leftIntValue)); + } + if (relationship != null) { + relationship.setRequirement(requirement); + } + status = StorageOperationStatus.OK; + } else { + // move from fulfilled + status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey, relationship); + } + } + return status; + } + + private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map calculatedCapability, Map fullFilledCapability, String toResInstanceUid, + RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) { + StorageOperationStatus status; + String hereIsTheKey = null; + MapListCapabilityDataDefinition capByInstance = calculatedCapability.get(toResInstanceUid); + if (capByInstance == null || capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()) == null) { + // move from fulfilled + status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey, relationship); + } else { + hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()); + ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey); + Optional capabilityOptional = capByType.getListToscaDataDefinition().stream().filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId())) + .findFirst(); + + if (capabilityOptional.isPresent()) { + + CapabilityDataDefinition capability = capabilityOptional.get(); + String leftOccurrences = capability.getLeftOccurrences(); + if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + Integer leftIntValue = Integer.parseInt(leftOccurrences); + ++leftIntValue; + capability.setLeftOccurrences(String.valueOf(leftIntValue)); + } + if (relationship != null) { + relationship.setCapability(capability); + } + status = StorageOperationStatus.OK; + } else { + // move from fulfilled + status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey, relationship); + } + } + return status; + } + + private StorageOperationStatus moveFromFullFilledCapabilty(Map calculatedCapability, Map fullFilledCapability, String toResInstanceUid, + RelationshipInstDataDefinition relation, String hereIsTheKey, CapabilityRequirementRelationship relationship) { + MapListCapabilityDataDefinition capByInstance = fullFilledCapability.get(toResInstanceUid); + if (capByInstance == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability in fulfilled list for instance {} ", toResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + if (null == hereIsTheKey) + hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()); + if (null == hereIsTheKey) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability with id {} in fulfilled list for instance {} ", relation.getCapabilityId(), toResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey); + Iterator iterator = capByType.getListToscaDataDefinition().iterator(); + boolean found = false; + while (iterator.hasNext()) { + CapabilityDataDefinition cap = iterator.next(); + if (cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId())) { + found = true; + iterator.remove(); + // return to calculated list + String leftOccurrences = cap.getLeftOccurrences(); + Integer leftIntValue = Integer.parseInt(leftOccurrences); + ++leftIntValue; + cap.setLeftOccurrences(String.valueOf(leftIntValue)); + + MapListCapabilityDataDefinition mapListCapaDataDef = calculatedCapability.get(toResInstanceUid); + if (mapListCapaDataDef == null) { + mapListCapaDataDef = new MapListCapabilityDataDefinition(); + } + ListCapabilityDataDefinition findByKey = mapListCapaDataDef.findByKey(hereIsTheKey); + if (findByKey == null) { + findByKey = new ListCapabilityDataDefinition(); + mapListCapaDataDef.put(hereIsTheKey, findByKey); + } + findByKey.add(cap); + if (relationship != null) + relationship.setCapability(cap); + break; + } + } + if (!found) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getCapabilityOwnerId(), toResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus moveFromFullFilledRequirement(Map calculatedRequirement, Map fullFilledRequirement, String fromResInstanceUid, + RelationshipInstDataDefinition relation, String hereIsTheKey, CapabilityRequirementRelationship relationship) { + MapListRequirementDataDefinition reqByInstance = fullFilledRequirement.get(fromResInstanceUid); + if (reqByInstance == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement in fullfilled list for instance {} ", fromResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + if (null == hereIsTheKey) + hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()); + if (null == hereIsTheKey) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement with id {} in fulfilled list for instance {} ", relation.getRequirementId(), fromResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey); + Iterator iterator = reqByType.getListToscaDataDefinition().iterator(); + boolean found = false; + while (iterator.hasNext()) { + RequirementDataDefinition req = iterator.next(); + if (req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId().equals(relation.getRequirementId())) { + found = true; + iterator.remove(); + // return to calculated list + String leftOccurrences = req.getLeftOccurrences(); + Integer leftIntValue = Integer.parseInt(leftOccurrences); + ++leftIntValue; + req.setLeftOccurrences(String.valueOf(leftIntValue)); + + MapListRequirementDataDefinition mapListReqDataDef = calculatedRequirement.get(fromResInstanceUid); + if (mapListReqDataDef == null) { + mapListReqDataDef = new MapListRequirementDataDefinition(); + } + ListRequirementDataDefinition findByKey = mapListReqDataDef.findByKey(hereIsTheKey); + if (findByKey == null) { + findByKey = new ListRequirementDataDefinition(); + mapListReqDataDef.put(hereIsTheKey, findByKey); + } + findByKey.add(req); + if (relationship != null) + relationship.setRequirement(req); + break; + } + } + if (!found) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getRequirementOwnerId(), fromResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + return StorageOperationStatus.OK; + + } + + public StorageOperationStatus updateCustomizationUUID(String componentInstanceId, CompositionDataDefinition compositionDataDefinition) { + ComponentInstanceDataDefinition componentInstance = compositionDataDefinition.getComponentInstances().get(componentInstanceId); + + if (componentInstance == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component instance by id {} from map of instances ", componentInstanceId); + return StorageOperationStatus.NOT_FOUND; + } + UUID uuid = UUID.randomUUID(); + componentInstance.setCustomizationUUID(uuid.toString()); + + return StorageOperationStatus.OK; + } + + public Either, StorageOperationStatus> connectInstancesInContainer(String fromResInstanceUid, String toResInstanceUid, RelationshipInfo relationPair, boolean originUI, + Map calculatedCapabilty, Map calculatedRequirement, Map fullfilledCapabilty, + Map fullfilledRequirement, CompositionDataDefinition compositionDataDefinition, String containerId) { + String requirement = relationPair.getRequirement(); + Map componentInstances = compositionDataDefinition.getComponentInstances(); + + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to associate resource instance {} to resource instance {} under component {}. Requirement is {}.", fromResInstanceUid, toResInstanceUid, containerId, requirement); + + ComponentInstanceDataDefinition fromResourceInstData = componentInstances.get(fromResInstanceUid); + if (fromResourceInstData == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find from resource instance {}.", fromResInstanceUid); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + ComponentInstanceDataDefinition toResourceInstData = componentInstances.get(toResInstanceUid); + if (toResourceInstData == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find to resource instance {}.", toResInstanceUid); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + + Either, StorageOperationStatus> reqVsCap = connectRequirementVsCapability(fromResourceInstData, toResourceInstData, relationPair, originUI, calculatedCapabilty, calculatedRequirement, fullfilledCapabilty, + fullfilledRequirement, containerId); + if (reqVsCap.isRight()) { + StorageOperationStatus status = reqVsCap.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to connect requirement {} between resource instance {} to resource instance {}. status is {}", requirement, fromResInstanceUid, toResInstanceUid, status); + return Either.right(status); + } + Map relationship = reqVsCap.left().value(); + + // add to json new relations + compositionDataDefinition.addRelation(((RelationshipInstDataDefinition) relationship.get(JsonPresentationFields.RELATIONSHIP)).getUniqueId(), (RelationshipInstDataDefinition) relationship.get(JsonPresentationFields.RELATIONSHIP)); + + return Either.left(relationship); + } + + private Either>, StorageOperationStatus> fetchContainerCalculatedCapability(GraphVertex containerV, EdgeLabelEnum capLabel) { + + Either>, JanusGraphOperationStatus> calculatedCapabiltyEither = getDataAndVertexFromGraph(containerV, capLabel); + if (calculatedCapabiltyEither.isRight()) { + JanusGraphOperationStatus error = calculatedCapabiltyEither.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilties for container {}.", containerV.getUniqueId(), error); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error)); + } + Pair> calculatedCapabilty = calculatedCapabiltyEither.left().value(); + return Either.left(calculatedCapabilty); + } + + private Either>, StorageOperationStatus> fetchContainerCalculatedRequirement(GraphVertex containerV, EdgeLabelEnum reqLabel) { + Either>, JanusGraphOperationStatus> calculatedRequirementEither = getDataAndVertexFromGraph(containerV, reqLabel); + if (calculatedRequirementEither.isRight()) { + JanusGraphOperationStatus error = calculatedRequirementEither.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for container {}.", containerV.getUniqueId(), error); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error)); + } + Pair> calculatedRequirement = calculatedRequirementEither.left().value(); + return Either.left(calculatedRequirement); + } + + @SuppressWarnings("unchecked") + private Either, StorageOperationStatus> connectRequirementVsCapability(ComponentInstanceDataDefinition fromResInstance, ComponentInstanceDataDefinition toResInstance, + RelationshipInfo relationPair, boolean originUI, Map calculatedCapabilty, Map calculatedRequirement, + Map fullfilledCapabilty, Map fullfilledRequirement, String containerId) { + String type = relationPair.getRelationship().getType(); + // capability + + String toInstId = toResInstance.getUniqueId(); + MapListCapabilityDataDefinition mapListCapabilityDataDefinition = calculatedCapabilty.get(toInstId); + Map capReqRelationship = new EnumMap<>(JsonPresentationFields.class); + + if (mapListCapabilityDataDefinition == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for instance {} in container {}.", toInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + ListCapabilityDataDefinition listCapabilityDataDefinition = mapListCapabilityDataDefinition.getMapToscaDataDefinition().get(type); + if (listCapabilityDataDefinition == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for type {} for instance {} in container {}.", type, toInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + CapabilityDataDefinition capabilityForRelation = null; + Iterator iteratorCap = listCapabilityDataDefinition.getListToscaDataDefinition().iterator(); + while (iteratorCap.hasNext()) { + CapabilityDataDefinition cap = iteratorCap.next(); + if (cap.getUniqueId().equals(relationPair.getCapabilityUid()) && cap.getOwnerId().equals(relationPair.getCapabilityOwnerId())) { + capabilityForRelation = cap; + capReqRelationship.put(JsonPresentationFields.CAPABILITY, (T) capabilityForRelation); + String leftOccurrences = cap.getLeftOccurrences(); + if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + Integer leftIntValue = Integer.parseInt(leftOccurrences); + if (leftIntValue > 0) { + --leftIntValue; + capabilityForRelation.setLeftOccurrences(String.valueOf(leftIntValue)); + if (leftIntValue == 0) { + // remove from calculated + iteratorCap.remove(); + // move to fulfilled + MapListCapabilityDataDefinition mapListCapabiltyFullFilledInst = fullfilledCapabilty.get(toInstId); + if (mapListCapabiltyFullFilledInst == null) { + mapListCapabiltyFullFilledInst = new MapListCapabilityDataDefinition(); + fullfilledCapabilty.put(toInstId, mapListCapabiltyFullFilledInst); + } + + ListCapabilityDataDefinition listCapabilityFull = mapListCapabiltyFullFilledInst.findByKey(type); + if (listCapabilityFull == null) { + listCapabilityFull = new ListCapabilityDataDefinition(); + mapListCapabiltyFullFilledInst.put(type, listCapabilityFull); + } + listCapabilityFull.add(capabilityForRelation); + } + break; + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.", capabilityForRelation.getType(), toInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + } + } + } + if (capabilityForRelation == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch capabilty for type {} for instance {} in container {}.", type, toInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + + // requirements + String fromInstId = fromResInstance.getUniqueId(); + MapListRequirementDataDefinition mapListRequirementDataDefinition = calculatedRequirement.get(fromInstId); + if (mapListRequirementDataDefinition == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for instance {} in container {}.", fromInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + ListRequirementDataDefinition listRequirementDataDefinition = mapListRequirementDataDefinition.getMapToscaDataDefinition().get(type); + if (listRequirementDataDefinition == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for type {} for instance {} in container {}.", type, fromInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + + RequirementDataDefinition requirementForRelation = null; + Iterator iteratorReq = listRequirementDataDefinition.getListToscaDataDefinition().iterator(); + while (iteratorReq.hasNext()) { + RequirementDataDefinition req = iteratorReq.next(); + if (req.getUniqueId().equals(relationPair.getRequirementUid()) && req.getOwnerId().equals(relationPair.getRequirementOwnerId())) { + requirementForRelation = req; + capReqRelationship.put(JsonPresentationFields.REQUIREMENT, (T) requirementForRelation); + String leftOccurrences = req.getLeftOccurrences(); + if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + Integer leftIntValue = Integer.parseInt(leftOccurrences); + if (leftIntValue > 0) { + --leftIntValue; + req.setLeftOccurrences(String.valueOf(leftIntValue)); + if (leftIntValue == 0) { + // remove from calculated + iteratorReq.remove(); + // move to fulfilled + MapListRequirementDataDefinition mapListRequirementFullFilledInst = fullfilledRequirement.get(fromInstId); + if (mapListRequirementFullFilledInst == null) { + mapListRequirementFullFilledInst = new MapListRequirementDataDefinition(); + fullfilledRequirement.put(fromInstId, mapListRequirementFullFilledInst); + } + + ListRequirementDataDefinition listRequirementFull = mapListRequirementFullFilledInst.findByKey(type); + if (listRequirementFull == null) { + listRequirementFull = new ListRequirementDataDefinition(); + mapListRequirementFullFilledInst.put(type, listRequirementFull); + } + listRequirementFull.add(requirementForRelation); + } + break; + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No left occurrences requirement {} from {} to {} in container {}.", requirementForRelation.getCapability(), fromInstId, toInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + } + } + } + if (requirementForRelation == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch requirement for type {} for instance {} in container {}.", type, toInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + if (!capabilityForRelation.getType().equals(requirementForRelation.getCapability())) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No macth for capability from type {} and requirement {} from {} to {} in container {}.", capabilityForRelation.getType(), requirementForRelation.getCapability(), fromInstId, toInstId, + containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + + RelationshipInstDataDefinition relationshipTypeData = buildRelationshipInstData(fromInstId, toInstId, relationPair, originUI); + if (requirementForRelation.getRelationship() != null) + relationshipTypeData.setType(requirementForRelation.getRelationship()); + capReqRelationship.put(JsonPresentationFields.RELATIONSHIP, (T) relationshipTypeData); + return Either.left(capReqRelationship); + } + + private RelationshipInstDataDefinition buildRelationshipInstData(String fromResInstanceUid, String toInstId, RelationshipInfo relationPair, boolean originUI) { + + RelationshipInstDataDefinition relationshipInstData = new RelationshipInstDataDefinition(); + relationshipInstData.setUniqueId(UniqueIdBuilder.buildRelationsipInstInstanceUid(fromResInstanceUid, toInstId)); + + relationshipInstData.setType(relationPair.getRelationship().getType()); + Long creationDate = System.currentTimeMillis(); + relationshipInstData.setCreationTime(creationDate); + relationshipInstData.setModificationTime(creationDate); + relationshipInstData.setCapabilityOwnerId(relationPair.getCapabilityOwnerId()); + relationshipInstData.setRequirementOwnerId(relationPair.getRequirementOwnerId()); + relationshipInstData.setCapabilityId(relationPair.getCapabilityUid()); + relationshipInstData.setRequirementId(relationPair.getRequirementUid()); + relationshipInstData.setFromId(fromResInstanceUid); + relationshipInstData.setToId(toInstId); + relationshipInstData.setRequirement(relationPair.getRequirement()); + relationshipInstData.setCapability(relationPair.getCapability()); + relationshipInstData.setOriginUI(originUI); + + return relationshipInstData; + } + + public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map componentInstanceTMap, GraphVertex containerVertex, boolean allowDeleted) { + + StorageOperationStatus result = null; + String containerId = containerComponent.getUniqueId(); + Map instancesJsonData = null; + Either updateElement = null; + if (!validateInstanceNames(componentInstanceTMap)) { + result = StorageOperationStatus.INCONSISTENCY; + } + if (result == null && !validateInstanceNames(componentInstanceTMap)) { + result = StorageOperationStatus.INCONSISTENCY; + } + if (result == null && !allowDeleted && !validateDeletedResources(componentInstanceTMap)) { + result = StorageOperationStatus.INCONSISTENCY; + } + if (result == null) { + instancesJsonData = convertToComponentInstanceDataDefinition(componentInstanceTMap, containerId); + } + if (result == null && MapUtils.isNotEmpty(instancesJsonData)) { + containerVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + Map compositions = new HashMap<>(); + CompositionDataDefinition composition = new CompositionDataDefinition(); + composition.setComponentInstances(instancesJsonData); + compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), composition); + containerVertex.setJson(compositions); + updateElement = janusGraphDao.updateVertex(containerVertex); + if (updateElement.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instances. ", containerComponent.getName()); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()); + } + } + if (result == null && updateElement != null) { + GraphVertex vertexC = updateElement.left().value(); + instancesJsonData.entrySet().forEach(i ->createInstanceEdge(vertexC, i.getValue())); + result = StorageOperationStatus.OK; + } + return result; + } + + private Map convertToComponentInstanceDataDefinition(Map componentInstanceTMap, String containerId) { + + Map instances = new HashMap<>(); + for (Entry entry : componentInstanceTMap.entrySet()) { + ComponentInstanceDataDefinition instance = buildComponentInstanceDataDefinition(entry.getKey(), containerId, null, true, ModelConverter.convertToToscaElement(entry.getValue())); + instances.put(instance.getUniqueId(), instance); + } + return instances; + } + + private boolean validateDeletedResources(Map resourcesInstancesMap) { + boolean result = true; + for (Component component : resourcesInstancesMap.values()) { + if (component.getIsDeleted() != null && component.getIsDeleted()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance. ", component.getName()); + result = false; + break; + } + } + return result; + } + + private boolean validateInstanceNames(Map resourcesInstancesMap) { + boolean result = true; + Set names = new HashSet<>(); + for (ComponentInstance instance : resourcesInstancesMap.keySet()) { + if (StringUtils.isEmpty(instance.getName())) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component instance {} name is empty. Cannot add component instance. ", instance.getUniqueId()); + result = false; + break; + } else if (names.contains(instance.getName())) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component instance with the name {} already exsists. Cannot add component instance. ", instance.getName()); + result = false; + break; + } else { + names.add(instance.getName()); + } + } + return result; + } + + public StorageOperationStatus addDeploymentArtifactsToInstance(String toscaElementId, String instanceId, Map instDeplArtifacts) { + return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS); + } + + public StorageOperationStatus addInformationalArtifactsToInstance(String toscaElementId, String instanceId, Map instDeplArtifacts) { + return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INSTANCE_ARTIFACTS, VertexTypeEnum.INSTANCE_ARTIFACTS); + } + + public StorageOperationStatus addArtifactsToInstance(String toscaElementId, String instanceId, Map instDeplArtifacts, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexType) { + Either metadataVertex = janusGraphDao + .getVertexById(toscaElementId, JsonParseFlagEnum.NoParse); + if (metadataVertex.isRight()) { + JanusGraphOperationStatus status = metadataVertex.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; + } + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + MapArtifactDataDefinition instArtifacts = new MapArtifactDataDefinition(instDeplArtifacts); + return addToscaDataDeepElementsBlockToToscaElement(metadataVertex.left().value(), edgeLabel, vertexType, instArtifacts, instanceId); + + } + + @SuppressWarnings({ "unchecked" }) + public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) { + Either metadataVertex = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (metadataVertex.isRight()) { + JanusGraphOperationStatus status = metadataVertex.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; + } + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + GraphVertex metaVertex = metadataVertex.left().value(); + Map json = (Map) metaVertex.getJson(); + CompositionDataDefinition compositionDataDefinition = json.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + StorageOperationStatus status = updateCustomizationUUID(instanceId, compositionDataDefinition); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to update customization UUID for instance {} in component {} error {}", instanceId, componentId, status); + return status; + } + Either updateVertex = janusGraphDao.updateVertex(metaVertex); + if (updateVertex.isRight()) { + log.debug("Failed to update vertex of component {} error {}", componentId, updateVertex.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateVertex.right().value()); + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List groupInstances) { + if (groupInstances != null) { + Either, JanusGraphOperationStatus> dataFromGraph = getDataFromGraph(componentId, EdgeLabelEnum.INST_GROUPS); + if (dataFromGraph.isRight()) { + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(dataFromGraph.right().value()); + } + MapGroupsDataDefinition grInstPerInstance = dataFromGraph.left().value().get(instanceId); + if (grInstPerInstance == null) { + log.debug("No instance groups for instance {} in component {}", instanceId, componentId); + return StorageOperationStatus.NOT_FOUND; + } + for (String instGroupForUpdate : groupInstances) { + GroupInstanceDataDefinition groupInst = grInstPerInstance.findByKey(instGroupForUpdate); + if (groupInst == null) { + log.debug("No group instance {} in group list for instance {} in component {}", instGroupForUpdate, instanceId, componentId); + continue; + } + UUID uuid = UUID.randomUUID(); + groupInst.setCustomizationUUID(uuid.toString()); + } + + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List groupInstances) { + + return addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, + new MapDataDefinition<>(groupInstances.stream().collect(Collectors.toMap(GroupInstanceDataDefinition::getName, gi -> gi))), componentInstance.getUniqueId()); + } + + public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map deploymentArtifacts) { + + return addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, new MapDataDefinition<>(deploymentArtifacts), + componentInstance.getUniqueId()); + } + + public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { + + List pathKeys = new ArrayList<>(); + pathKeys.add(componentInstanceId); + return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus updateComponentInstanceCapabilityProperty(Component containerComponent, String componentInstanceId, String capabilityUniqueId, ComponentInstanceProperty property) { + List pathKeys = new ArrayList<>(); + pathKeys.add(componentInstanceId); + pathKeys.add(capabilityUniqueId); + return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus overrideComponentCapabilitiesProperties(Component containerComponent, Map capabilityPropertyMap) { + return overrideToscaDataOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilityPropertyMap); + } + + public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { + List pathKeys = new ArrayList<>(); + pathKeys.add(componentInstanceId); + return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List properties) { + List pathKeys = new ArrayList<>(); + pathKeys.add(componentInstanceId); + return updateToscaDataDeepElementsOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, properties, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus updateComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property){ + List pathKeys = new ArrayList<>(); + pathKeys.add(componentInstanceId); + return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, property, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus addComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property){ + List pathKeys = new ArrayList<>(); + pathKeys.add(componentInstanceId); + return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, property, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { + + List pathKeys = new ArrayList<>(); + pathKeys.add(componentInstanceId); + return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, property, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List properties) { + List pathKeys = new ArrayList<>(); + pathKeys.add(componentInstanceId); + return updateToscaDataDeepElementsOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, properties, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { + List pathKeys = new ArrayList<>(); + pathKeys.add(componentInstanceId); + return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, property, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus createInstanceEdge(GraphVertex metadataVertex, ComponentInstanceDataDefinition componentInstance) { + String instUniqueId = componentInstance.getUniqueId(); + + // create edge between container and origin ( in case of proxy this edge will be to ProxyService node type) + StorageOperationStatus result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.INSTANCE_OF, componentInstance.getComponentUid(), instUniqueId).either(v -> StorageOperationStatus.OK, + DaoStatusConverter::convertJanusGraphStatusToStorageStatus); + + if (result == StorageOperationStatus.OK && componentInstance.getIsProxy()) { + // create edge between container and service origin + result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.PROXY_OF, componentInstance.getSourceModelUid(), instUniqueId) + .either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertJanusGraphStatusToStorageStatus); + } + return result; + } + + public StorageOperationStatus createAllottedOfEdge(String componentId, String instanceId, String serviceUUID) { + Either vertexById = janusGraphDao.getVertexById(componentId); + if ( vertexById.isRight() ){ + log.debug("Failed to fetch component metadata vertex for id {} error {}", componentId, vertexById.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexById.right().value()); + } + GraphVertex metadataVertex = vertexById.left().value(); + + EnumMap props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.UUID, serviceUUID); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + EnumMap hasNot = new EnumMap<>(GraphPropertyEnum.class); + hasNot.put(GraphPropertyEnum.IS_DELETED, true); + + Either, JanusGraphOperationStatus> byCriteria = janusGraphDao + .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props,hasNot, JsonParseFlagEnum.ParseMetadata ); + if ( byCriteria.isRight() ){ + log.debug("Failed to fetch vertex by criteria {} error {}", props, byCriteria.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(byCriteria.right().value()); + } + List vertecies = byCriteria.left().value(); + StorageOperationStatus result = StorageOperationStatus.OK; + if ( vertecies != null ){ + GraphVertex serviceVertex = vertecies.get(0); + //remove previous edges + + log.debug("Try to create or update edge between resource {} and service {} ", metadataVertex, serviceVertex.getUniqueId()); + // create edge between container and service reference + result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.ALLOTTED_OF, serviceVertex.getUniqueId(), instanceId).either(v -> StorageOperationStatus.OK, + DaoStatusConverter::convertJanusGraphStatusToStorageStatus); + } + return result; + } + + + public StorageOperationStatus removeInstanceEdge(GraphVertex metadataVertex, ComponentInstanceDataDefinition componentInstance) { + String instUniqueId = componentInstance.getUniqueId(); + + // create edge between container and origin ( in case of proxy this edge will be to ProxyService node type) + StorageOperationStatus result = removeOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.INSTANCE_OF, componentInstance.getComponentUid(), instUniqueId) + .either(v -> StorageOperationStatus.OK, + DaoStatusConverter::convertJanusGraphStatusToStorageStatus); + + if (componentInstance.getIsProxy()) { + // create edge between container and service origin + result = removeOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.PROXY_OF, componentInstance.getSourceModelUid(), instUniqueId) + .either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertJanusGraphStatusToStorageStatus); + } + return result; + } + + private Either createOrUpdateInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, String instUniqueId) { + Map properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.UNIQUE_ID, componentUid); + + return janusGraphDao.getEdgeByChildrenVertexProperties(metadataVertex, edgeLabel, properties) + .left() + .bind(v -> addInstanceToPropertyOnEdge(instUniqueId, v, metadataVertex)) + .right() + .bind(s -> createInstanceEdge(metadataVertex, edgeLabel, componentUid, instUniqueId, s)); + } + + private Either removeOrUpdateInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, String instUniqueId) { + Map properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.UNIQUE_ID, componentUid); + + return janusGraphDao.getEdgeByChildrenVertexProperties(metadataVertex, edgeLabel, properties).left().bind(v -> removeInstanceFromPropertyOnEdge(instUniqueId, v, metadataVertex)).right() + .map(err -> removeInstanceEdgeLogError(metadataVertex, edgeLabel, componentUid, err)); + } + + private Either addInstanceToPropertyOnEdge(String instUniqueId, Edge edge, GraphVertex metadataVertex) { + // edge exist need to add instance id to list on edge's property + List property = (List) janusGraphDao.getProperty(edge, EdgePropertyEnum.INSTANCES); + if (property == null) { + property = new ArrayList<>(); + } + Optional findFirst = property.stream().filter(a -> a.equals(instUniqueId)).findFirst(); + if (!findFirst.isPresent()) { + property.add(instUniqueId); + } + try { + String jsonArr = JsonParserUtils.toJson(property); + log.debug("Update INSTANCES edge property with value {} ", jsonArr ); + + edge.property(EdgePropertyEnum.INSTANCES.getProperty(), jsonArr); + } catch (IOException e) { + log.debug("Failed to convert INSTANCES edge property to json for container {}", metadataVertex.getUniqueId(), e ); + return Either.right(JanusGraphOperationStatus.GENERAL_ERROR); + } + return Either.left(metadataVertex); + } + + private Either removeInstanceFromPropertyOnEdge(String instUniqueId, Edge edge, GraphVertex metadataVertex) { + // edge exist need to add instance id to list on edge's property + List property = (List) janusGraphDao.getProperty(edge, EdgePropertyEnum.INSTANCES); + if (property == null) { + property = new ArrayList<>(); + } + Optional findFirst = property.stream().filter(a -> a.equals(instUniqueId)).findFirst(); + if (findFirst.isPresent()) { + property.remove(instUniqueId); + } + if (property.isEmpty()) { + // For last instance need to remove edge + edge.remove(); + } else { + try { + String jsonArr = JsonParserUtils.toJson(property); + edge.property(EdgePropertyEnum.INSTANCES.getProperty(), jsonArr); + } catch (IOException e) { + log.debug("Failed to convert INSTANCES edge property to json for container {}", metadataVertex.getUniqueId(), e ); + return Either.right(JanusGraphOperationStatus.GENERAL_ERROR); + } + } + return Either.left(metadataVertex); + } + + private Either createInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, String instUniqueId, JanusGraphOperationStatus retrieveEdgeStatus) { + if (retrieveEdgeStatus == JanusGraphOperationStatus.NOT_FOUND) { + // create new edge + Either vertexById = janusGraphDao.getVertexById(componentUid); + if (vertexById.isRight()) { + return vertexById; + } + GraphVertex originVertex = vertexById.left().value(); + Map edgeProps = new EnumMap<>(EdgePropertyEnum.class); + List instList = new ArrayList<>(); + instList.add(instUniqueId); + edgeProps.put(EdgePropertyEnum.INSTANCES, instList); + + log.debug("Create new edge {} between {} and {} and properties {} ", edgeLabel, metadataVertex.getUniqueId(), originVertex.getUniqueId(), edgeProps); + JanusGraphOperationStatus + edgeResult = janusGraphDao + .createEdge(metadataVertex, originVertex, edgeLabel, edgeProps); + return edgeResult == JanusGraphOperationStatus.OK ? Either.left(metadataVertex) : Either.right(edgeResult); + } + // error + log.debug("Failed to fetch edge with label {} and to vertex with id {} error {} ", edgeLabel, componentUid, retrieveEdgeStatus); + return Either.right(retrieveEdgeStatus); + } + + private JanusGraphOperationStatus removeInstanceEdgeLogError(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, JanusGraphOperationStatus retrieveEdgeStatus) { + if (retrieveEdgeStatus == JanusGraphOperationStatus.NOT_FOUND) { + log.debug("No edge {} to remove between container {} and origin {}", edgeLabel, metadataVertex.getUniqueId(), componentUid); + } else { + // error + log.debug("Failed to fetch edge with label {} and to vertex with id {} error {} ", edgeLabel, componentUid, retrieveEdgeStatus); + } + return retrieveEdgeStatus; + } + + public void removeAllAllotedEdges(String uniqueId) { + Either vertexById = janusGraphDao.getVertexById(uniqueId); + if (vertexById.isLeft()) { + GraphVertex originVertex = vertexById.left().value(); + JanusGraphVertex vertex = originVertex.getVertex(); + Iterator edges = vertex.edges(Direction.OUT, EdgeLabelEnum.ALLOTTED_OF.name()); + while ( edges != null && edges.hasNext() ){ + Edge edge = edges.next(); + edge.remove(); + } + } + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java new file mode 100644 index 0000000000..eb8b90332c --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java @@ -0,0 +1,979 @@ +/*- + * ============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.jsonjanusgraph.operations; + +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.DerivedNodeTypeResolver; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.NodeType; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.beans.factory.annotation.Qualifier; + +import java.util.*; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +@org.springframework.stereotype.Component("node-type-operation") +public class NodeTypeOperation extends ToscaElementOperation { + public final static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1"); + public final static Pattern uuidNormativeNewVersion = Pattern.compile("^\\d{1,}.0"); + private static final Logger log = Logger.getLogger(NodeTypeOperation.class); + private DerivedNodeTypeResolver derivedResourceResolver; + + + public NodeTypeOperation(@Qualifier("derived-resource-resolver") DerivedNodeTypeResolver derivedNodeTypeResolver) { + this.derivedResourceResolver = derivedNodeTypeResolver; + } + + public Either createNodeType(NodeType nodeType) { + + Either result = null; + + nodeType.generateUUID(); + + //Set missing props such as names, default lifecycle state, dates etc... + nodeType = getResourceMetaDataFromResource(nodeType); + + //Set unique ID + String resourceUniqueId = nodeType.getUniqueId(); + if (resourceUniqueId == null) { + resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId(); + nodeType.setUniqueId(resourceUniqueId); + } + + // get derived from resources + List derivedResources = null; + Either, StorageOperationStatus> derivedResourcesResult = findDerivedResources(nodeType); + if (derivedResourcesResult.isRight()) { + result = Either.right(derivedResourcesResult.right().value()); + return result; + } else { + derivedResources = derivedResourcesResult.left().value(); + } + + //Create Vertext Object and fill according to given NodeType + GraphVertex nodeTypeVertex = new GraphVertex(VertexTypeEnum.NODE_TYPE); + fillToscaElementVertexData(nodeTypeVertex, nodeType, JsonParseFlagEnum.ParseAll); + + //Create Node Type in Graph + Either createdVertex = janusGraphDao.createVertex(nodeTypeVertex); + if (createdVertex.isRight()) { + JanusGraphOperationStatus status = createdVertex.right().value(); + log.error("Error returned after creating resource data node {}. status returned is ", nodeTypeVertex, status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + return result; + } + nodeTypeVertex = createdVertex.left().value(); + + StorageOperationStatus assosiateCommon = assosiateCommonForToscaElement(nodeTypeVertex, nodeType, derivedResources); + if (assosiateCommon != StorageOperationStatus.OK) { + result = Either.right(assosiateCommon); + return result; + } + + StorageOperationStatus associateDerived = assosiateToDerived(nodeTypeVertex, derivedResources); + if (associateDerived != StorageOperationStatus.OK) { + result = Either.right(associateDerived); + return result; + } + StorageOperationStatus associateCategory = assosiateResourceMetadataToCategory(nodeTypeVertex, nodeType); + if (associateCategory != StorageOperationStatus.OK) { + result = Either.right(associateCategory); + return result; + } + + StorageOperationStatus associateAttributes = associateAttributesToResource(nodeTypeVertex, nodeType, derivedResources); + if (associateAttributes != StorageOperationStatus.OK) { + result = Either.right(associateAttributes); + return result; + } + + StorageOperationStatus associateRequirements = associateRequirementsToResource(nodeTypeVertex, nodeType, derivedResources); + if (associateRequirements != StorageOperationStatus.OK) { + result = Either.right(associateRequirements); + return result; + } + + StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(nodeTypeVertex, nodeType, derivedResources); + if (associateCapabilities != StorageOperationStatus.OK) { + result = Either.right(associateCapabilities); + return result; + } + StorageOperationStatus associateCapabilitiesProps = associateCapabilitiesPropertiesToResource(nodeTypeVertex, nodeType, derivedResources); + if (associateCapabilitiesProps != StorageOperationStatus.OK) { + result = Either.right(associateCapabilitiesProps); + return result; + } + + StorageOperationStatus associateInterfaces = associateInterfacesToResource(nodeTypeVertex, nodeType, derivedResources); + if (associateInterfaces != StorageOperationStatus.OK) { + result = Either.right(associateInterfaces); + return result; + } + + StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(nodeTypeVertex, nodeType, derivedResources); + if (addAdditionalInformation != StorageOperationStatus.OK) { + result = Either.right(addAdditionalInformation); + return result; + } + result = Either.left(nodeType); + return result; + + } + + private StorageOperationStatus associateInterfacesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { + // Note : currently only one derived supported!!!! + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.INTERFACE_ARTIFACTS); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map interfacArtsAll = dataFromDerived.left().value(); + + Map interfacArts = nodeType.getInterfaceArtifacts(); + if (interfacArts != null) { + interfacArtsAll.putAll(interfacArts); + } + if (!interfacArtsAll.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INTERFACE_ARTIFACTS, EdgeLabelEnum.INTERFACE_ARTIFACTS, interfacArtsAll); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + @Override + public Either getToscaElement(String uniqueId, ComponentParametersView componentParametersView) { + + Either componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata); + if (componentByLabelAndId.isRight()) { + return Either.right(componentByLabelAndId.right().value()); + } + GraphVertex componentV = componentByLabelAndId.left().value(); + + return getToscaElement(componentV, componentParametersView); + + } + + // ------------------------------------------------------------- + @Override + public Either getToscaElement(GraphVertex componentV, ComponentParametersView componentParametersView) { + NodeType toscaElement; + toscaElement = convertToComponent(componentV); + JanusGraphOperationStatus status = null; + if (!componentParametersView.isIgnoreUsers()) { + status = setCreatorFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + + status = setLastModifierFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + + if (!componentParametersView.isIgnoreProperties()) { + status = setResourcePropertiesFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK && status != JanusGraphOperationStatus.NOT_FOUND) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + + if (!componentParametersView.isIgnoreAttributesFrom()) { + status = setResourceAttributesFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + + if (!componentParametersView.isIgnoreDerivedFrom()) { + status = setResourceDerivedFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + + if (!componentParametersView.isIgnoreCategories()) { + status = setResourceCategoryFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreRequirements()) { + status = setResourceRequirementsFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + log.error("Failed to set requirement of resource {}. status is {}", componentV.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreCapabilities()) { + status = setResourceCapabilitiesFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + + if (!componentParametersView.isIgnoreArtifacts()) { + status = setArtifactsFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreAdditionalInformation()) { + status = setAdditionalInformationFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreInterfaces()) { + status = setInterfacesFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreAllVersions()) { + status = setAllVersions(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK && status != JanusGraphOperationStatus.NOT_FOUND) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + + if (!componentParametersView.isIgnoreCapabiltyProperties()) { + status = setComponentCapPropertiesFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + + } + } + return Either.left(toscaElement); + } + + private JanusGraphOperationStatus setComponentCapPropertiesFromGraph(GraphVertex componentV, NodeType toscaElement) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES_PROPERTIES); + if (result.isLeft()) { + toscaElement.setCapabilitiesProperties(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setInterfacesFromGraph(GraphVertex componentV, NodeType toscaElement) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INTERFACE_ARTIFACTS); + if (result.isLeft()) { + toscaElement.setInterfaceArtifacts(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + protected JanusGraphOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) { + return setResourceCapabilitiesFromGraph(componentV, (NodeType) toscaElement); + } + + private JanusGraphOperationStatus setResourceCapabilitiesFromGraph(GraphVertex componentV, NodeType toscaElement) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES); + if (result.isLeft()) { + toscaElement.setCapabilities(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setResourceDerivedFromGraph(GraphVertex componentV, NodeType toscaElement) { + List derivedFromList = new ArrayList<>(); + + JanusGraphOperationStatus + listFromGraphStatus = findResourcesPathRecursively(componentV, derivedFromList); + if (JanusGraphOperationStatus.OK != listFromGraphStatus) { + return listFromGraphStatus; + } + + if (!derivedFromList.isEmpty()) { + if (derivedFromList.size() > 1) { + List lastDerivedFrom = new ArrayList<>(); + lastDerivedFrom.add(derivedFromList.get(1)); + toscaElement.setDerivedFrom(lastDerivedFrom); + toscaElement.setDerivedList(derivedFromList); + } else { + toscaElement.setDerivedFrom(null); + toscaElement.setDerivedList(derivedFromList); + } + + } + return JanusGraphOperationStatus.OK; + } + + protected JanusGraphOperationStatus findResourcesPathRecursively(GraphVertex nodeTypeV, List resourcesPathList) { + Either parentResourceRes = janusGraphDao + .getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); + resourcesPathList.add((String) nodeTypeV.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME)); + while (parentResourceRes.isLeft()) { + + GraphVertex parent = parentResourceRes.left().value(); + resourcesPathList.add((String) parent.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME)); + parentResourceRes = janusGraphDao + .getChildVertex(parent, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); + } + JanusGraphOperationStatus operationStatus = parentResourceRes.right().value(); + + if (operationStatus != JanusGraphOperationStatus.NOT_FOUND) { + return operationStatus; + } else { + return JanusGraphOperationStatus.OK; + } + + } + + protected JanusGraphOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) { + return setResourceRequirementsFromGraph(componentV, (NodeType) toscaElement); + } + + private JanusGraphOperationStatus setResourceRequirementsFromGraph(GraphVertex componentV, NodeType toscaElement) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.REQUIREMENTS); + if (result.isLeft()) { + toscaElement.setRequirements(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setResourceAttributesFromGraph(GraphVertex componentV, NodeType toscaElement) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ATTRIBUTES); + if (result.isLeft()) { + toscaElement.setAttributes(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setResourcePropertiesFromGraph(GraphVertex componentV, NodeType toscaElement) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.PROPERTIES); + if (result.isLeft()) { + toscaElement.setProperties(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private StorageOperationStatus assosiateToDerived(GraphVertex nodeTypeVertex, List derivedResources) { + for (GraphVertex derivedV : derivedResources) { + JanusGraphOperationStatus + createEdge = janusGraphDao + .createEdge(nodeTypeVertex, derivedV, EdgeLabelEnum.DERIVED_FROM, null); + if (createEdge != JanusGraphOperationStatus.OK) { + log.trace("Failed to associate resource {} to derived with id {}", nodeTypeVertex.getUniqueId(), derivedV.getUniqueId()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { + // Note : currently only one derived supported!!!! + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.ADDITIONAL_INFORMATION); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map addInformationAll = dataFromDerived.left().value(); + + Map addInformation = nodeType.getAdditionalInformation(); + if (addInformation != null) { + ToscaDataDefinition.mergeDataMaps(addInformationAll, addInformation); + } + if (!addInformationAll.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformationAll); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { + // Note : currently only one derived supported!!!! + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.CAPABILITIES); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map capabiltiesAll = dataFromDerived.left().value(); + + Map capabilties = nodeType.getCapabilities(); + if (capabilties != null) { + if (capabiltiesAll == null) { + capabiltiesAll = new HashMap<>(); + } + capabilties.values().forEach(l -> { + l.getListToscaDataDefinition().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { + String uid = UniqueIdBuilder.buildCapabilityUid(nodeTypeVertex.getUniqueId(), p.getName()); + p.setUniqueId(uid); + }); + }); + + ToscaDataDefinition.mergeDataMaps(capabiltiesAll, capabilties); + capabiltiesAll.values().forEach(l -> { + l.getListToscaDataDefinition().forEach(c -> { + List capabilitySources = c.getCapabilitySources(); + if (capabilitySources == null) { + capabilitySources = new ArrayList<>(); + } + capabilitySources.add((String) nodeType.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); + c.setCapabilitySources(capabilitySources); + }); + }); + } + capabiltiesAll.values().forEach(l -> { + l.getListToscaDataDefinition().forEach(c -> { + List capabilitySources = c.getCapabilitySources(); + if (capabilitySources == null) { + capabilitySources = new ArrayList<>(); + } + capabilitySources.add((String) nodeType.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); + c.setCapabilitySources(capabilitySources); + }); + }); + if (!capabiltiesAll.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILITIES, EdgeLabelEnum.CAPABILITIES, capabiltiesAll); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { + // Note : currently only one derived supported!!!! + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.REQUIREMENTS); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map requirementsAll = dataFromDerived.left().value(); + + Map requirements = nodeType.getRequirements(); + if (requirements != null) { + if (requirementsAll == null) { + requirementsAll = new HashMap<>(); + } + requirements.values().forEach(l -> { + l.getListToscaDataDefinition().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { + String uid = UniqueIdBuilder.buildRequirementUid(nodeTypeVertex.getUniqueId(), p.getName()); + p.setUniqueId(uid); + }); + }); + + ToscaDataDefinition.mergeDataMaps(requirementsAll, requirements); + + } + if (!requirementsAll.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.REQUIREMENTS, EdgeLabelEnum.REQUIREMENTS, requirementsAll); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateAttributesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { + // Note : currently only one derived supported!!!! + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.ATTRIBUTES); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map attributesAll = dataFromDerived.left().value(); + + Map attributes = nodeType.getAttributes(); + if (attributes != null) { + attributes.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { + String uid = UniqueIdBuilder.buildAttributeUid(nodeTypeVertex.getUniqueId(), p.getName()); + p.setUniqueId(uid); + }); + ToscaDataDefinition.mergeDataMaps(attributesAll, attributes); + } + if (!attributesAll.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ATTRIBUTES, EdgeLabelEnum.ATTRIBUTES, attributesAll); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + // TODO get from derived + private StorageOperationStatus associateCapabilitiesPropertiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { + // // Note : currently only one derived supported!!!! + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.CAPABILITIES_PROPERTIES); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map propertiesAll = dataFromDerived.left().value(); + Map capabiltiesProps = nodeType.getCapabilitiesProperties(); + if (capabiltiesProps != null) { + capabiltiesProps.values().forEach(l -> { + if (l.getMapToscaDataDefinition() != null && l.getMapToscaDataDefinition().values() != null) { + Collection mapToscaDataDefinition = l.getMapToscaDataDefinition().values(); + mapToscaDataDefinition.stream().filter(p -> p != null && p.getUniqueId() == null).forEach(p -> { + String uid = UniqueIdBuilder.buildRequirementUid(nodeTypeVertex.getUniqueId(), p.getName()); + p.setUniqueId(uid); + }); + } + }); + ToscaDataDefinition.mergeDataMaps(propertiesAll, capabiltiesProps); + } + if (!propertiesAll.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, propertiesAll); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + public Either, StorageOperationStatus> findDerivedResources(NodeType nodeType) { + + List derivedResources = new ArrayList<>(); + List derivedFromResources = nodeType.getDerivedFrom(); + if (derivedFromResources != null && !derivedFromResources.isEmpty()) { + + for (String parentResource : derivedFromResources) { + Either, JanusGraphOperationStatus> getParentResources = derivedResourceResolver.findDerivedResources(parentResource); + List resources = null; + if (getParentResources.isRight()) { + log.error("Cannot find parent resource by tosca resource name {} in the graph.", parentResource); + return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND); + + } else { + resources = getParentResources.left().value(); + if (resources == null || resources.size() == 0) { + log.error("Cannot find parent resource by tosca name {} in the graph. resources size is empty", parentResource); + return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND); + } else { + if (resources.size() > 1) { + return handleMultipleParent(parentResource, derivedResources, resources); + } else { + GraphVertex parentResourceData = resources.get(0); + derivedResources.add(parentResourceData); + } + } + + } + + } + } + return Either.left(derivedResources); + } + + Either, StorageOperationStatus> handleMultipleParent(String parentResource, List derivedResource, List fetchedDerivedResources) { + + Either, StorageOperationStatus> result = Either.left(derivedResource); + try { + fetchedDerivedResources.sort((d1, d2) -> { + return new Double(Double.parseDouble((String) d1.getMetadataProperty(GraphPropertyEnum.VERSION))).compareTo(Double.parseDouble((String) d2.getMetadataProperty(GraphPropertyEnum.VERSION))); + }); + + int actualHighestIndex = fetchedDerivedResources.size() - 1; + derivedResource.add(fetchedDerivedResources.get(actualHighestIndex)); + fetchedDerivedResources.remove(actualHighestIndex); + + StorageOperationStatus status = fixMultipleParent(fetchedDerivedResources); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during handle multiple parent {}. Exception is {}", parentResource, e.getMessage()); + result = Either.right(StorageOperationStatus.GENERAL_ERROR); + } + return result; + } + + private StorageOperationStatus fixMultipleParent(List fetchedDerivedResources) { + StorageOperationStatus result = StorageOperationStatus.OK; + for (GraphVertex fetchedDerivedResource : fetchedDerivedResources) { + fetchedDerivedResource.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, false); + Either updateVertexRes = janusGraphDao.updateVertex(fetchedDerivedResource); + if (updateVertexRes.isRight()) { + JanusGraphOperationStatus titatStatus = updateVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set highest version of node type {} to false. Status is {}", fetchedDerivedResource.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME), titatStatus); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(titatStatus); + break; + } + } + return result; + } + + private GraphVertex fillMetadata(GraphVertex nodeTypeVertex, NodeType nodeType) { + nodeTypeVertex.setLabel(VertexTypeEnum.NODE_TYPE); + + fillCommonMetadata(nodeTypeVertex, nodeType); + + return nodeTypeVertex; + } + + @Override + public Either deleteToscaElement(GraphVertex toscaElementVertex) { + Either nodeType = getToscaElement(toscaElementVertex, new ComponentParametersView()); + if (nodeType.isRight()) { + log.debug("Failed to fetch tosca element {} error {}", toscaElementVertex.getUniqueId(), nodeType.right().value()); + return nodeType; + } + JanusGraphOperationStatus status = disassociateAndDeleteCommonElements(toscaElementVertex); + if (status != JanusGraphOperationStatus.OK) { + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao + .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate capabilties for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao + .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES_PROPERTIES); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate capabilties properties for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao + .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao + .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao + .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INTERFACE_ARTIFACTS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate interface artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + toscaElementVertex.getVertex().remove(); + log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId()); + + return nodeType; + } + + @SuppressWarnings("unchecked") + @Override + public Either createToscaElement(ToscaElement toscaElement) { + return createNodeType((NodeType) toscaElement); + } + + @Override + protected JanusGraphOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) { + return setResourceCategoryFromGraph(vertexComponent, toscaElement); + } + + @Override + protected StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) { + return validateResourceCategory(toscaElementToUpdate, elementV); + } + + @Override + protected StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex nodeTypeV) { + + NodeType nodeType = (NodeType) toscaElementToUpdate; + + List derivedFromResources = nodeType.getDerivedFrom(); + + // now supported only single derived from + if (derivedFromResources != null && !derivedFromResources.isEmpty() && derivedFromResources.get(0) != null) { + String firstDerived = derivedFromResources.get(0); + boolean derivedFromGenericType = null != nodeType.getDerivedFromGenericType(); + Either childVertex = janusGraphDao + .getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + JanusGraphOperationStatus getchieldError = childVertex.right().value(); + log.debug("Failed to fetch derived resource for element {} error {}", nodeTypeV.getUniqueId(), getchieldError); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getchieldError); + } + GraphVertex firstDerivedInChain = childVertex.left().value(); + + String firstCurrentDerived = (String) firstDerivedInChain.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME); + if (!firstDerived.equals(firstCurrentDerived) || derivedFromGenericType) { + + Map propertiesToMatch = new HashMap<>(); + propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + + propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, firstDerived); + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + Either, JanusGraphOperationStatus> getParentResources = janusGraphDao + .getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, JsonParseFlagEnum.NoParse); + + if (getParentResources.isRight()) { + JanusGraphOperationStatus error = getParentResources.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch derived by criteria {}. error {} ", propertiesToMatch, error); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error); + } + // must be only one + GraphVertex newDerivedV = getParentResources.left().value().get(0); + return updateDerived(toscaElementToUpdate, nodeTypeV, firstDerivedInChain, newDerivedV, false); + } + } + return StorageOperationStatus.OK; + } + + /** + * + * @param toscaElementToUpdate + * @param nodeTypeV + * @param preDerivedV + * @param newDerivedV + * @param mergeValues + * @return + */ + protected StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex nodeTypeV, GraphVertex preDerivedV, GraphVertex newDerivedV, boolean mergeValues) { + Set preDerivedChainIdList = new HashSet(); + preDerivedChainIdList.add(preDerivedV.getUniqueId()); + Either childVertex = janusGraphDao + .getChildVertex(preDerivedV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); + while (childVertex.isLeft()) { + GraphVertex currentChield = childVertex.left().value(); + preDerivedChainIdList.add(currentChield.getUniqueId()); + childVertex = janusGraphDao + .getChildVertex(currentChield, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); + } + + List derivedResources = new ArrayList<>(); + derivedResources.add(newDerivedV); + StorageOperationStatus updateStatus = updateDataFromNewDerived(derivedResources, nodeTypeV, (NodeType) toscaElementToUpdate, mergeValues, preDerivedChainIdList); + if (updateStatus != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update data for {} from new derived {} ", nodeTypeV.getUniqueId(), newDerivedV.getUniqueId(), updateStatus); + return updateStatus; + } + + Either deleteEdge = janusGraphDao + .deleteEdge(nodeTypeV, preDerivedV, EdgeLabelEnum.DERIVED_FROM); + if (deleteEdge.isRight()) { + JanusGraphOperationStatus deleteError = deleteEdge.right().value(); + log.debug("Failed to disassociate element {} from derived {} , error {}", nodeTypeV.getUniqueId(), preDerivedV.getUniqueId(), deleteError); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(deleteError); + } + + janusGraphDao.createEdge(nodeTypeV, newDerivedV, EdgeLabelEnum.DERIVED_FROM, new HashMap<>()); + + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateDerivedDataByType(EdgeLabelEnum edgeLabel, GraphVertex nodeTypeV, NodeType nodeToUpdate, List newDerived) { + + switch (edgeLabel) { + case CAPABILITIES: + return associateCapabilitiesToResource(nodeTypeV, nodeToUpdate, newDerived); + case REQUIREMENTS: + return associateRequirementsToResource(nodeTypeV, nodeToUpdate, newDerived); + case PROPERTIES: + return associatePropertiesToResource(nodeTypeV, nodeToUpdate, newDerived); + case ATTRIBUTES: + return associateAttributesToResource(nodeTypeV, nodeToUpdate, newDerived); + case ADDITIONAL_INFORMATION: + return addAdditionalInformationToResource(nodeTypeV, nodeToUpdate, newDerived); + case CAPABILITIES_PROPERTIES: + return associateCapabilitiesPropertiesToResource(nodeTypeV, nodeToUpdate, newDerived); + default: + return StorageOperationStatus.OK; + } + + } + + private StorageOperationStatus updateDataFromNewDerived(List newDerived, GraphVertex nodeTypeV, NodeType nodeToUpdate, boolean mergeValues, Set preDerivedChainIdList) { + EnumSet edgeLabels = EnumSet.of(EdgeLabelEnum.CAPABILITIES, EdgeLabelEnum.REQUIREMENTS, EdgeLabelEnum.PROPERTIES, EdgeLabelEnum.ATTRIBUTES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.ADDITIONAL_INFORMATION); + StorageOperationStatus status = null; + for (EdgeLabelEnum edge : edgeLabels) { + status = updateDataByType(newDerived, nodeTypeV, edge, nodeToUpdate, mergeValues, preDerivedChainIdList); + if (status != StorageOperationStatus.OK) { + break; + } + } + return status; + + } + + private StorageOperationStatus updateDataByType(List newDerivedList, GraphVertex nodeTypeV, EdgeLabelEnum label, NodeType nodeElement, boolean mergeValues, Set preDerivedChainIdList) { + log.debug("Update data from derived for element {} type {}", nodeTypeV.getUniqueId(), label); + Either dataFromGraph = getDataVertex(nodeTypeV, label); + if (dataFromGraph.isRight()) { + if (JanusGraphOperationStatus.NOT_FOUND == dataFromGraph.right().value()) + return associateDerivedDataByType(label, nodeTypeV, nodeElement, newDerivedList); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(dataFromGraph.right().value()); + } + GraphVertex dataV = dataFromGraph.left().value(); + + Map mapFromGraph = (Map) dataV.getJson(); + Map valuesFrmPrev = null; + if (isSimpleHierarchy(label)) { + if (mergeValues) { + valuesFrmPrev = mapFromGraph.entrySet().stream().filter(e -> e.getValue().getOwnerId() != null).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + mapFromGraph.entrySet().removeIf(e -> preDerivedChainIdList.contains(e.getValue().getOwnerId())); + } else { + final Map valuesFrmPrevFinal = new HashMap<>(); + mapFromGraph.entrySet().stream().forEach(e -> { + T value = e.getValue(); + value = ToscaDataDefinition.removeAndCollectByOwnerId(value, preDerivedChainIdList); + valuesFrmPrevFinal.put(e.getKey(), value); + }); + valuesFrmPrev = valuesFrmPrevFinal; + mapFromGraph.entrySet().removeIf(e->e.getValue().isEmpty()); + } + + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(newDerivedList, label); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map dataFromDerivedAll = dataFromDerived.left().value(); + + Either, String> merged = ToscaDataDefinition.mergeDataMaps(dataFromDerivedAll, mapFromGraph); + if (merged.isRight()) { + log.debug("property {} cannot be overriden", merged.right().value()); + return StorageOperationStatus.INVALID_PROPERTY; + } + if (mergeValues && valuesFrmPrev != null) { + valuesFrmPrev.entrySet().forEach(e -> { + T newData = merged.left().value().get(e.getKey()); + if (newData != null) { + if (isSimpleHierarchy(label)) { + e.getValue().mergeFunction(newData, true); + }else{ + e.getValue().updateIfExist(newData, true); + } + } + }); + } + dataV.setJson(dataFromDerivedAll); + Either updateDataV = updateOrCopyOnUpdate(dataV, nodeTypeV, label); + if (updateDataV.isRight()) { + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateDataV.right().value()); + } + return StorageOperationStatus.OK; + } + + private boolean isSimpleHierarchy(EdgeLabelEnum label) { + switch (label) { + case PROPERTIES: + case ATTRIBUTES: + case ADDITIONAL_INFORMATION: + case ARTIFACTS: + case GROUPS: + case INPUTS: + return true; + default: + return false; + } + } + + @Override + public void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) { + fillMetadata(elementV, (NodeType) toscaElementToUpdate); + } + + public Either shouldUpdateDerivedVersion(ToscaElement toscaElementToUpdate, GraphVertex nodeTypeV) { + NodeType nodeType = (NodeType) toscaElementToUpdate; + + Either childVertex = janusGraphDao + .getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + JanusGraphOperationStatus getchildError = childVertex.right().value(); + if (getchildError == JanusGraphOperationStatus.NOT_FOUND) { + log.debug("derived resource for element {} not found", nodeTypeV.getUniqueId()); + return Either.right(StorageOperationStatus.OK); + } + + log.debug("Failed to fetch derived resource for element {} error {}", nodeTypeV.getUniqueId(), getchildError); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getchildError)); + } + GraphVertex firstDerivedInChain = childVertex.left().value(); + + String currentVersion = (String) firstDerivedInChain.getMetadataProperty(GraphPropertyEnum.VERSION); + + Map props = new HashMap<>(); + props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, nodeType.getDerivedFrom().get(0)); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + Map propsHasNot = new HashMap<>(); + propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); + Either, JanusGraphOperationStatus> byCriteria = janusGraphDao + .getByCriteria(VertexTypeEnum.NODE_TYPE, props, propsHasNot, JsonParseFlagEnum.NoParse); + if (byCriteria.isRight()) { + log.debug("Failed to fetch derived by props {} error {}", props, byCriteria.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(byCriteria.right().value())); + } + List lastDerived = byCriteria.left().value(); + // now supported only one derived!!! Change in future!(Evg) + GraphVertex derivedFromHighest = lastDerived.get(0); + String highestVersion = (String) derivedFromHighest.getMetadataProperty(GraphPropertyEnum.VERSION); + if (!highestVersion.equals(currentVersion)) { + + // need to update to latest version of derived from + StorageOperationStatus updateDerived = updateDerived(toscaElementToUpdate, nodeTypeV, firstDerivedInChain, derivedFromHighest, true); + + if (updateDerived != StorageOperationStatus.OK) { + log.debug("Failed to update {} to highest derived {} from error {}", nodeTypeV.getUniqueId(), derivedFromHighest.getUniqueId(), updateDerived); + return Either.right(updateDerived); + } + return getToscaElement(nodeTypeV.getUniqueId(), new ComponentParametersView()); + } + // no version changes + return Either.right(StorageOperationStatus.OK); + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperation.java new file mode 100644 index 0000000000..349ea809e7 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperation.java @@ -0,0 +1,62 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@org.springframework.stereotype.Component +public class PolicyOperation { + + private static final Logger log = Logger.getLogger(PolicyOperation.class.getName()); + private TopologyTemplateOperation topologyTemplateOperation; + private JanusGraphDao janusGraphDao; + + public PolicyOperation(TopologyTemplateOperation topologyTemplateOperation, JanusGraphDao janusGraphDao) { + this.topologyTemplateOperation = topologyTemplateOperation; + this.janusGraphDao = janusGraphDao; + } + + /** + * updates a list of policy properties by overriding the existing ones with the same name + * @param containerComponent the container of the policy of which its properties are to be updated + * @param policyId the id of the policy of which its properties are to be updated + * @param propertiesToUpdate the policy properties to update + * @return the update operation status + */ + public StorageOperationStatus updatePolicyProperties(Component containerComponent, String policyId, List propertiesToUpdate) { + log.debug("#updatePolicyProperties - updating the properties of policy {} in component {}", policyId, containerComponent.getUniqueId()); + PolicyDefinition policy = containerComponent.getPolicyById(policyId); + return janusGraphDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.NoParse) + .either(containerVertex -> updatePolicyProperties(containerVertex, policy, propertiesToUpdate), + DaoStatusConverter::convertJanusGraphStatusToStorageStatus); + } + + private StorageOperationStatus updatePolicyProperties(GraphVertex container, PolicyDefinition policy, List propertiesToUpdate) { + List policyProperties = policy.getProperties(); + List updatedPolicyProperties = updatePolicyProperties(policyProperties, propertiesToUpdate); + policy.setProperties(updatedPolicyProperties); + return topologyTemplateOperation.updatePolicyOfToscaElement(container, policy); + } + + private List updatePolicyProperties(List currentPolicyProperties, List toBeUpdatedProperties) { + Map currPropsByName = MapUtil.toMap(currentPolicyProperties, PropertyDataDefinition::getName); + overrideCurrentPropertiesWithUpdatedProperties(currPropsByName, toBeUpdatedProperties); + return new ArrayList<>(currPropsByName.values()); + } + + private void overrideCurrentPropertiesWithUpdatedProperties(Map currPropsByName, List toBeUpdatedProperties) { + toBeUpdatedProperties.forEach(prop -> currPropsByName.put(prop.getName(), prop)); + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/RequirementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/RequirementOperation.java new file mode 100644 index 0000000000..9c1d1eec3b --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/RequirementOperation.java @@ -0,0 +1,92 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * 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. + */ + +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +@org.springframework.stereotype.Component("requirement-operation") +public class RequirementOperation extends BaseOperation { + private static final Logger LOGGER = LoggerFactory.getLogger(RequirementOperation.class); + + public Either, StorageOperationStatus> addRequirement( + String componentId, + List requirementDefinitions) { + return addOrUpdateRequirements( componentId, requirementDefinitions, false); + } + + public Either, StorageOperationStatus> updateRequirement( + String componentId, + List requirementDefinitions) { + return addOrUpdateRequirements( componentId, requirementDefinitions, true); + } + + + private Either, StorageOperationStatus> addOrUpdateRequirements(String componentId, + List requirementDefinitions, + boolean isUpdateAction) { + + StorageOperationStatus statusRes = performUpdateToscaAction(isUpdateAction, + componentId, Collections + .singletonList(convertToListRequirementDataDefinition(requirementDefinitions))); + if (!statusRes.equals(StorageOperationStatus.OK)) { + janusGraphDao.rollback(); + LOGGER.error("Failed to find the parent capability of capability type {}." + + " status is {}", componentId, statusRes); + return Either.right(statusRes); + } + janusGraphDao.commit(); + return Either.left(requirementDefinitions); + } + + public StorageOperationStatus deleteRequirements(Component component, + String requirementToDelete) { + return deleteToscaDataElements(component.getUniqueId(), + EdgeLabelEnum.REQUIREMENTS, Collections.singletonList(requirementToDelete)); + } + + private static ListRequirementDataDefinition convertToListRequirementDataDefinition( + List requirementDefinitions) { + List requirementDataDefinitions = + new ArrayList<>(requirementDefinitions); + return new ListRequirementDataDefinition(requirementDataDefinitions); + } + + private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, + String componentId, List toscaDataList) { + if (isUpdate) { + return updateToscaDataOfToscaElement(componentId, EdgeLabelEnum.REQUIREMENTS, + VertexTypeEnum.REQUIREMENTS, toscaDataList, JsonPresentationFields.CAPABILITY); + } else { + return addToscaDataToToscaElement(componentId, EdgeLabelEnum.REQUIREMENTS, + VertexTypeEnum.REQUIREMENTS, toscaDataList, JsonPresentationFields.CAPABILITY); + } + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java new file mode 100644 index 0000000000..a429033505 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java @@ -0,0 +1,1623 @@ +/*- + * ============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.jsonjanusgraph.operations; + +import com.google.gson.reflect.TypeToken; +import fj.data.Either; +import org.apache.commons.collections.MapUtils; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.CapabilityRequirementNameResolver; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; +import org.openecomp.sdc.be.model.operations.StorageException; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +@org.springframework.stereotype.Component("topology-template-operation") +public class TopologyTemplateOperation extends ToscaElementOperation { + + private static final Logger log = Logger.getLogger(TopologyTemplateOperation.class); + private Set nodeTypeSet = new HashSet<>(Arrays.asList(OriginTypeEnum.VFC, OriginTypeEnum.CP, OriginTypeEnum.VL, OriginTypeEnum.Configuration, OriginTypeEnum.VFCMT)); + + @Autowired + private ArchiveOperation archiveOperation; + + public Either createTopologyTemplate(TopologyTemplate topologyTemplate) { + Either result = null; + + topologyTemplate.generateUUID(); + + topologyTemplate = getResourceMetaDataFromResource(topologyTemplate); + String resourceUniqueId = topologyTemplate.getUniqueId(); + if (resourceUniqueId == null) { + resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId(); + topologyTemplate.setUniqueId(resourceUniqueId); + } + + GraphVertex topologyTemplateVertex = new GraphVertex(); + topologyTemplateVertex = fillMetadata(topologyTemplateVertex, topologyTemplate, JsonParseFlagEnum.ParseAll); + + Either createdVertex = janusGraphDao.createVertex(topologyTemplateVertex); + if (createdVertex.isRight()) { + JanusGraphOperationStatus status = createdVertex.right().value(); + log.debug("Error returned after creating topology template data node {}. status returned is ", topologyTemplateVertex, status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + return result; + } + + topologyTemplateVertex = createdVertex.left().value(); + + StorageOperationStatus assosiateCommon = assosiateCommonForToscaElement(topologyTemplateVertex, topologyTemplate, null); + if (assosiateCommon != StorageOperationStatus.OK) { + result = Either.right(assosiateCommon); + return result; + } + + StorageOperationStatus associateCategory = assosiateMetadataToCategory(topologyTemplateVertex, topologyTemplate); + if (associateCategory != StorageOperationStatus.OK) { + result = Either.right(associateCategory); + return result; + } + + StorageOperationStatus associateInputs = associateInputsToComponent(topologyTemplateVertex, topologyTemplate); + if (associateInputs != StorageOperationStatus.OK) { + result = Either.right(associateInputs); + return result; + } + StorageOperationStatus associateGroups = associateGroupsToComponent(topologyTemplateVertex, topologyTemplate); + if (associateGroups != StorageOperationStatus.OK) { + result = Either.right(associateGroups); + return result; + } + StorageOperationStatus associatePolicies = associatePoliciesToComponent(topologyTemplateVertex, topologyTemplate); + if (associatePolicies != StorageOperationStatus.OK) { + result = Either.right(associatePolicies); + return result; + } + StorageOperationStatus associateInstAttr = associateInstAttributesToComponent(topologyTemplateVertex, topologyTemplate); + if (associateInstAttr != StorageOperationStatus.OK) { + result = Either.right(associateInstAttr); + return result; + } + StorageOperationStatus associateInstProperties = associateInstPropertiesToComponent(topologyTemplateVertex, topologyTemplate); + if (associateInstProperties != StorageOperationStatus.OK) { + result = Either.right(associateInstProperties); + return result; + } + StorageOperationStatus associateInstInputs = associateInstInputsToComponent(topologyTemplateVertex, topologyTemplate); + if (associateInstProperties != StorageOperationStatus.OK) { + result = Either.right(associateInstInputs); + return result; + } + StorageOperationStatus associateInstGroups = associateInstGroupsToComponent(topologyTemplateVertex, topologyTemplate); + if (associateInstGroups != StorageOperationStatus.OK) { + result = Either.right(associateInstInputs); + return result; + } + + StorageOperationStatus associateRequirements = associateRequirementsToResource(topologyTemplateVertex, topologyTemplate); + if (associateRequirements != StorageOperationStatus.OK) { + result = Either.right(associateRequirements); + return result; + } + + StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(topologyTemplateVertex, topologyTemplate); + if (associateCapabilities != StorageOperationStatus.OK) { + result = Either.right(associateCapabilities); + return result; + } + + StorageOperationStatus associateArtifacts = associateTopologyTemplateArtifactsToComponent(topologyTemplateVertex, topologyTemplate); + if (associateArtifacts != StorageOperationStatus.OK) { + result = Either.right(associateArtifacts); + return result; + } + + StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(topologyTemplateVertex, topologyTemplate); + if (addAdditionalInformation != StorageOperationStatus.OK) { + result = Either.right(addAdditionalInformation); + return result; + } + StorageOperationStatus associateCapProperties = associateCapPropertiesToResource(topologyTemplateVertex, topologyTemplate); + if (associateCapProperties != StorageOperationStatus.OK) { + result = Either.right(associateCapProperties); + return result; + } + + StorageOperationStatus associateInterfaces = associateInterfacesToComponent(topologyTemplateVertex, topologyTemplate); + if (associateInterfaces != StorageOperationStatus.OK) { + result = Either.right(associateInterfaces); + return result; + } + + StorageOperationStatus associatePathProperties = associateForwardingPathToResource(topologyTemplateVertex, topologyTemplate); + if (associateCapProperties != StorageOperationStatus.OK) { + result = Either.right(associatePathProperties); + return result; + } + + + return Either.left(topologyTemplate); + + } + + private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + return associatePoliciesToComponent(nodeTypeVertex, topologyTemplate.getPolicies()); + } + + private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex, Map policies) { + if (policies != null && !policies.isEmpty()) { + policies.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { + String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName()); + p.setUniqueId(uid); + }); + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.POLICIES, EdgeLabelEnum.POLICIES, policies); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateForwardingPathToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) { + Map forwardingPaths = topologyTemplate.getForwardingPaths(); + return associateForwardingPathToComponent(topologyTemplateVertex, forwardingPaths); + } + + private StorageOperationStatus associateNodeFilterToResource(GraphVertex topologyTemplateVertex, + TopologyTemplate topologyTemplate) { + Map nodeFilters = + topologyTemplate.getNodeFilterComponents(); + return associateNodeFiltersToComponent(topologyTemplateVertex, nodeFilters); + } + + private StorageOperationStatus associateCapPropertiesToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) { + Map calculatedCapProperties = topologyTemplate + .getCalculatedCapabilitiesProperties(); + if (MapUtils.isNotEmpty(calculatedCapProperties)) { + Either associateElementToData = associateElementToData + (topologyTemplateVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, + EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapProperties); + if (associateElementToData.isRight()) { + return associateElementToData.right().value(); + } + } + + Map capabilitiesProperties = topologyTemplate.getCapabilitiesProperties(); + if (MapUtils.isNotEmpty(capabilitiesProperties)) { + Either associateElementToData = + associateElementToData(topologyTemplateVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, + EdgeLabelEnum.CAPABILITIES_PROPERTIES, capabilitiesProperties); + if (associateElementToData.isRight()) { + return associateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map calculatedCapabilities = topologyTemplate.getCalculatedCapabilities(); + if (calculatedCapabilities != null && !calculatedCapabilities.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calculatedCapabilities); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + Map fullfilledCapabilities = topologyTemplate.getFullfilledCapabilities(); + if (fullfilledCapabilities != null && !fullfilledCapabilities.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullfilledCapabilities); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + Map capabilities = topologyTemplate.getCapabilities(); + if(MapUtils.isNotEmpty(capabilities)) { + Either associateElementToData = + associateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILITIES, + EdgeLabelEnum.CAPABILITIES, capabilities); + if (associateElementToData.isRight()) { + return associateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + + } + + private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map calculatedRequirements = topologyTemplate.getCalculatedRequirements(); + if (calculatedRequirements != null && !calculatedRequirements.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calculatedRequirements); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + Map fullfilledRequirements = topologyTemplate.getFullfilledRequirements(); + if (fullfilledRequirements != null && !fullfilledRequirements.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullfilledRequirements); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + Map requirements = topologyTemplate.getRequirements(); + if(MapUtils.isNotEmpty(requirements)) { + Either associateElementToData = + associateElementToData(nodeTypeVertex, VertexTypeEnum.REQUIREMENTS, + EdgeLabelEnum.REQUIREMENTS, requirements); + if (associateElementToData.isRight()) { + return associateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateTopologyTemplateArtifactsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map addInformation = topologyTemplate.getServiceApiArtifacts(); + + if (addInformation != null && !addInformation.isEmpty()) { + addInformation.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); + a.setUniqueId(uniqueId); + }); + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.SERVICE_API_ARTIFACTS, EdgeLabelEnum.SERVICE_API_ARTIFACTS, addInformation); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + Map instArtifacts = topologyTemplate.getInstDeploymentArtifacts(); + + if (instArtifacts != null && !instArtifacts.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, instArtifacts); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + Map instInfoArtifacts = topologyTemplate.getInstanceArtifacts(); + + if (instInfoArtifacts != null && !instInfoArtifacts.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS, instInfoArtifacts); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + + Map addInformation = topologyTemplate.getAdditionalInformation(); + + if (addInformation != null && !addInformation.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformation); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map instProps = topologyTemplate.getInstProperties(); + return associateInstPropertiesToComponent(nodeTypeVertex, instProps); + } + + public StorageOperationStatus associateInstInputsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map instProps = topologyTemplate.getInstInputs(); + return associateInstInputsToComponent(nodeTypeVertex, instProps); + } + + public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map instGroups = topologyTemplate.getInstGroups(); + return associateInstGroupsToComponent(nodeTypeVertex, instGroups); + } + + + public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map instProps) { + if (instProps != null && !instProps.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_PROPERTIES, EdgeLabelEnum.INST_PROPERTIES, instProps); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus associateInstInputsToComponent(GraphVertex nodeTypeVertex, Map instInputs) { + if (instInputs != null && !instInputs.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, instInputs); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, Map instGroups) { + if (instGroups != null && !instGroups.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, instGroups); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + + public StorageOperationStatus deleteInstInputsToComponent(GraphVertex nodeTypeVertex, Map instInputs) { + + if (instInputs != null && !instInputs.isEmpty()) { + instInputs.entrySet().forEach(i -> { + List uniqueKeys = new ArrayList<>(i.getValue().getMapToscaDataDefinition().keySet()); + List pathKeys = new ArrayList<>(); + pathKeys.add(i.getKey()); + + StorageOperationStatus status = deleteToscaDataDeepElements(nodeTypeVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, uniqueKeys, pathKeys, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + return; + } + }); + } + + return StorageOperationStatus.OK; + } + + public StorageOperationStatus addInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map instInputs) { + + if (instInputs != null && !instInputs.isEmpty()) { + instInputs.entrySet().forEach(i -> { + StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(nodeTypeVertex, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, i.getValue(), i.getKey()); + if (status != StorageOperationStatus.OK) { + return; + } + }); + } + + return StorageOperationStatus.OK; + } + + public StorageOperationStatus associateInstDeploymentArtifactsToComponent(GraphVertex nodeTypeVertex, Map instArtifacts) { + return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + } + + public StorageOperationStatus associateInstArtifactsToComponent(GraphVertex nodeTypeVertex, Map instArtifacts) { + return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS); + } + + private StorageOperationStatus associateInstanceArtifactsToComponent(GraphVertex nodeTypeVertex, Map instProps, VertexTypeEnum vertexType, EdgeLabelEnum edgeLabel) { + if (instProps != null && !instProps.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, vertexType, edgeLabel, instProps); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus associateOrAddCalcCapReqToComponent(GraphVertex nodeTypeVertex, Map calcRequirements, Map calcCapabilty, Map calculatedCapabilitiesProperties) { + if (calcRequirements != null && !calcRequirements.isEmpty()) { + Either assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calcRequirements); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + Map fullFilled = new HashMap<>(); + assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullFilled); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + if (calcCapabilty != null && !calcCapabilty.isEmpty()) { + Either assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calcCapabilty); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + Map fullFilled = new HashMap<>(); + assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullFilled); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + if (calculatedCapabilitiesProperties != null && !calculatedCapabilitiesProperties.isEmpty()) { + return associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, + EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapabilitiesProperties) + .right() + .on(v -> StorageOperationStatus.OK); + } + return StorageOperationStatus.OK; + } + + private Either associateOrAddElementToData(GraphVertex nodeTypeVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map dataMap) { + return janusGraphDao.getChildVertex(nodeTypeVertex, edgeLabelEnum, JsonParseFlagEnum.ParseJson) + .either(dataVertex -> addElementsToComponent(nodeTypeVertex, dataVertex, vertexTypeEnum, edgeLabelEnum, dataMap), + status -> associateElementToDataIfNotFound(status, nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap)); + } + + private Either associateElementToDataIfNotFound(JanusGraphOperationStatus status, GraphVertex nodeTypeVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map dataMap) { + if (status == JanusGraphOperationStatus.NOT_FOUND) { + return associateElementToData(nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap); + } + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + + private Either addElementsToComponent(GraphVertex nodeTypeVertex, GraphVertex dataVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map dataMap) { + Optional error = dataMap.entrySet() + .stream() + .map(e -> addElementToComponent(nodeTypeVertex.getUniqueId(), vertexTypeEnum, edgeLabelEnum, e)) + .filter(s -> s != StorageOperationStatus.OK) + .findFirst(); + if (error.isPresent()) { + return Either.right(error.get()); + } + return Either.left(dataVertex); + } + + private StorageOperationStatus associateInstAttributesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map instAttr = topologyTemplate.getInstAttributes(); + return associateInstAttributeToComponent(nodeTypeVertex, instAttr); + } + + public StorageOperationStatus associateForwardingPathToComponent(GraphVertex nodeTypeVertex, Map forwardingPathMap) { + if (forwardingPathMap != null && !forwardingPathMap.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FORWARDING_PATH, EdgeLabelEnum.FORWARDING_PATH, forwardingPathMap); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus associateInstAttributeToComponent(GraphVertex nodeTypeVertex, Map instAttr) { + if (instAttr != null && !instAttr.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_ATTRIBUTES, EdgeLabelEnum.INST_ATTRIBUTES, instAttr); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, Map groups) { + + if (groups != null && !groups.isEmpty()) { + groups.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { + String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName()); + p.setUniqueId(uid); + }); + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.GROUPS, EdgeLabelEnum.GROUPS, groups); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + return associateGroupsToComponent(nodeTypeVertex, topologyTemplate.getGroups()); + } + + public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map inputs = topologyTemplate.getInputs(); + return associateInputsToComponent(nodeTypeVertex, inputs, topologyTemplate.getUniqueId()); + } + + public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, Map inputs, String id) { + if (inputs != null && !inputs.isEmpty()) { + inputs.values().stream().filter(e -> e.getUniqueId() == null).forEach(e -> e.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(id, e.getName()))); + + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INPUTS, EdgeLabelEnum.INPUTS, inputs); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private GraphVertex fillMetadata(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate, JsonParseFlagEnum flag) { + nodeTypeVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); + fillCommonMetadata(nodeTypeVertex, topologyTemplate); + if (flag == JsonParseFlagEnum.ParseAll || flag == JsonParseFlagEnum.ParseJson) { + nodeTypeVertex.setJson(topologyTemplate.getCompositions()); + } + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.CSAR_UUID, topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, topologyTemplate.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS)); + + return nodeTypeVertex; + + } + + private StorageOperationStatus assosiateMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + if (topologyTemplate.getResourceType() == null) { + // service + return associateServiceMetadataToCategory(nodeTypeVertex, topologyTemplate); + } else { + // VF + return assosiateResourceMetadataToCategory(nodeTypeVertex, topologyTemplate); + } + } + + private StorageOperationStatus associateServiceMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + String categoryName = topologyTemplate.getCategories().get(0).getName(); + Either category = categoryOperation.getCategory(categoryName, VertexTypeEnum.SERVICE_CATEGORY); + if (category.isRight()) { + log.trace("NO category {} for service {}", categoryName, topologyTemplate.getUniqueId()); + return StorageOperationStatus.CATEGORY_NOT_FOUND; + } + GraphVertex categoryV = category.left().value(); + JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(nodeTypeVertex, categoryV, EdgeLabelEnum.CATEGORY, new HashMap<>()); + if (createEdge != JanusGraphOperationStatus.OK) { + log.trace("Failed to associate resource {} to category {} with id {}", topologyTemplate.getUniqueId(), categoryName, categoryV.getUniqueId()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge); + } + return StorageOperationStatus.OK; + } + + @Override + public Either getToscaElement(String uniqueId, ComponentParametersView componentParametersView) { + JsonParseFlagEnum parseFlag = componentParametersView.detectParseFlag(); + + Either componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.TOPOLOGY_TEMPLATE, parseFlag); + if (componentByLabelAndId.isRight()) { + return Either.right(componentByLabelAndId.right().value()); + } + GraphVertex componentV = componentByLabelAndId.left().value(); + + return getToscaElement(componentV, componentParametersView); + + } + // ------------------------------------------------------------- + + public Either getToscaElement(GraphVertex componentV, ComponentParametersView componentParametersView) { + TopologyTemplate toscaElement; + + toscaElement = convertToTopologyTemplate(componentV); + JanusGraphOperationStatus status; + if (!componentParametersView.isIgnoreUsers()) { + status = setCreatorFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + + status = setLastModifierFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreCategories()) { + status = setTopologyTempalteCategoriesFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + + } + } + if (!componentParametersView.isIgnoreArtifacts()) { + JanusGraphOperationStatus storageStatus = setAllArtifactsFromGraph(componentV, toscaElement); + if (storageStatus != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(storageStatus)); + } + } + if (!componentParametersView.isIgnoreComponentInstancesProperties()) { + status = setComponentInstancesPropertiesFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreCapabilities()) { + status = setCapabilitiesFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreRequirements()) { + status = setRequirementsFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreAllVersions()) { + status = setAllVersions(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreAdditionalInformation()) { + status = setAdditionalInformationFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + + if (!componentParametersView.isIgnoreGroups()) { + status = setGroupsFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + + } + if (!componentParametersView.isIgnorePolicies()) { + status = setPoliciesFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + + } + if (!componentParametersView.isIgnoreComponentInstances()) { + status = setInstGroupsFromGraph(componentV, toscaElement); + + //Mark all CIs that has archived origins + archiveOperation.setArchivedOriginsFlagInComponentInstances(componentV); + + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + + } + if (!componentParametersView.isIgnoreInputs()) { + status = setInputsFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + + } + if (!componentParametersView.isIgnoreProperties()) { + status = setPropertiesFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + + } + + if (!componentParametersView.isIgnoreComponentInstancesInputs()) { + status = setComponentInstancesInputsFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + + } + } + + if (!componentParametersView.isIgnoreCapabiltyProperties()) { + status = setComponentInstancesCapPropertiesFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + + } + } + + if (!componentParametersView.isIgnoreForwardingPath()) { + status = setForwardingGraphPropertiesFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + + } + } + + if (!componentParametersView.isIgnoreNodeFilter()) { + status = setNodeFilterComponentFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + + } + } + + if (!componentParametersView.isIgnoreInterfaces()) { + JanusGraphOperationStatus storageStatus = setInterfacesFromGraph(componentV, toscaElement); + if (storageStatus != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(storageStatus)); + + } + } + + if (!componentParametersView.isIgnoreComponentInstancesInterfaces()) { + JanusGraphOperationStatus storageStatus = + setComponentInstancesInterfacesFromGraph(componentV, toscaElement); + if (storageStatus != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(storageStatus)); + } + } + + if (!componentParametersView.isIgnoreDataType()) { + JanusGraphOperationStatus storageStatus = setDataTypesFromGraph(componentV, toscaElement); + if (storageStatus != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(storageStatus)); + } + } + + return Either.left(toscaElement); + } + + private JanusGraphOperationStatus setDataTypesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.DATA_TYPES); + if (result.isLeft()) { + toscaElement.setDataTypes(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setPoliciesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.POLICIES); + if (result.isLeft()) { + toscaElement.setPolicies(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setInterfacesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INTERFACE); + if (result.isLeft()) { + topologyTemplate.setInterfaces(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + + private JanusGraphOperationStatus setComponentInstancesInterfacesFromGraph(GraphVertex componentV, + TopologyTemplate topologyTemplate) { + Either, JanusGraphOperationStatus> result = + getDataFromGraph(componentV, EdgeLabelEnum.INST_INTERFACES); + if (result.isLeft()) { + result.left().value().entrySet().forEach(entry -> topologyTemplate + .addComponentInstanceInterfaceMap(entry.getKey(), entry.getValue())); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private StorageOperationStatus associateInterfacesToComponent(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) { + Map interfaceMap = topologyTemplate.getInterfaces(); + if (interfaceMap != null && !interfaceMap.isEmpty()) { + Either assosiateElementToData = associateElementToData(topologyTemplateVertex, VertexTypeEnum.INTERFACE, EdgeLabelEnum.INTERFACE, interfaceMap); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus associateNodeFiltersToComponent(GraphVertex nodeTypeVertex, + Map filterMaps) { + if (filterMaps != null && !filterMaps.isEmpty()) { + Either assosiateElementToData = associateElementToData + (nodeTypeVertex, VertexTypeEnum.NODE_FILTER_TEMPLATE, + EdgeLabelEnum.NODE_FILTER_TEMPLATE, filterMaps); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private JanusGraphOperationStatus setForwardingGraphPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.FORWARDING_PATH); + if (result.isLeft()) { + topologyTemplate.setForwardingPaths(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + + private JanusGraphOperationStatus setComponentInstancesCapPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES); + if (result.isLeft()) { + topologyTemplate.setCalculatedCapabilitiesProperties(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + Either, JanusGraphOperationStatus> capPropResult = + getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES_PROPERTIES); + if (capPropResult.isLeft()) { + topologyTemplate.setCapabilitiesProperties(capPropResult.left().value()); + } else { + if (capPropResult.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return capPropResult.right().value(); + } + } + + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setPropertiesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.PROPERTIES); + if (result.isLeft()) { + toscaElement.setProperties(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setInstGroupsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_GROUPS); + if (result.isLeft()) { + topologyTemplate.setInstGroups(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setComponentInstancesPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_PROPERTIES); + if (result.isLeft()) { + topologyTemplate.setInstProperties(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setComponentInstancesInputsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_INPUTS); + if (result.isLeft()) { + topologyTemplate.setInstInputs(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setNodeFilterComponentFromGraph(GraphVertex componentV, + TopologyTemplate topologyTemplate) { + Either, JanusGraphOperationStatus> result = + getDataFromGraph(componentV, + EdgeLabelEnum.NODE_FILTER_TEMPLATE); + if (result.isLeft()) { + topologyTemplate.setNodeFilterComponents(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + @Override + protected JanusGraphOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); + if (result.isLeft()) { + ((TopologyTemplate) toscaElement).setCalculatedRequirements(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); + if (result.isLeft()) { + ((TopologyTemplate) toscaElement).setFullfilledRequirements(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + Either, JanusGraphOperationStatus> requirementResult = + getDataFromGraph(componentV, EdgeLabelEnum.REQUIREMENTS); + if (requirementResult.isLeft()) { + toscaElement.setRequirements(requirementResult.left().value()); + } else { + if (requirementResult.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return requirementResult.right().value(); + } + } + return JanusGraphOperationStatus.OK; + + } + + protected JanusGraphOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAPABILITIES); + if (result.isLeft()) { + ((TopologyTemplate) toscaElement).setCalculatedCapabilities(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); + if (result.isLeft()) { + ((TopologyTemplate) toscaElement).setFullfilledCapabilities(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + Either, JanusGraphOperationStatus> capabilitiesResult = + getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES); + if (capabilitiesResult.isLeft()) { + toscaElement.setCapabilities(capabilitiesResult.left().value()); + } else { + if (capabilitiesResult.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return capabilitiesResult.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setAllArtifactsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { + JanusGraphOperationStatus storageStatus = setArtifactsFromGraph(componentV, toscaElement); + if (storageStatus != JanusGraphOperationStatus.OK) { + return storageStatus; + } + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.SERVICE_API_ARTIFACTS); + if (result.isLeft()) { + toscaElement.setServiceApiArtifacts(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + Either, JanusGraphOperationStatus> resultInstArt = getDataFromGraph(componentV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + if (resultInstArt.isLeft()) { + toscaElement.setInstDeploymentArtifacts(resultInstArt.left().value()); + } else { + if (resultInstArt.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return resultInstArt.right().value(); + } + } + Either, JanusGraphOperationStatus> instanceArt = getDataFromGraph(componentV, EdgeLabelEnum.INSTANCE_ARTIFACTS); + if (instanceArt.isLeft()) { + toscaElement.setInstanceArtifacts(instanceArt.left().value()); + } else { + if (instanceArt.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return instanceArt.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setInputsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INPUTS); + if (result.isLeft()) { + toscaElement.setInputs(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setGroupsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.GROUPS); + if (result.isLeft()) { + toscaElement.setGroups(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setTopologyTempalteCategoriesFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + List categories = new ArrayList<>(); + + switch (componentV.getType()) { + case RESOURCE: + return setResourceCategoryFromGraph(componentV, toscaElement); + case SERVICE: + return setServiceCategoryFromGraph(componentV, toscaElement, categories); + + default: + log.debug("Not supported component type {} ", componentV.getType()); + break; + } + return JanusGraphOperationStatus.OK; + } + + private JanusGraphOperationStatus setServiceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement, List categories) { + Either childVertex = janusGraphDao.getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value()); + return childVertex.right().value(); + } + GraphVertex categoryV = childVertex.left().value(); + Map metadataProperties = categoryV.getMetadataProperties(); + CategoryDefinition category = new CategoryDefinition(); + category.setUniqueId(categoryV.getUniqueId()); + category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME)); + category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME)); + + Type listTypeCat = new TypeToken>() { + }.getType(); + List iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS.getProperty()), listTypeCat); + category.setIcons(iconsfromJsonCat); + categories.add(category); + toscaElement.setCategories(categories); + + return JanusGraphOperationStatus.OK; + } + + @SuppressWarnings("unchecked") + private TopologyTemplate convertToTopologyTemplate(GraphVertex componentV) { + + TopologyTemplate topologyTemplate = super.convertToComponent(componentV); + + Map json = (Map) componentV.getJson(); + topologyTemplate.setCompositions(json); + + return topologyTemplate; + } + + @Override + public Either deleteToscaElement(GraphVertex toscaElementVertex) { + Either nodeType = getToscaElement(toscaElementVertex, new ComponentParametersView()); + if (nodeType.isRight()) { + log.debug("Failed to fetch tosca element {} error {}", toscaElementVertex.getUniqueId(), nodeType.right().value()); + return nodeType; + } + JanusGraphOperationStatus status = disassociateAndDeleteCommonElements(toscaElementVertex); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_ATTRIBUTES); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate instances attributes for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_PROPERTIES); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate instances properties for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate instances inputs for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.GROUPS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate groups for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.POLICIES); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate policies for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_GROUPS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate instance groups for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INPUTS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate inputs for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate instance inputs for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES_PROPERTIES); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate capabilities properties for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAPABILITIES); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate calculated capabiliites for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_CAPABILITIES); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate fullfilled capabilities for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate calculated capabiliites properties for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_REQUIREMENTS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate calculated requirements for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate full filled requirements for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate instance artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.SERVICE_API_ARTIFACTS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INTERFACE); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate interfaces for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INSTANCE_ARTIFACTS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate instance artifact for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, + EdgeLabelEnum.REQUIREMENTS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate requirements for {} error {}", + toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, + EdgeLabelEnum.CAPABILITIES); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate capabilities for {} error {}", + toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INTERFACES); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disassociate instances interfaces for {} error {}", toscaElementVertex.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + toscaElementVertex.getVertex().remove(); + log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId()); + + return nodeType; + } + + @SuppressWarnings("unchecked") + @Override + public Either createToscaElement(ToscaElement toscaElement) { + return createTopologyTemplate((TopologyTemplate) toscaElement); + } + + @Override + protected JanusGraphOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) { + return setTopologyTempalteCategoriesFromGraph(vertexComponent, toscaElement); + } + + @Override + protected StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) { + // Product isn't supported now!! + // TODO add for Product + if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.SERVICE) { + return validateServiceCategory(toscaElementToUpdate, elementV); + } else { + // Resource + return validateResourceCategory(toscaElementToUpdate, elementV); + } + } + + @Override + protected StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV) { + // not relevant now for topology template + return StorageOperationStatus.OK; + } + + @Override + public void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) { + fillMetadata(elementV, (TopologyTemplate) toscaElementToUpdate, flag); + } + + private StorageOperationStatus validateServiceCategory(T toscaElementToUpdate, GraphVertex elementV) { + StorageOperationStatus status = StorageOperationStatus.OK; + List newCategoryList = toscaElementToUpdate.getCategories(); + CategoryDefinition newCategory = newCategoryList.get(0); + + Either childVertex = janusGraphDao.getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value()); + } + + GraphVertex categoryV = childVertex.left().value(); + Map metadataProperties = categoryV.getMetadataProperties(); + String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); + + String newCategoryName = newCategory.getName(); + if (newCategoryName != null && !newCategoryName.equals(categoryNameCurrent)) { + // the category was changed + Either getCategoryVertex = categoryOperation.getCategory(newCategoryName, VertexTypeEnum.SERVICE_CATEGORY); + + if (getCategoryVertex.isRight()) { + return getCategoryVertex.right().value(); + } + GraphVertex newCategoryV = getCategoryVertex.left().value(); + status = moveCategoryEdge(elementV, newCategoryV); + log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status); + } + return status; + } + + public Either updateDistributionStatus(String uniqueId, User user, DistributionStatusEnum distributionStatus) { + + Either result = null; + String userId = user.getUserId(); + Either getRes = findUserVertex(userId); + GraphVertex userVertex = null; + GraphVertex serviceVertex = null; + if (getRes.isRight()) { + JanusGraphOperationStatus status = getRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Cannot find user {} in the graph. status is {}", userId, status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + if (result == null) { + userVertex = getRes.left().value(); + getRes = janusGraphDao.getVertexById(uniqueId, JsonParseFlagEnum.ParseMetadata); + if (getRes.isRight()) { + JanusGraphOperationStatus status = getRes.right().value(); + log.debug("Cannot find service {} in the graph. status is {}", uniqueId, status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (result == null) { + serviceVertex = getRes.left().value(); + Iterator edgeIterator = serviceVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER.name()); + if (edgeIterator.hasNext()) { + log.debug("Remove existing edge from user to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER); + edgeIterator.next().remove(); + } + } + if (result == null) { + JanusGraphOperationStatus status = janusGraphDao.createEdge(userVertex, serviceVertex, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER, null); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to associate user {} to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (result == null) { + serviceVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, distributionStatus.name()); + long lastUpdateDate = System.currentTimeMillis(); + serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate); + Either updateRes = janusGraphDao.updateVertex(serviceVertex); + if (updateRes.isRight()) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateRes.right().value())); + } + } + if (result == null) { + result = Either.left(serviceVertex); + } + return result; + } + + /** + * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId + * + * @param componentId + * @param instanceId + * @param capabilityName + * @param capabilityType + * @param ownerId + * @return + */ + public Either, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) { + + Either, StorageOperationStatus> result = null; + Map mapPropertiesDataDefinition = null; + Either componentByLabelAndId = getComponentByLabelAndId(componentId, ToscaElementTypeEnum.TOPOLOGY_TEMPLATE, JsonParseFlagEnum.NoParse); + if (componentByLabelAndId.isRight()) { + result = Either.right(componentByLabelAndId.right().value()); + } + if (componentByLabelAndId.isLeft()) { + Either, JanusGraphOperationStatus> getDataRes = getDataFromGraph(componentByLabelAndId.left().value(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES); + if (getDataRes.isRight()) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getDataRes.right().value())); + } else { + mapPropertiesDataDefinition = getDataRes.left().value(); + } + } + if (isNotEmptyMapOfProperties(instanceId, mapPropertiesDataDefinition)) { + result = Either.left(findComponentInstanceCapabilityProperties(instanceId, capabilityName, capabilityType, ownerId, mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition())); + } + return result; + } + + public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceId, MapCapabilityProperty instanceProperties) { + return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, instanceProperties, componentInstanceId); + } + + public StorageOperationStatus updateComponentInstanceInterfaces(Component containerComponent, + String componentInstanceId, + MapInterfaceDataDefinition instanceInterfaces) { + if (MapUtils.isNotEmpty(instanceInterfaces.getMapToscaDataDefinition())) { + return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), + EdgeLabelEnum.INST_INTERFACES, instanceInterfaces, componentInstanceId); + } + return StorageOperationStatus.OK; + } + + + private boolean isNotEmptyMapOfProperties(String instanceId, Map mapPropertiesDataDefinition) { + return MapUtils.isNotEmpty(mapPropertiesDataDefinition) && + mapPropertiesDataDefinition.get(instanceId) != null && + MapUtils.isNotEmpty(mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition()); + } + + private List findComponentInstanceCapabilityProperties(String instanceId, String capabilityName, String capabilityType, String ownerId, Map propertiesMap) { + List capPropsList = null; + for (Entry capProp : propertiesMap.entrySet()) { + if (isBelongingPropertyMap(instanceId, capabilityName, capabilityType, ownerId, capProp)) { + Map capMap = capProp.getValue().getMapToscaDataDefinition(); + if (capMap != null && !capMap.isEmpty()) { + capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList()); + break; + } + } + } + if (capPropsList == null) { + capPropsList = new ArrayList<>(); + } + return capPropsList; + } + + private boolean isBelongingPropertyMap(String instanceId, String capabilityName, String capabilityType, String ownerId, Entry capProp) { + if (capProp != null) { + String[] path = capProp.getKey().split(ModelConverter.CAP_PROP_DELIM); + if (path.length < 4) { + log.debug("wrong key format for capabilty, key {}", capProp); + return false; + } + return path[path.length - 2].equals(capabilityType) && path[path.length - 1].equals(capabilityName) && path[1].equals(ownerId) && path[0].equals(instanceId); + } + return false; + } + + public StorageOperationStatus addPolicyToToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) { + fillPolicyDefinition(componentV, policyDefinition, counter); + return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID); + } + + public StorageOperationStatus addPoliciesToToscaElement(GraphVertex componentV, List policies) { + return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policies, JsonPresentationFields.UNIQUE_ID); + } + + public StorageOperationStatus updatePolicyOfToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition) { + return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID); + } + + public StorageOperationStatus updatePoliciesOfToscaElement(GraphVertex componentV, List policiesDefinitions) { + return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policiesDefinitions, JsonPresentationFields.UNIQUE_ID); + } + + public StorageOperationStatus removePolicyFromToscaElement(GraphVertex componentV, String policyId) { + return deleteToscaDataElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyId, JsonPresentationFields.UNIQUE_ID); + } + + public StorageOperationStatus updateGroupOfToscaElement(GraphVertex componentV, GroupDefinition groupDefinition) { + return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition, JsonPresentationFields.NAME); + } + + private void fillPolicyDefinition(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) { + String policyName = buildSubComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME), policyDefinition.getPolicyTypeName(), counter); + policyDefinition.setName(policyName); + policyDefinition.setInvariantName(policyName); + policyDefinition.setComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME)); + policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentV.getUniqueId(), policyName)); + policyDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); + policyDefinition.setPolicyUUID(UniqueIdBuilder.generateUUID()); + } + + public static String buildSubComponentName(String componentName, String subComponentTypeName, int counter) { + String normalizedComponentName = ValidationUtils.normalizeComponentInstanceName(componentName); + String typeSuffix = subComponentTypeName.substring(subComponentTypeName.lastIndexOf('.') + 1, subComponentTypeName.length()); + return normalizedComponentName + Constants.GROUP_POLICY_NAME_DELIMETER + typeSuffix + Constants.GROUP_POLICY_NAME_DELIMETER + counter; + } + + void revertNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) { + if (MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())) { + GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse) + .left() + .on(this::throwStorageException); + if (MapUtils.isNotEmpty(toscaElement.getComponentInstances())) { + toscaElement.getComponentInstances().values().forEach(i -> CapabilityRequirementNameResolver.revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), this::getOriginToscaElement)); + } + if (MapUtils.isNotEmpty(toscaElement.getGroups())) { + toscaElement.getGroups().values().forEach(g -> CapabilityRequirementNameResolver.revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), this::getOriginToscaElement)); + } + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, toscaElement.getCalculatedCapabilities()); + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, toscaElement.getCalculatedRequirements()); + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, toscaElement.getCalculatedCapabilitiesProperties()); + } + } + + public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) { + if (MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())) { + GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse) + .left() + .on(this::throwStorageException); + if (MapUtils.isNotEmpty(toscaElement.getComponentInstances())) { + toscaElement.getComponentInstances().values().forEach(i -> CapabilityRequirementNameResolver.updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), i.getNormalizedName(), this::getOriginToscaElement)); + } + if (MapUtils.isNotEmpty(toscaElement.getGroups())) { + toscaElement.getGroups().values().forEach(g -> CapabilityRequirementNameResolver.updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), g.getName(), this::getOriginToscaElement)); + } + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, toscaElement.getCalculatedCapabilities()); + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, toscaElement.getCalculatedRequirements()); + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, toscaElement.getCalculatedCapabilitiesProperties()); + } + } + + private ToscaElement getOriginToscaElement(ComponentInstanceDataDefinition instance) { + log.debug("#getOriginToscaElement - origin name: {}", instance.getComponentName()); + ToscaElementTypeEnum elementType = detectToscaType(instance.getOriginType()); + Either getOriginRes; + if (elementType == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE) { + getOriginRes = this.getToscaElement(CapabilityRequirementNameResolver.getActualComponentUid(instance), getFilter()); + + } else { + getOriginRes = nodeTypeOperation.getToscaElement(CapabilityRequirementNameResolver.getActualComponentUid(instance), getFilter()); + } + if (getOriginRes.isRight()) { + log.debug("Failed to get an origin component with uniqueId {}", CapabilityRequirementNameResolver.getActualComponentUid(instance)); + throw new StorageException(getOriginRes.right().value()); + } + return getOriginRes.left().value(); + } + + private ToscaElementTypeEnum detectToscaType(OriginTypeEnum originType) { + log.debug("#detectToscaType - type: {}", originType); + if (nodeTypeSet.contains(originType)){ + return ToscaElementTypeEnum.NODE_TYPE; + } else { + return ToscaElementTypeEnum.TOPOLOGY_TEMPLATE; + } + } + + private ComponentParametersView getFilter() { + ComponentParametersView filter = new ComponentParametersView(); + filter.setIgnoreCapabilities(false); + filter.setIgnoreCapabiltyProperties(false); + filter.setIgnoreRequirements(false); + return filter; + } + public void updateCapReqPropertiesOwnerId(String componentId, TopologyTemplate toscaElement) { + GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse) + .left().on(this::throwStorageException); + updateCapOwnerId(toscaElement, componentId); + updateReqOwnerId(toscaElement, componentId); + updatePropertiesOwnerId(toscaElement, componentId); + topologyTemplateOperation + + .updateFullToscaData(toscaElementV, EdgeLabelEnum.CAPABILITIES, + VertexTypeEnum.CAPABILITIES, toscaElement.getCapabilities()); + topologyTemplateOperation + .updateFullToscaData(toscaElementV, EdgeLabelEnum.REQUIREMENTS, + VertexTypeEnum.REQUIREMENTS, toscaElement.getRequirements()); + topologyTemplateOperation + .updateFullToscaData(toscaElementV, EdgeLabelEnum.PROPERTIES, + VertexTypeEnum.PROPERTIES, toscaElement.getProperties()); + } + + private void updateCapOwnerId(ToscaElement toscaElement, String ownerId) { + if(MapUtils.isNotEmpty(toscaElement.getCapabilities())) { + toscaElement.getCapabilities().values().stream().flatMap(listCapDef -> listCapDef.getListToscaDataDefinition().stream()) + .forEach(capabilityDefinition -> capabilityDefinition.setOwnerId(ownerId)); + } + } + + private void updateReqOwnerId(ToscaElement toscaElement, String ownerId) { + if(MapUtils.isNotEmpty(toscaElement.getRequirements())) { + toscaElement.getRequirements().values().stream().flatMap(listReqDef -> listReqDef.getListToscaDataDefinition().stream()) + .forEach(requirementDefinition -> requirementDefinition.setOwnerId(ownerId)); + } + } + + private void updatePropertiesOwnerId(ToscaElement toscaElement, String ownerId) { + Map properties = toscaElement.getProperties(); + if(MapUtils.isNotEmpty(properties)) { + properties.values().forEach(propertyDataDefinition -> propertyDataDefinition.setParentUniqueId(ownerId)); + } + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaDataOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaDataOperation.java new file mode 100644 index 0000000000..1501b79ca5 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaDataOperation.java @@ -0,0 +1,25 @@ +/*- + * ============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.jsonjanusgraph.operations; + +@org.springframework.stereotype.Component("tosca-data-operation") +public class ToscaDataOperation extends BaseOperation { +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementLifecycleOperation.java new file mode 100644 index 0000000000..771620d758 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementLifecycleOperation.java @@ -0,0 +1,1636 @@ +/*- + * ============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.jsonjanusgraph.operations; + +import org.janusgraph.core.JanusGraphVertex; +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; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; +import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.util.*; +import java.util.stream.Collectors; + +@org.springframework.stereotype.Component("tosca-element-lifecycle-operation") + +/** + * Allows to perform lifecycle operations: checkin, checkout, submit for testing, start certification and certification process for tosca element + */ +public class ToscaElementLifecycleOperation extends BaseOperation { + + private static final String FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS = "Failed to delete last state edge. Status is {}. "; + private static final String FAILED_TO_GET_VERTICES = "Failed to get vertices by id {}. Status is {}. "; + public static final String VERSION_DELIMITER = "."; + public static final String VERSION_DELIMITER_REGEXP = "\\."; + + private static final Logger log = Logger.getLogger(ToscaElementLifecycleOperation.class); + + /** + * Performs changing a lifecycle state of tosca element from "checked out" or "ready for certification" to "checked in" + * + * @param currState + * @param toscaElementId + * @param modifierId + * @param ownerId + * @return + */ + public Either checkinToscaELement(LifecycleStateEnum currState, String toscaElementId, String modifierId, String ownerId) { + Either updateResult = null; + Either result = null; + Map vertices = null; + ToscaElementOperation operation; + try { + Either, JanusGraphOperationStatus> getVerticesRes = janusGraphDao + .getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckin(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + updateResult = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVerticesRes.right().value())); + } else { + vertices = getVerticesRes.left().value(); + updateResult = checkinToscaELement(currState, vertices.get(toscaElementId), vertices.get(ownerId), vertices.get(modifierId), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + } + if (updateResult.isLeft()) { + operation = getToscaElementOperation(vertices.get(toscaElementId).getLabel()); + result = operation.getToscaElement(updateResult.left().value().getUniqueId()); + if (result.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated tosca element {}. Status is {}", toscaElementId, result.right().value()); + } + } else { + result = Either.right(updateResult.right().value()); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during checkin of tosca element {}. {} ", toscaElementId, e.getMessage()); + } + return result; + } + + /** + * Returns vertex presenting owner of tosca element specified by uniqueId + * + * @param toscaElementId + * @return + */ + public Either getToscaElementOwner(String toscaElementId) { + Either result = null; + GraphVertex toscaElement = null; + Either getToscaElementRes = janusGraphDao + .getVertexById(toscaElementId, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getToscaElementRes.right().value())); + } + if (result == null) { + toscaElement = getToscaElementRes.left().value(); + Iterator vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name()); + if (vertices == null || !vertices.hasNext()) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } else { + result = Either.left(convertToUser(vertices.next())); + } + } + return result; + } + + /** + * Returns vertex presenting owner of tosca element specified by uniqueId + * + * @param toscaElement + * @return + */ + public Either getToscaElementOwner(GraphVertex toscaElement) { + Either result = null; + Iterator vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name()); + if (vertices == null || !vertices.hasNext()) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } else { + result = Either.left(convertToUser(vertices.next())); + } + return result; + } + + /** + * Performs checkout of a tosca element + * + * @param toscaElementId + * @param modifierId + * @param ownerId + * @return + */ + public Either checkoutToscaElement(String toscaElementId, String modifierId, String ownerId) { + Either result = null; + Map vertices = null; + try { + Either, JanusGraphOperationStatus> getVerticesRes = janusGraphDao + .getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckout(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVerticesRes.right().value())); + } + if (result == null) { + vertices = getVerticesRes.left().value(); + // update previous component if not certified + StorageOperationStatus status = updatePreviousVersion(vertices.get(toscaElementId), vertices.get(ownerId)); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update vertex with id {} . Status is {}. ", status); + result = Either.right(status); + } + } + if (result == null) { + result = cloneToscaElementForCheckout(vertices.get(toscaElementId), vertices.get(modifierId)); + if (result.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to checkout tosca element {}. Status is {} ", toscaElementId, result.right().value()); + } + + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during checkout tosca element {}. {}", toscaElementId, e.getMessage()); + } + return result; + } + + /** + * Performs undo checkout for tosca element + * + * @param toscaElementId + * @return + */ + public Either undoCheckout(String toscaElementId) { + Either result = null; + Either getToscaElementRes = null; + Iterator nextVersionComponentIter = null; + ToscaElementOperation operation; + Vertex preVersionVertex = null; + try { + getToscaElementRes = janusGraphDao.getVertexById(toscaElementId, JsonParseFlagEnum.ParseMetadata); + if (getToscaElementRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getToscaElementRes.right().value())); + } + GraphVertex currVersionV = getToscaElementRes.left().value(); + if (result == null && hasPreviousVersion(currVersionV)) { + // find previous version + nextVersionComponentIter = currVersionV.getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name()); + if (nextVersionComponentIter == null || !nextVersionComponentIter.hasNext()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch previous version of tosca element with name {}. ", currVersionV.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString()); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + if (result == null) { + preVersionVertex = nextVersionComponentIter.next().outVertex(); + StorageOperationStatus updateOldResourceResult = updateOldToscaElementBeforeUndoCheckout(preVersionVertex); + if (updateOldResourceResult != StorageOperationStatus.OK) { + result = Either.right(updateOldResourceResult); + } + } + } + if (result == null) { + StorageOperationStatus updateCatalogRes = updateEdgeToCatalogRootByUndoCheckout((JanusGraphVertex) preVersionVertex, currVersionV); + if (updateCatalogRes != StorageOperationStatus.OK) { + return Either.right(updateCatalogRes); + } + operation = getToscaElementOperation(currVersionV.getLabel()); + result = operation.deleteToscaElement(currVersionV); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during undo checkout tosca element {}. {}", toscaElementId, e.getMessage()); + } + return result; + } + + private boolean hasPreviousVersion(GraphVertex toscaElementVertex) { + boolean hasPreviousVersion = true; + String version = (String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION); + if (StringUtils.isEmpty(version) || "0.1".equals(version)) + hasPreviousVersion = false; + return hasPreviousVersion; + } + + /** + * Performs request certification for tosca element + * + * @param toscaElementId + * @param modifierId + * @param ownerId + * @return + */ + public Either requestCertificationToscaElement(String toscaElementId, String modifierId, String ownerId) { + Either resultUpdate = null; + Either result = null; + GraphVertex toscaElement = null; + GraphVertex modifier = null; + GraphVertex owner; + try { + Either, JanusGraphOperationStatus> getVerticesRes = janusGraphDao + .getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVerticesRes.right().value())); + } + if (result == null) { + toscaElement = getVerticesRes.left().value().get(toscaElementId); + modifier = getVerticesRes.left().value().get(modifierId); + owner = getVerticesRes.left().value().get(ownerId); + + StorageOperationStatus status = handleRelationsUponRequestForCertification(toscaElement, modifier, owner); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); + } + } + if (result == null) { + LifecycleStateEnum nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION; + + toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); + toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + + resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); + if (resultUpdate.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); + result = Either.right(resultUpdate.right().value()); + } + } + if (result == null) { + ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); + result = operation.getToscaElement(toscaElement.getUniqueId()); + } + return result; + + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage()); + } + return result; + } + + /** + * Starts certification of tosca element + * + * @param toscaElementId + * @param modifierId + * @param ownerId + * @return + */ + public Either startCertificationToscaElement(String toscaElementId, String modifierId, String ownerId) { + Either result = null; + Either resultUpdate = null; + GraphVertex toscaElement = null; + GraphVertex modifier = null; + GraphVertex owner; + try { + Either, JanusGraphOperationStatus> getVerticesRes = janusGraphDao + .getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVerticesRes.right().value())); + } + if (result == null) { + toscaElement = getVerticesRes.left().value().get(toscaElementId); + modifier = getVerticesRes.left().value().get(modifierId); + owner = getVerticesRes.left().value().get(ownerId); + + StorageOperationStatus status = handleRelationsUponCertification(toscaElement, modifier, owner); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations during certification of tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); + } + } + if (result == null) { + LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFICATION_IN_PROGRESS; + + toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); + toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + + resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); + if (resultUpdate.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Couldn't set lifecycle for component {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); + result = Either.right(resultUpdate.right().value()); + } + } + if (result == null) { + ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); + result = operation.getToscaElement(toscaElement.getUniqueId()); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during start certification tosca element {}. {}", toscaElementId, e.getMessage()); + } + return result; + } + + public Either certifyToscaElement(String toscaElementId, String modifierId, String ownerId) { + Either result = null; + Either cloneRes = null; + GraphVertex toscaElement = null; + GraphVertex modifier = null; + GraphVertex certifiedToscaElement = null; + Integer majorVersion = null; + + StorageOperationStatus status; + try { + Either, JanusGraphOperationStatus> getVerticesRes = janusGraphDao + .getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVerticesRes.right().value())); + } + if (result == null) { + toscaElement = getVerticesRes.left().value().get(toscaElementId); + modifier = getVerticesRes.left().value().get(modifierId); + majorVersion = getMajorVersion((String) toscaElement.getMetadataProperty(GraphPropertyEnum.VERSION)); + status = handleRelationsOfPreviousToscaElementBeforeCertifying(toscaElement, modifier, majorVersion); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations of previous tosca element before certifying {}. Status is {}. ", toscaElement.getUniqueId(), status); + } + } + if (result == null) { + cloneRes = cloneToscaElementForCertify(toscaElement, modifier, majorVersion); + if (cloneRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element during certification. "); + result = Either.right(cloneRes.right().value()); + } + } + if (result == null) { + certifiedToscaElement = cloneRes.left().value(); + status = handleRelationsOfNewestCertifiedToscaElement(toscaElement, certifiedToscaElement); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations of newest certified tosca element {}. Status is {}. ", certifiedToscaElement.getUniqueId(), status); + } + } + if (result == null) { + return getToscaElementOperation(toscaElement.getLabel()).getToscaElement(certifiedToscaElement.getUniqueId()); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during certification tosca element {}. {}", toscaElementId, e.getMessage()); + } + return result; + } + + /** + * Deletes (marks as deleted) all tosca elements according received name and uuid + * + * @param vertexType + * @param componentType + * @param componentName + * @param uuid + * @return + */ + public Either deleteOldToscaElementVersions(VertexTypeEnum vertexType, ComponentTypeEnum componentType, String componentName, String uuid) { + + Either result = null; + ToscaElementOperation operation = getToscaElementOperation(componentType); + + try { + Map properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.UUID, uuid); + properties.put(GraphPropertyEnum.NAME, componentName); + Either, JanusGraphOperationStatus> getToscaElementsRes = janusGraphDao + .getByCriteria(vertexType, properties, JsonParseFlagEnum.ParseMetadata); + if (getToscaElementsRes.isRight()) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getToscaElementsRes.right().value())); + } + if (result == null) { + result = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value()); + } + if (result == null) { + result = Either.left(true); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage()); + } + return result; + } + + /** + * Performs cancelation or failure of certification for received tosca element + * + * @param toscaElementId + * @param modifierId + * @param ownerId + * @param nextState + * @return + */ + public Either cancelOrFailCertification(String toscaElementId, String modifierId, String ownerId, LifecycleStateEnum nextState) { + Either result = null; + StorageOperationStatus status; + ToscaElementOperation operation = null; + GraphVertex toscaElement = null; + GraphVertex modifier = null; + try { + Either, JanusGraphOperationStatus> getVerticesRes = janusGraphDao + .getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVerticesRes.right().value())); + } + if (result == null) { + toscaElement = getVerticesRes.left().value().get(toscaElementId); + modifier = getVerticesRes.left().value().get(modifierId); + operation = getToscaElementOperation(toscaElement.getLabel()); + toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + toscaElement.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifier.getUniqueId()); + toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); + + Either updateVertexRes = janusGraphDao.updateVertex(toscaElement); + if (updateVertexRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update vertex {} . Status is {}. ", toscaElementId, updateVertexRes.right().value()); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateVertexRes.right().value())); + } + } + if (result == null) { + // cancel certification process + status = handleRelationsUponCancelCertification(toscaElement, nextState); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations upon cancel certification {}. Status is {}. ", toscaElement.getUniqueId(), status); + } + } + if (result == null) { + // fail certification + status = handleRelationsUponFailCertification(toscaElement, nextState); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations upon fail certification {}. Status is {}. ", toscaElement.getUniqueId(), status); + } + } + if (result == null) { + result = operation.getToscaElement(toscaElementId); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during cancel or fail certification of tosca element {}. {}. ", toscaElementId, e.getMessage()); + } + return result; + } + + public Either findUser(String userId) { + return findUserVertex(userId); + } + + private Either markToscaElementsAsDeleted(ToscaElementOperation operation, List toscaElements) { + Either result = Either.left(true); + for (GraphVertex resourceToDelete : toscaElements) { + if (!((String) resourceToDelete.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())) { + Either deleteElementRes = operation.markComponentToDelete(resourceToDelete); + if (deleteElementRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete tosca element {}. Status is {}. ", resourceToDelete.getUniqueId(), deleteElementRes.right().value()); + result = Either.right(deleteElementRes.right().value()); + break; + } + } + } + return result; + } + + private StorageOperationStatus handleRelationsOfNewestCertifiedToscaElement(GraphVertex toscaElement, GraphVertex certifiedToscaElement) { + StorageOperationStatus result = null; + Edge foundEdge = null; + Iterator certReqUserEdgeIter = null; + // add rfc relation to preserve follower information + // get user of certification request + certReqUserEdgeIter = toscaElement.getVertex().edges(Direction.IN, GraphEdgeLabels.LAST_STATE.name()); + if (certReqUserEdgeIter == null || !certReqUserEdgeIter.hasNext()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. "); + result = StorageOperationStatus.NOT_FOUND; + } + if (result == null) { + JanusGraphOperationStatus + createVersionEdgeStatus = janusGraphDao + .createEdge(toscaElement, certifiedToscaElement, EdgeLabelEnum.VERSION, new HashMap<>()); + if (createVersionEdgeStatus != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create version edge from last element {} to new certified element {}. status=", toscaElement.getUniqueId(), certifiedToscaElement.getUniqueId(), + createVersionEdgeStatus); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createVersionEdgeStatus); + } + } + if (result == null) { + if (certReqUserEdgeIter!=null) { + while (certReqUserEdgeIter.hasNext()) { + Edge edge = certReqUserEdgeIter.next(); + if (((String) janusGraphDao.getProperty(edge, EdgePropertyEnum.STATE)).equals(LifecycleStateEnum.READY_FOR_CERTIFICATION.name())) { + foundEdge = edge; + break; + } + + } + } + if (foundEdge == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. "); + result = StorageOperationStatus.NOT_FOUND; + } + } + if (result == null) { + JanusGraphOperationStatus + createEdgeRes = janusGraphDao + .createEdge(foundEdge.outVertex(), certifiedToscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, foundEdge); + if (createEdgeRes != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create rfc relation for component {}. status=", certifiedToscaElement.getUniqueId(), createEdgeRes); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdgeRes); + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private StorageOperationStatus handleRelationsUponFailCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) { + StorageOperationStatus result = null; + JanusGraphOperationStatus status = null; + Edge originEdge; + Vertex user = null; + if (nextState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) { + // fail certification + // delete relation CERTIFICATION_IN_PROGRESS + Map properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + + Either deleteResult = janusGraphDao + .deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties); + if (deleteResult.isRight()) { + status = deleteResult.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", status); + result = StorageOperationStatus.INCONSISTENCY; + } + if (result == null) { + // delete relation READY_FOR_CERTIFICATION + properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION); + deleteResult = janusGraphDao + .deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); + if (deleteResult.isRight()) { + status = deleteResult.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS, status); + result = StorageOperationStatus.INCONSISTENCY; + } + } + if (result == null) { + // delete relation NOT_CERTIFIED_CHECKIN (in order to change to STATE) + properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + deleteResult = janusGraphDao + .deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); + if (deleteResult.isRight()) { + status = deleteResult.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS, status); + result = StorageOperationStatus.INCONSISTENCY; + } + } + if (result == null) { + // create new STATE relation NOT_CERTIFIED_CHECKIN + originEdge = deleteResult.left().value(); + user = originEdge.outVertex(); + status = janusGraphDao + .createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge); + if (status != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status); + result = StorageOperationStatus.INCONSISTENCY; + } + } + if (result == null) { + // delete relation LAST_MODIFIER (in order to change tester to designer) + deleteResult = janusGraphDao + .deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); + if (status != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status); + result = StorageOperationStatus.INCONSISTENCY; + } + } + if (result == null) { + // create new LAST_MODIFIER relation + originEdge = deleteResult.left().value(); + status = janusGraphDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.LAST_MODIFIER, originEdge); + if (status != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status); + result = StorageOperationStatus.INCONSISTENCY; + } + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private StorageOperationStatus handleRelationsUponCancelCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) { + StorageOperationStatus result = null; + Edge originEdge; + if (nextState == LifecycleStateEnum.READY_FOR_CERTIFICATION) { + // delete relation CERTIFICATION_IN_PROGRESS + Map properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either deleteResult = janusGraphDao + .deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties); + + if (deleteResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", deleteResult.right().value()); + result = StorageOperationStatus.INCONSISTENCY; + } + if (result == null) { + // delete relation READY_FOR_CERTIFICATION (LAST_STATE) + properties.put(GraphPropertyEnum.STATE, nextState); + deleteResult = janusGraphDao + .deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); + + if (deleteResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS, deleteResult.right().value()); + result = StorageOperationStatus.INCONSISTENCY; + } + } + if (result == null) { + // create relation READY_FOR_CERTIFICATION (STATE) + originEdge = deleteResult.left().value(); + JanusGraphOperationStatus + status = janusGraphDao + .createEdge(originEdge.outVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge); + if (status != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status); + result = StorageOperationStatus.INCONSISTENCY; + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + } + return result; + } + + private StorageOperationStatus handleRelationsOfPreviousToscaElementBeforeCertifying(GraphVertex toscaElement, GraphVertex modifier, Integer majorVersion) { + StorageOperationStatus result = null; + if (majorVersion > 0) { + Either findRes = findLastCertifiedToscaElementVertex(toscaElement); + if (findRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch last certified tosca element {} . Status is {}. ", toscaElement.getMetadataProperty(GraphPropertyEnum.NAME), findRes.right().value()); + result = findRes.right().value(); + } + if (result == null) { + Vertex lastCertifiedVertex = findRes.left().value(); + Map properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, false); + JanusGraphOperationStatus status = janusGraphDao + .updateVertexMetadataPropertiesWithJson(lastCertifiedVertex, properties); + if (status != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set highest version of tosca element {} to [{}]. Status is {}", toscaElement.getUniqueId(), false, status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + // remove previous certified version from the catalog + GraphVertex lastCertifiedV = new GraphVertex(); + lastCertifiedV.setVertex((JanusGraphVertex) lastCertifiedVertex); + lastCertifiedV.setUniqueId((String) janusGraphDao + .getProperty((JanusGraphVertex) lastCertifiedVertex, GraphPropertyEnum.UNIQUE_ID.getProperty())); + StorageOperationStatus res = updateEdgeToCatalogRoot(null, lastCertifiedV); + if (res != StorageOperationStatus.OK) { + return res; + } + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private StorageOperationStatus handleRelationsUponRequestForCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { + JanusGraphOperationStatus status; + StorageOperationStatus result = null; + + if (((String) toscaElement.getMetadataProperty(GraphPropertyEnum.STATE)).equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + // remove CHECKOUT relation + Either deleteRes = janusGraphDao + .deleteEdge(owner, toscaElement, EdgeLabelEnum.STATE); + if (deleteRes.isRight()) { + status = deleteRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete edge. Status is {}. ", status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + if (result == null) { + // create CHECKIN relation + Map properties = new EnumMap<>(EdgePropertyEnum.class); + properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + status = janusGraphDao + .createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, properties); + if (status != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + } + } else { + status = janusGraphDao + .replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); + if (status != JanusGraphOperationStatus.OK) { + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + } + if (result == null) { + // create RFC relation + Map properties = new EnumMap<>(EdgePropertyEnum.class); + properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION); + status = janusGraphDao + .createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, properties); + if (status != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private StorageOperationStatus handleRelationsUponCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { + + StorageOperationStatus result = null; + JanusGraphOperationStatus status = janusGraphDao + .replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); + if (status != JanusGraphOperationStatus.OK) { + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + if (result == null) { + Map properties = new EnumMap<>(EdgePropertyEnum.class); + properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + status = janusGraphDao + .createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties); + if (status != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + } + if (result == null) { + Either updateRelationsRes = updateLastModifierEdge(toscaElement, owner, modifier); + if (updateRelationsRes.isRight()) { + result = updateRelationsRes.right().value(); + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private Either findLastCertifiedToscaElementVertex(GraphVertex toscaElement) { + return findLastCertifiedToscaElementVertexRecursively(toscaElement.getVertex()); + } + + private Either findLastCertifiedToscaElementVertexRecursively(Vertex vertex) { + if (isCertifiedVersion((String) vertex.property(GraphPropertyEnum.VERSION.getProperty()).value())) { + return Either.left(vertex); + } + Iterator edgeIter = vertex.edges(Direction.IN, EdgeLabelEnum.VERSION.name()); + if (!edgeIter.hasNext()) { + return Either.right(StorageOperationStatus.NOT_FOUND); + } + return findLastCertifiedToscaElementVertexRecursively(edgeIter.next().outVertex()); + } + + private boolean isCertifiedVersion(String version) { + String[] versionParts = version.split(VERSION_DELIMITER_REGEXP); + if (Integer.parseInt(versionParts[0]) > 0 && Integer.parseInt(versionParts[1]) == 0) { + return true; + } + return false; + } + + private StorageOperationStatus updateOldToscaElementBeforeUndoCheckout(Vertex previousVersionToscaElement) { + + StorageOperationStatus result = StorageOperationStatus.OK; + String previousVersion = (String) previousVersionToscaElement.property(GraphPropertyEnum.VERSION.getProperty()).value(); + if (!previousVersion.endsWith(".0")) { + try { + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update vertex of previous version of tosca element", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty())); + + Map propertiesToUpdate = new HashMap<>(); + propertiesToUpdate.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true); + Map jsonMetadataMap = JsonParserUtils.toMap((String) previousVersionToscaElement.property(GraphPropertyEnum.METADATA.getProperty()).value()); + jsonMetadataMap.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true); + propertiesToUpdate.put(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.toJson(jsonMetadataMap)); + + janusGraphDao.setVertexProperties(previousVersionToscaElement, propertiesToUpdate); + + Iterator edgesIter = previousVersionToscaElement.edges(Direction.IN, EdgeLabelEnum.LAST_STATE.name()); + if (!edgesIter.hasNext()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch last modifier vertex for tosca element {}. ", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty())); + result = StorageOperationStatus.NOT_FOUND; + } else { + Edge lastStateEdge = edgesIter.next(); + Vertex lastModifier = lastStateEdge.outVertex(); + JanusGraphOperationStatus replaceRes = janusGraphDao + .replaceEdgeLabel(lastModifier, previousVersionToscaElement, lastStateEdge, EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE); + if (replaceRes != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to replace label from {} to {}. status = {}", EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE, replaceRes); + result = StorageOperationStatus.INCONSISTENCY; + if (replaceRes != JanusGraphOperationStatus.INVALID_ID) { + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(replaceRes); + } + } + + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during update previous tosca element {} before undo checkout. {} ", e.getMessage()); + } + } + return result; + } + + private StorageOperationStatus updatePreviousVersion(GraphVertex toscaElementVertex, GraphVertex ownerVertex) { + StorageOperationStatus result = null; + String ownerId = (String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID); + String toscaElementId = toscaElementVertex.getUniqueId(); + if (!toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())) { + toscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, false); + Either updateVertexRes = janusGraphDao.updateVertex(toscaElementVertex); + if (updateVertexRes.isRight()) { + JanusGraphOperationStatus titatStatus = updateVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update tosca element vertex {}. Status is {}", toscaElementVertex.getUniqueId(), titatStatus); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(titatStatus); + } + Either deleteEdgeRes = null; + if (result == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to replace edge with label {} to label {} from {} to {}. ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId); + + deleteEdgeRes = janusGraphDao + .deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE); + if (deleteEdgeRes.isRight()) { + JanusGraphOperationStatus janusGraphStatus = deleteEdgeRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete edge with label {} from {} to {}. Status is {} ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId, janusGraphStatus); + if (!janusGraphStatus.equals(JanusGraphOperationStatus.INVALID_ID)) { + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphStatus); + } else { + result = StorageOperationStatus.INCONSISTENCY; + } + } + } + if (result == null) { + JanusGraphOperationStatus + createEdgeRes = janusGraphDao + .createEdge(ownerVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_STATE, deleteEdgeRes.left().value()); + if (createEdgeRes != JanusGraphOperationStatus.OK) { + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdgeRes); + } + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private Either cloneToscaElementForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) { + + Either result = null; + Either cloneResult = null; + ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel()); + // check if component with the next version doesn't exist. + Iterator nextVersionComponentIter = toscaElementVertex.getVertex().edges(Direction.OUT, EdgeLabelEnum.VERSION.name()); + if (nextVersionComponentIter != null && nextVersionComponentIter.hasNext()) { + Vertex nextVersionVertex = nextVersionComponentIter.next().inVertex(); + String fetchedVersion = (String) nextVersionVertex.property(GraphPropertyEnum.VERSION.getProperty()).value(); + String fetchedName = (String) nextVersionVertex.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to checkout component {} with version {}. The component with name {} and version {} was fetched from graph as existing following version. ", + toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString(), toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION).toString(), fetchedName, fetchedVersion); + result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS); + } + if (result == null) { + toscaElementVertex.getOrSetDefaultInstantiationTypeForToscaElementJson(); + cloneResult = operation.cloneToscaElement(toscaElementVertex, cloneGraphVertexForCheckout(toscaElementVertex, modifierVertex), modifierVertex); + if (cloneResult.isRight()) { + result = Either.right(cloneResult.right().value()); + } + } + GraphVertex clonedVertex = null; + if (result == null) { + clonedVertex = cloneResult.left().value(); + JanusGraphOperationStatus + status = janusGraphDao + .createEdge(toscaElementVertex.getVertex(), cloneResult.left().value().getVertex(), EdgeLabelEnum.VERSION, new HashMap<>()); + if (status != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION, + toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), cloneResult.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (result == null) { + Boolean isHighest = (Boolean) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); + GraphVertex prevVersionInCatalog = (isHighest != null && isHighest) ? null : toscaElementVertex; + StorageOperationStatus updateCatalogRes = updateEdgeToCatalogRoot(clonedVertex, prevVersionInCatalog); + if (updateCatalogRes != StorageOperationStatus.OK) { + return Either.right(updateCatalogRes); + } + result = operation.getToscaElement(cloneResult.left().value().getUniqueId()); + if (result.isRight()) { + return result; + } + ToscaElement toscaElement = result.left().value(); + if (toscaElement.getToscaType() == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE) { + result = handleFixTopologyTemplate(toscaElementVertex, result, operation, clonedVertex, toscaElement); + } + } + + return result; + } + + private Either handleFixTopologyTemplate(GraphVertex toscaElementVertex, Either result, ToscaElementOperation operation, GraphVertex clonedVertex, + ToscaElement toscaElement) { + TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; + Map instInputs = topologyTemplate.getInstInputs(); + Map instGroups = topologyTemplate.getInstGroups(); + Map instArtifactsMap = topologyTemplate.getInstanceArtifacts(); + Map origCompMap = new HashMap<>(); + if (instInputs == null) { + instInputs = new HashMap<>(); + } + if (instGroups == null) { + instGroups = new HashMap<>(); + } + if (instArtifactsMap == null) { + instArtifactsMap = new HashMap<>(); + } + Map instancesMap = topologyTemplate.getComponentInstances(); + boolean isAddInstGroup = instGroups == null || instGroups.isEmpty(); + boolean needUpdateComposition = false; + + if (instancesMap != null && !instancesMap.isEmpty()) { + for (ComponentInstanceDataDefinition vfInst : instancesMap.values()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "vfInst name is {} . OriginType {}. ", vfInst.getName(), vfInst.getOriginType()); + if (vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) { + collectInstanceInputAndGroups(instInputs, instGroups, instArtifactsMap, origCompMap, isAddInstGroup, vfInst, clonedVertex); + } + needUpdateComposition = needUpdateComposition || fixToscaComponentName(vfInst, origCompMap); + if (needUpdateComposition) { + instancesMap.put(vfInst.getUniqueId(), vfInst); + } + } + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before add to graph instInputs {} instGroups {} needUpdateComposition {}", instInputs, instGroups, needUpdateComposition); + if (!instInputs.isEmpty()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before add inst inputs {} ", instInputs == null ? 0 : instInputs.size()); + GraphVertex toscaDataVertex = null; + Either instInpVertexEither = janusGraphDao + .getChildVertex(toscaElementVertex, EdgeLabelEnum.INST_INPUTS, JsonParseFlagEnum.ParseJson); + if (instInpVertexEither.isLeft()) { + toscaDataVertex = instInpVertexEither.left().value(); + } + + StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, toscaDataVertex, instInputs); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update instance inputs . Status is {}. ", status); + result = Either.right(status); + return result; + } + + } + if (!instGroups.isEmpty()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before add inst groups {} ", instGroups == null ? 0 : instGroups.size()); + GraphVertex toscaDataVertex = null; + Either instGrVertexEither = janusGraphDao + .getChildVertex(toscaElementVertex, EdgeLabelEnum.INST_GROUPS, JsonParseFlagEnum.ParseJson); + if (instGrVertexEither.isLeft()) { + toscaDataVertex = instGrVertexEither.left().value(); + } + + StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, toscaDataVertex, instGroups); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update instance group . Status is {}. ", status); + result = Either.right(status); + return result; + } + + } + if (needUpdateComposition) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before update Instances "); + Map jsonComposition = (Map) clonedVertex.getJson(); + CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + compositionDataDefinition.setComponentInstances(instancesMap); + Either updateElement = janusGraphDao.updateVertex(clonedVertex); + if (updateElement.isRight()) { + JanusGraphOperationStatus status = updateElement.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update instances on metadata vertex . Status is {}. ", status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + return result; + } + } + + result = operation.getToscaElement(clonedVertex.getUniqueId()); + + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "RI map empty on component {}", toscaElement.getUniqueId()); + } + return result; + } + + // TODO remove after jsonModelMigration + public boolean resolveToscaComponentName(ComponentInstanceDataDefinition vfInst, Map origCompMap) { + return fixToscaComponentName(vfInst, origCompMap); + } + + private boolean fixToscaComponentName(ComponentInstanceDataDefinition vfInst, Map origCompMap) { + if (vfInst.getToscaComponentName() == null || vfInst.getToscaComponentName().isEmpty()) { + String ciUid = vfInst.getUniqueId(); + String origCompUid = vfInst.getComponentUid(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "fixToscaComponentName:: Ri id {} . origin component id is {}. type is{} ", ciUid, origCompUid, vfInst.getOriginType()); + ToscaElement origComp = null; + if (!origCompMap.containsKey(origCompUid)) { + Either origCompEither; + if (vfInst.getOriginType() == null || vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) { + origCompEither = topologyTemplateOperation.getToscaElement(origCompUid); + } else { + origCompEither = nodeTypeOperation.getToscaElement(origCompUid); + } + if (origCompEither.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value()); + return false; + } + origComp = origCompEither.left().value(); + origCompMap.put(origCompUid, origComp); + } else { + origComp = origCompMap.get(origCompUid); + } + String toscaName = (String) origComp.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Origin component id is {}. toscaName {}", origCompUid, toscaName); + vfInst.setToscaComponentName(toscaName); + return true; + } + return false; + } + + private void collectInstanceInputAndGroups(Map instInputs, Map instGroups, Map instArtifactsMap, Map origCompMap, + boolean isAddInstGroup, ComponentInstanceDataDefinition vfInst, GraphVertex clonedVertex) { + String ciUid = vfInst.getUniqueId(); + String origCompUid = vfInst.getComponentUid(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "collectInstanceInputAndGroups:: Ri id {} . origin component id is {}. ", ciUid, origCompUid); + TopologyTemplate origComp = null; + if (!origCompMap.containsKey(origCompUid)) { + Either origCompEither = topologyTemplateOperation.getToscaElement(origCompUid); + if (origCompEither.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value()); + return; + } + origComp = (TopologyTemplate) origCompEither.left().value(); + origCompMap.put(origCompUid, origComp); + } else { + origComp = (TopologyTemplate) origCompMap.get(origCompUid); + } + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Orig component {}. ", origComp.getUniqueId()); + + Map origInputs = origComp.getInputs(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Orig component inputs size {}. ", origInputs == null ? 0 : origInputs.size()); + if (origInputs != null) { + if (!instInputs.containsKey(ciUid)) { + MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(origInputs); + instInputs.put(ciUid, instProperties); + } else { + + MapPropertiesDataDefinition instInputMap = instInputs.get(ciUid); + Map instProp = instInputMap.getMapToscaDataDefinition(); + origInputs.forEach((propName, propMap) -> { + if (!instProp.containsKey(propName)) { + instProp.put(propName, propMap); + } + }); + } + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "ComponentInstanseInputs {}. ", instInputs.get(ciUid)); + } + + if (isAddInstGroup) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before create group instance. "); + List filteredGroups = null; + + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check vf groups before filter. Size is {} ", filteredGroups == null ? 0 : filteredGroups.size()); + if (origComp.getGroups() != null && !origComp.getGroups().isEmpty()) { + filteredGroups = origComp.getGroups().values().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList()); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check vf groups . Size is {} ", filteredGroups == null ? 0 : filteredGroups.size()); + } + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check vf groups after filter. Size is {} ", filteredGroups == null ? 0 : filteredGroups.size()); + if (CollectionUtils.isNotEmpty(filteredGroups)) { + MapArtifactDataDefinition instArifacts = null; + if (!instArtifactsMap.containsKey(ciUid)) { + + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "istance artifacts not found "); + + Map deploymentArtifacts = origComp.getDeploymentArtifacts(); + + instArifacts = new MapArtifactDataDefinition(deploymentArtifacts); + addToscaDataDeepElementsBlockToToscaElement(clonedVertex, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArifacts, ciUid); + + instArtifactsMap.put(ciUid, instArifacts); + + } else { + instArifacts = instArtifactsMap.get(ciUid); + } + + if (instArifacts != null) { + Map instDeplArtifMap = instArifacts.getMapToscaDataDefinition(); + + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check group dep artifacts. Size is {} ", instDeplArtifMap == null ? 0 : instDeplArtifMap.values().size()); + Map groupInstanceToCreate = new HashMap<>(); + for (GroupDataDefinition group : filteredGroups) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "create new groupInstance {} ", group.getName()); + GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition(group, vfInst, instDeplArtifMap); + List artifactsUid = new ArrayList<>(); + List artifactsId = new ArrayList<>(); + if (instDeplArtifMap!=null) { + for (ArtifactDataDefinition artifact : instDeplArtifMap.values()) { + Optional op = group.getArtifacts().stream().filter(p -> p.equals(artifact.getGeneratedFromId())).findAny(); + if (op.isPresent()) { + artifactsUid.add(artifact.getArtifactUUID()); + artifactsId.add(artifact.getUniqueId()); + + } + } + } + groupInstance.setGroupInstanceArtifacts(artifactsId); + groupInstance.setGroupInstanceArtifactsUuid(artifactsUid); + groupInstanceToCreate.put(groupInstance.getName(), groupInstance); + } + if (MapUtils.isNotEmpty(groupInstanceToCreate)) { + instGroups.put(vfInst.getUniqueId(), new MapGroupsDataDefinition(groupInstanceToCreate)); + + } + } + } + } + } + + private GraphVertex cloneGraphVertexForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) { + GraphVertex nextVersionToscaElementVertex = new GraphVertex(); + String uniqueId = UniqueIdBuilder.buildComponentUniqueId(); + Map metadataProperties = new HashMap<>(toscaElementVertex.getMetadataProperties()); + nextVersionToscaElementVertex.setMetadataProperties(metadataProperties); + nextVersionToscaElementVertex.setUniqueId(uniqueId); + nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel()); + nextVersionToscaElementVertex.setType(toscaElementVertex.getType()); + + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId); + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name()); + String nextVersion = getNextVersion((String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION)); + if (isFirstCheckoutAfterCertification(nextVersion)) { + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UUID, IdBuilderUtils.generateUUID()); + } + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, nextVersion); + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())) { + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + } + if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) { + nextVersionToscaElementVertex.setMetadataJson(new HashMap<>(toscaElementVertex.getMetadataJson())); + nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties(); + } + long currTime = System.currentTimeMillis(); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CREATION_DATE, currTime); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currTime); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId()); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId()); + if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE) { + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CONFORMANCE_LEVEL, ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel()); + } + + if (!MapUtils.isEmpty(toscaElementVertex.getJson())) { + nextVersionToscaElementVertex.setJson(new HashMap(toscaElementVertex.getJson())); + } + return nextVersionToscaElementVertex; + } + + private Either cloneToscaElementForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) { + Either result; + Either, StorageOperationStatus> deleteResult = null; + GraphVertex clonedToscaElement = null; + result = getToscaElementOperation(toscaElementVertex.getLabel()).cloneToscaElement(toscaElementVertex, cloneGraphVertexForCertify(toscaElementVertex, modifierVertex, majorVersion), modifierVertex); + if (result.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element {} for certification. Sattus is {}. ", toscaElementVertex.getUniqueId(), result.right().value()); + } else { + clonedToscaElement = result.left().value(); + StorageOperationStatus updateEdgeToCatalog = updateEdgeToCatalogRoot(clonedToscaElement, toscaElementVertex); + if (updateEdgeToCatalog != StorageOperationStatus.OK) { + return Either.right(updateEdgeToCatalog); + } + deleteResult = deleteAllPreviousNotCertifiedVersions(toscaElementVertex); + if (deleteResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete all previous npt certified versions of tosca element {}. Status is {}. ", toscaElementVertex.getUniqueId(), deleteResult.right().value()); + result = Either.right(deleteResult.right().value()); + } + } + if (result.isLeft()) { + result = handlePreviousVersionRelation(clonedToscaElement, deleteResult.left().value(), majorVersion); + } + return result; + } + + private Either handlePreviousVersionRelation(GraphVertex clonedToscaElement, List deletedVersions, Integer majorVersion) { + Either result = null; + Vertex previousCertifiedToscaElement = null; + if (majorVersion > 0) { + List firstMinorVersionVertex = deletedVersions.stream().filter(gv -> getMinorVersion((String) gv.getMetadataProperty(GraphPropertyEnum.VERSION)) == 1).collect(Collectors.toList()); + + if (CollectionUtils.isEmpty(firstMinorVersionVertex)) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } else { + previousCertifiedToscaElement = getPreviousCertifiedToscaElement(firstMinorVersionVertex.get(0)); + if (previousCertifiedToscaElement == null) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + if (result == null) { + JanusGraphOperationStatus + status = janusGraphDao + .createEdge(previousCertifiedToscaElement, clonedToscaElement.getVertex(), EdgeLabelEnum.VERSION, new HashMap<>()); + if (status != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION, + previousCertifiedToscaElement.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), clonedToscaElement.getUniqueId(), status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + + } + if (result == null) { + result = Either.left(clonedToscaElement); + } + return result; + } + + private Vertex getPreviousCertifiedToscaElement(GraphVertex graphVertex) { + + Iterator edges = graphVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name()); + if (edges.hasNext()) { + return edges.next().outVertex(); + } + return null; + } + + private Either, StorageOperationStatus> deleteAllPreviousNotCertifiedVersions(GraphVertex toscaElementVertex) { + Either, StorageOperationStatus> result = null; + + ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel()); + List previosVersions = null; + Object uuid = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.UUID); + Object componentName = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NAME); + try { + Map properties = new HashMap<>(); + properties.put(GraphPropertyEnum.UUID, uuid); + properties.put(GraphPropertyEnum.NAME, componentName); + Either, JanusGraphOperationStatus> getToscaElementsRes = janusGraphDao + .getByCriteria(toscaElementVertex.getLabel(), properties, JsonParseFlagEnum.ParseMetadata); + if (getToscaElementsRes.isRight()) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getToscaElementsRes.right().value())); + } + if (result == null) { + previosVersions = getToscaElementsRes.left().value(); + Either deleteResult = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value()); + if (deleteResult.isRight()) { + result = Either.right(deleteResult.right().value()); + } + } + if (result == null) { + result = Either.left(previosVersions); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage()); + } + return result; + } + + private GraphVertex cloneGraphVertexForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) { + + GraphVertex nextVersionToscaElementVertex = new GraphVertex(); + String uniqueId = IdBuilderUtils.generateUniqueId(); + Map metadataProperties = new EnumMap<>(toscaElementVertex.getMetadataProperties()); + nextVersionToscaElementVertex.setMetadataProperties(metadataProperties); + nextVersionToscaElementVertex.setUniqueId(uniqueId); + nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel()); + nextVersionToscaElementVertex.setType(toscaElementVertex.getType()); + + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId); + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name()); + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, (majorVersion + 1) + VERSION_DELIMITER + "0"); + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CREATION_DATE, System.currentTimeMillis()); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, null); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId()); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId()); + + if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED)) { + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + } + if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) { + nextVersionToscaElementVertex.setMetadataJson(new HashMap<>(toscaElementVertex.getMetadataJson())); + nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties(); + } + if (!MapUtils.isEmpty(toscaElementVertex.getJson())) { + nextVersionToscaElementVertex.setJson(new HashMap(toscaElementVertex.getJson())); + } + return nextVersionToscaElementVertex; + } + + + private Either checkinToscaELement(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex, LifecycleStateEnum nextState) { + Either updateRelationsRes; + Either result = changeStateToCheckedIn(currState, toscaElementVertex, ownerVertex, modifierVertex); + if (result.isLeft()) { + toscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); + toscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + result = updateToscaElementVertexMetadataPropertiesAndJson(toscaElementVertex); + } + if (result.isLeft()) { + updateRelationsRes = updateLastModifierEdge(toscaElementVertex, ownerVertex, modifierVertex); + if (updateRelationsRes.isRight()) { + result = Either.right(updateRelationsRes.right().value()); + } + } + return result; + } + + private Either updateToscaElementVertexMetadataPropertiesAndJson(GraphVertex toscaElementVertex) { + + Either result; + + Either updateVertexRes = janusGraphDao.updateVertex(toscaElementVertex); + if (updateVertexRes.isRight()) { + JanusGraphOperationStatus titatStatus = updateVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update state of tosca element vertex {} metadata. Status is {}", toscaElementVertex.getUniqueId(), titatStatus); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(titatStatus)); + } else { + result = Either.left(updateVertexRes.left().value()); + } + return result; + } + + private Either changeStateToCheckedIn(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) { + Either result = null; + LifecycleStateEnum nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN; + String faileToUpdateStateMsg = "Failed to update state of tosca element {}. Status is {}"; + + if (currState == LifecycleStateEnum.READY_FOR_CERTIFICATION) { + // In case of cancel "ready for certification" remove last state edge with "STATE" property equals to "NOT_CERTIFIED_CHECKIN" + Map vertexProperties = new EnumMap<>(GraphPropertyEnum.class); + vertexProperties.put(GraphPropertyEnum.STATE, nextState); + Either deleteResult = janusGraphDao + .deleteBelongingEdgeByCriteria(toscaElementVertex, EdgeLabelEnum.LAST_STATE, vertexProperties); + if (deleteResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId(), deleteResult.right().value()); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "failed to update last state relation"); + result = Either.right(StorageOperationStatus.INCONSISTENCY); + } + } + if (result == null) { + // Remove CHECKOUT relation + Either deleteEdgeResult = janusGraphDao + .deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE); + if (deleteEdgeResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId()); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(deleteEdgeResult.right().value())); + } + } + if (result == null) { + // Create CHECKIN relation + Map edgeProperties = new EnumMap<>(EdgePropertyEnum.class); + edgeProperties.put(EdgePropertyEnum.STATE, nextState); + JanusGraphOperationStatus + createEdgeRes = janusGraphDao + .createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.STATE, edgeProperties); + if (createEdgeRes != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId()); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdgeRes)); + } + } + if (result == null) { + result = Either.left(toscaElementVertex); + } + return result; + } + + private Either updateLastModifierEdge(GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) { + Either result = null; + if (!modifierVertex.getMetadataProperties().get(GraphPropertyEnum.USERID).equals(ownerVertex.getMetadataProperties().get(GraphPropertyEnum.USERID))) { + Either deleteEdgeRes = janusGraphDao + .deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.LAST_MODIFIER); + if (deleteEdgeRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete last modifier {} to tosca element {}. Edge type is {}", ownerVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(deleteEdgeRes.right().value())); + } + if (result == null) { + JanusGraphOperationStatus createEdgeRes = janusGraphDao + .createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); + + if (createEdgeRes != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to associate user {} to component {}. Edge type is {}", modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdgeRes)); + } else { + result = Either.left(modifierVertex); + } + } + } else { + result = Either.left(ownerVertex); + } + return result; + } + + private Map> prepareParametersToGetVerticesForCheckin(String toscaElementId, String modifierId, String ownerId) { + Map> verticesToGetParameters = new HashMap<>(); + verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseMetadata)); + verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); + verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); + return verticesToGetParameters; + } + + private Map> prepareParametersToGetVerticesForRequestCertification(String toscaElementId, String modifierId, String ownerId) { + Map> verticesToGetParameters = new HashMap<>(); + verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseAll)); + verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); + verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); + return verticesToGetParameters; + } + + private Map> prepareParametersToGetVerticesForCheckout(String toscaElementId, String modifierId, String ownerId) { + //Implementation is currently identical + return prepareParametersToGetVerticesForRequestCertification(toscaElementId,modifierId, ownerId); + } + + private String getNextCertifiedVersion(String version) { + String[] versionParts = version.split(VERSION_DELIMITER_REGEXP); + Integer nextMajorVersion = Integer.parseInt(versionParts[0]) + 1; + return nextMajorVersion + VERSION_DELIMITER + "0"; + } + + private String getNextVersion(String currVersion) { + String[] versionParts = currVersion.split(VERSION_DELIMITER_REGEXP); + Integer minorVersion = Integer.parseInt(versionParts[1]) + 1; + return versionParts[0] + VERSION_DELIMITER + minorVersion; + } + + private Integer getMinorVersion(String version) { + String[] versionParts = version.split(VERSION_DELIMITER_REGEXP); + return Integer.parseInt(versionParts[1]); + } + + private Integer getMajorVersion(String version) { + String[] versionParts = version.split(VERSION_DELIMITER_REGEXP); + return Integer.parseInt(versionParts[0]); + } + + private boolean isFirstCheckoutAfterCertification(String version) { + return (Integer.parseInt(version.split(VERSION_DELIMITER_REGEXP)[0]) != 0 && Integer.parseInt(version.split(VERSION_DELIMITER_REGEXP)[1]) == 1); + } + + public Either forceCerificationOfToscaElement(String toscaElementId, String modifierId, String ownerId, String currVersion) { + Either resultUpdate = null; + Either result = null; + GraphVertex toscaElement = null; + GraphVertex modifier = null; + GraphVertex owner; + try { + Either, JanusGraphOperationStatus> getVerticesRes = janusGraphDao + .getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVerticesRes.right().value())); + } + if (result == null) { + toscaElement = getVerticesRes.left().value().get(toscaElementId); + modifier = getVerticesRes.left().value().get(modifierId); + owner = getVerticesRes.left().value().get(ownerId); + + StorageOperationStatus status = handleRelationsUponForceCertification(toscaElement, modifier, owner); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); + } + } + if (result == null) { + LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFIED; + + toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + toscaElement.addMetadataProperty(GraphPropertyEnum.VERSION, getNextCertifiedVersion(currVersion)); + + resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); + if (resultUpdate.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); + result = Either.right(resultUpdate.right().value()); + } + } + if (result == null) { + ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); + result = operation.getToscaElement(toscaElement.getUniqueId()); + } + return result; + + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage()); + } + return result; + } + + private StorageOperationStatus handleRelationsUponForceCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { + + StorageOperationStatus result = null; + JanusGraphOperationStatus status = janusGraphDao + .replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); + if (status != JanusGraphOperationStatus.OK) { + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + if (result == null) { + Map properties = new EnumMap<>(EdgePropertyEnum.class); + properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFIED); + status = janusGraphDao + .createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties); + if (status != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private StorageOperationStatus updateEdgeToCatalogRootByUndoCheckout(JanusGraphVertex preV, GraphVertex curV) { + if (preV == null) { + return updateEdgeToCatalogRoot(null, curV); + } + String uniqueIdPreVer = (String) janusGraphDao + .getProperty((JanusGraphVertex) preV, GraphPropertyEnum.UNIQUE_ID.getProperty()); + LifecycleStateEnum state = LifecycleStateEnum.findState((String) janusGraphDao + .getProperty(preV, GraphPropertyEnum.STATE.getProperty())); + if (state == LifecycleStateEnum.CERTIFIED) { + return updateEdgeToCatalogRoot(null, curV); + } + return janusGraphDao.getVertexById(uniqueIdPreVer) + .either(l -> updateEdgeToCatalogRoot(l, curV), + DaoStatusConverter::convertJanusGraphStatusToStorageStatus); + } + + private StorageOperationStatus updateEdgeToCatalogRoot(GraphVertex newVersionV, GraphVertex prevVersionV) { + Either catalog = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT); + if (catalog.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch catalog vertex. error {}", catalog.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(catalog.right().value()); + } + GraphVertex catalogV = catalog.left().value(); + if (newVersionV != null) { + Boolean isAbstract = (Boolean) newVersionV.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT); + + if ( isAbstract == null || !isAbstract ) { + // no new vertex, only delete previous + JanusGraphOperationStatus + result = janusGraphDao + .createEdge(catalogV, newVersionV, EdgeLabelEnum.CATALOG_ELEMENT, null); + if (result != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge from {} to catalog vertex. error {}", newVersionV.getUniqueId(), result); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result); + } + } + } + if (prevVersionV != null) { + Boolean isAbstract = (Boolean) prevVersionV.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT); + if (isAbstract == null || !isAbstract) { + // if prev == null -> new resource was added + Either deleteResult = janusGraphDao + .deleteEdge(catalogV, prevVersionV, EdgeLabelEnum.CATALOG_ELEMENT); + if (deleteResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete edge from {} to catalog vertex. error {}", prevVersionV.getUniqueId(), deleteResult.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(deleteResult.right().value()); + } + } + } + return StorageOperationStatus.OK; + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java new file mode 100644 index 0000000000..791db33d66 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java @@ -0,0 +1,1405 @@ +/*- + * ============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.jsonjanusgraph.operations; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.catalog.CatalogComponent; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.NodeType; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.StopWatch; + +import java.lang.reflect.Type; +import java.util.*; +import java.util.Map.Entry; +import java.util.stream.Collectors; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public abstract class ToscaElementOperation extends BaseOperation { + private static final String FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR = "failed to fetch {} for tosca element with id {}, error {}"; + + private static final String CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS = "Cannot find user {} in the graph. status is {}"; + + private static final String FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS = "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. "; + + private static Logger log = Logger.getLogger(ToscaElementOperation.class.getName()); + + private static final Gson gson = new Gson(); + + @Autowired + protected CategoryOperation categoryOperation; + + protected Gson getGson() { + return gson; + } + + + protected Either getComponentByLabelAndId(String uniqueId, ToscaElementTypeEnum nodeType, JsonParseFlagEnum parseFlag) { + + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesToMatch.put(GraphPropertyEnum.UNIQUE_ID, uniqueId); + + VertexTypeEnum vertexType = ToscaElementTypeEnum.getVertexTypeByToscaType(nodeType); + Either, JanusGraphOperationStatus> getResponse = janusGraphDao + .getByCriteria(vertexType, propertiesToMatch, parseFlag); + if (getResponse.isRight()) { + log.debug("Couldn't fetch component with type {} and unique id {}, error: {}", vertexType, uniqueId, getResponse.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResponse.right().value())); + + } + List componentList = getResponse.left().value(); + if (componentList.isEmpty()) { + log.debug("Component with type {} and unique id {} was not found", vertexType, uniqueId); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + GraphVertex vertexG = componentList.get(0); + return Either.left(vertexG); + } + + public Either getToscaElement(String uniqueId) { + return getToscaElement(uniqueId, new ComponentParametersView()); + } + + public Either markComponentToDelete(GraphVertex componentToDelete) { + Either result = null; + + Boolean isDeleted = (Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_DELETED); + if (isDeleted != null && isDeleted && !(Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION)) { + // component already marked for delete + result = Either.left(componentToDelete); + return result; + } else { + + componentToDelete.addMetadataProperty(GraphPropertyEnum.IS_DELETED, Boolean.TRUE); + componentToDelete.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + + Either updateNode = janusGraphDao.updateVertex(componentToDelete); + + StorageOperationStatus updateComponent; + if (updateNode.isRight()) { + log.debug("Failed to update component {}. status is {}", componentToDelete.getUniqueId(), updateNode.right().value()); + updateComponent = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateNode.right().value()); + result = Either.right(updateComponent); + return result; + } + + result = Either.left(componentToDelete); + return result; + } + } + + /** + * Performs a shadow clone of previousToscaElement + * + * @param previousToscaElement + * @param nextToscaElement + * @param user + * @return + */ + public Either cloneToscaElement(GraphVertex previousToscaElement, GraphVertex nextToscaElement, GraphVertex user) { + + Either result = null; + GraphVertex createdToscaElementVertex = null; + JanusGraphOperationStatus status; + + Either createNextVersionRes = janusGraphDao.createVertex(nextToscaElement); + if (createNextVersionRes.isRight()) { + status = createNextVersionRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create tosca element vertex {} with version {} on graph. Status is {}. ", previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), + previousToscaElement.getMetadataProperty(GraphPropertyEnum.VERSION), status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + if (result == null) { + createdToscaElementVertex = createNextVersionRes.left().value(); + Map properties = new HashMap<>(); + properties.put(EdgePropertyEnum.STATE, createdToscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE)); + status = janusGraphDao + .createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.STATE, properties); + if (status != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.STATE, user.getUniqueId(), + previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (result == null) { + status = janusGraphDao + .createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); + if (status != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.LAST_MODIFIER, user.getUniqueId(), + nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (result == null) { + status = janusGraphDao + .createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.CREATOR, new HashMap<>()); + if (status != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.CREATOR, user.getUniqueId(), + nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (result == null) { + Iterator edgesToCopyIter = previousToscaElement.getVertex().edges(Direction.OUT); + while (edgesToCopyIter.hasNext()) { + Edge currEdge = edgesToCopyIter.next(); + Vertex currVertex = currEdge.inVertex(); + status = janusGraphDao + .createEdge(createdToscaElementVertex.getVertex(), currVertex, EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()), currEdge); + if (status != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from tosca element vertex {} to vertex with label {} on graph. Status is {}. ", currEdge.label(), createdToscaElementVertex.getUniqueId(), + currVertex.property(GraphPropertyEnum.LABEL.getProperty()), status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + break; + } + } + } + + if (result == null) { + result = Either.left(createdToscaElementVertex); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element {} with the name {}. ", previousToscaElement.getUniqueId(), previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME)); + } + return result; + } + + protected JanusGraphOperationStatus setLastModifierFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + Either parentVertex = janusGraphDao + .getParentVertex(componentV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse); + if (parentVertex.isRight()) { + log.debug("Failed to fetch last modifier for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value()); + return parentVertex.right().value(); + } + GraphVertex userV = parentVertex.left().value(); + String userId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); + toscaElement.setLastUpdaterUserId(userId); + toscaElement.setLastUpdaterFullName(buildFullName(userV)); + return JanusGraphOperationStatus.OK; + } + + public String buildFullName(GraphVertex userV) { + + String fullName = (String) userV.getMetadataProperty(GraphPropertyEnum.FIRST_NAME); + if (fullName == null) { + fullName = ""; + } else { + fullName = fullName + " "; + } + String lastName = (String) userV.getMetadataProperty(GraphPropertyEnum.LAST_NAME); + if (lastName != null) { + fullName += lastName; + } + return fullName; + } + + protected JanusGraphOperationStatus setCreatorFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + Either parentVertex = janusGraphDao + .getParentVertex(componentV, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse); + if (parentVertex.isRight()) { + log.debug("Failed to fetch creator for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value()); + return parentVertex.right().value(); + } + GraphVertex userV = parentVertex.left().value(); + String creatorUserId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); + toscaElement.setCreatorUserId(creatorUserId); + toscaElement.setCreatorFullName(buildFullName(userV)); + + return JanusGraphOperationStatus.OK; + } + + protected T getResourceMetaDataFromResource(T toscaElement) { + if (toscaElement.getNormalizedName() == null || toscaElement.getNormalizedName().isEmpty()) { + toscaElement.setNormalizedName(ValidationUtils.normaliseComponentName(toscaElement.getName())); + } + if (toscaElement.getSystemName() == null || toscaElement.getSystemName().isEmpty()) { + toscaElement.setSystemName(ValidationUtils.convertToSystemName(toscaElement.getName())); + } + + LifecycleStateEnum lifecycleStateEnum = toscaElement.getLifecycleState(); + if (lifecycleStateEnum == null) { + toscaElement.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + long currentDate = System.currentTimeMillis(); + if (toscaElement.getCreationDate() == null) { + toscaElement.setCreationDate(currentDate); + } + toscaElement.setLastUpdateDate(currentDate); + + return toscaElement; + } + + protected void fillCommonMetadata(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { + if (toscaElement.isHighestVersion() == null) { + toscaElement.setHighestVersion(true); + } + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_DELETED, toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, toscaElement.getMetadataValueOrDefault(JsonPresentationFields.HIGHEST_VERSION, Boolean.TRUE)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.STATE, toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_TYPE)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.VERSION, toscaElement.getMetadataValue(JsonPresentationFields.VERSION)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME, toscaElement.getMetadataValue(JsonPresentationFields.NORMALIZED_NAME)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, toscaElement.getMetadataValue(JsonPresentationFields.UNIQUE_ID)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UUID, toscaElement.getMetadataValue(JsonPresentationFields.UUID)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.INVARIANT_UUID, toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NAME, toscaElement.getMetadataValue(JsonPresentationFields.NAME)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.SYSTEM_NAME, toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_ARCHIVED)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME, toscaElement.getMetadataValue(JsonPresentationFields.ARCHIVE_TIME)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_VSP_ARCHIVED)); + toscaElement.getMetadata().entrySet().stream().filter(e -> e.getValue() != null).forEach(e -> nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.getByPresentation(e.getKey()), e.getValue())); + + nodeTypeVertex.setUniqueId(toscaElement.getUniqueId()); + nodeTypeVertex.setType(toscaElement.getComponentType()); + + } + + protected StorageOperationStatus assosiateToUsers(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { + // handle user + String userId = toscaElement.getCreatorUserId(); + + Either findUser = findUserVertex(userId); + + if (findUser.isRight()) { + JanusGraphOperationStatus status = findUser.right().value(); + log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, userId, status); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + + } + GraphVertex creatorVertex = findUser.left().value(); + GraphVertex updaterVertex = creatorVertex; + String updaterId = toscaElement.getLastUpdaterUserId(); + if (updaterId != null && !updaterId.equals(userId)) { + findUser = findUserVertex(updaterId); + if (findUser.isRight()) { + JanusGraphOperationStatus status = findUser.right().value(); + log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, userId, status); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } else { + updaterVertex = findUser.left().value(); + } + } + Map props = new EnumMap<>(EdgePropertyEnum.class); + props.put(EdgePropertyEnum.STATE, (String) toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); + + JanusGraphOperationStatus + result = janusGraphDao + .createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.STATE, props); + log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.STATE); + if (JanusGraphOperationStatus.OK != result) { + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result); + } + result = janusGraphDao + .createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.LAST_MODIFIER, null); + log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); + if (!result.equals(JanusGraphOperationStatus.OK)) { + log.error("Failed to associate user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result); + } + + toscaElement.setLastUpdaterUserId(toscaElement.getCreatorUserId()); + toscaElement.setLastUpdaterFullName(toscaElement.getCreatorFullName()); + + result = janusGraphDao.createEdge(creatorVertex, nodeTypeVertex, EdgeLabelEnum.CREATOR, null); + log.debug("After associating user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR); + if (!result.equals(JanusGraphOperationStatus.OK)) { + log.error("Failed to associate user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result); + } + return StorageOperationStatus.OK; + } + + protected StorageOperationStatus assosiateResourceMetadataToCategory(GraphVertex nodeTypeVertex, ToscaElement nodeType) { + String subcategoryName = nodeType.getCategories().get(0).getSubcategories().get(0).getName(); + String categoryName = nodeType.getCategories().get(0).getName(); + Either getCategoryVertex = getResourceCategoryVertex(nodeType.getUniqueId(), subcategoryName, categoryName); + + if (getCategoryVertex.isRight()) { + return getCategoryVertex.right().value(); + } + + GraphVertex subCategoryV = getCategoryVertex.left().value(); + + JanusGraphOperationStatus + createEdge = janusGraphDao + .createEdge(nodeTypeVertex, subCategoryV, EdgeLabelEnum.CATEGORY, new HashMap<>()); + if (createEdge != JanusGraphOperationStatus.OK) { + log.trace("Failed to associate resource {} to category {} with id {}", nodeType.getUniqueId(), subcategoryName, subCategoryV.getUniqueId()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge); + } + return StorageOperationStatus.OK; + } + + protected Either getResourceCategoryVertex(String elementId, String subcategoryName, String categoryName) { + Either category = categoryOperation.getCategory(categoryName, VertexTypeEnum.RESOURCE_CATEGORY); + if (category.isRight()) { + log.trace("Failed to fetch category {} for resource {} error {}", categoryName, elementId, category.right().value()); + return Either.right(category.right().value()); + } + GraphVertex categoryV = category.left().value(); + + if (subcategoryName != null) { + Either subCategory = categoryOperation.getSubCategoryForCategory(categoryV, subcategoryName); + if (subCategory.isRight()) { + log.trace("Failed to fetch subcategory {} of category for resource {} error {}", subcategoryName, categoryName, elementId, subCategory.right().value()); + return Either.right(subCategory.right().value()); + } + + GraphVertex subCategoryV = subCategory.left().value(); + return Either.left(subCategoryV); + } + return Either.left(categoryV); + } + + private StorageOperationStatus associateArtifactsToResource(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { + Map artifacts = toscaElement.getArtifacts(); + Either status; + if (artifacts != null) { + artifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); + a.setUniqueId(uniqueId); + }); + status = associateElementToData(nodeTypeVertex, VertexTypeEnum.ARTIFACTS, EdgeLabelEnum.ARTIFACTS, artifacts); + if (status.isRight()) { + return status.right().value(); + } + } + Map toscaArtifacts = toscaElement.getToscaArtifacts(); + if (toscaArtifacts != null) { + toscaArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); + a.setUniqueId(uniqueId); + }); + status = associateElementToData(nodeTypeVertex, VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, toscaArtifacts); + if (status.isRight()) { + return status.right().value(); + } + } + Map deploymentArtifacts = toscaElement.getDeploymentArtifacts(); + if (deploymentArtifacts != null) { + deploymentArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); + a.setUniqueId(uniqueId); + }); + status = associateElementToData(nodeTypeVertex, VertexTypeEnum.DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS, deploymentArtifacts); + if (status.isRight()) { + return status.right().value(); + } + } + return StorageOperationStatus.OK; + } + + protected JanusGraphOperationStatus disassociateAndDeleteCommonElements(GraphVertex toscaElementVertex) { + JanusGraphOperationStatus + status = janusGraphDao + .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ARTIFACTS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disaccociate artifact for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = janusGraphDao + .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.TOSCA_ARTIFACTS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disaccociate tosca artifact for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = janusGraphDao + .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to deployment artifact for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = janusGraphDao + .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.PROPERTIES); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disaccociate properties for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = janusGraphDao + .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disaccociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = janusGraphDao + .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disaccociate additional information for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = janusGraphDao + .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disaccociate capabilities for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = janusGraphDao + .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = janusGraphDao + .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH); + if (status != JanusGraphOperationStatus.OK) { + log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + return JanusGraphOperationStatus.OK; + } + + protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement, List derivedResources) { + + StorageOperationStatus associateUsers = assosiateToUsers(nodeTypeVertex, toscaElement); + if (associateUsers != StorageOperationStatus.OK) { + return associateUsers; + } + StorageOperationStatus associateArtifacts = associateArtifactsToResource(nodeTypeVertex, toscaElement); + if (associateArtifacts != StorageOperationStatus.OK) { + return associateArtifacts; + } + StorageOperationStatus associateProperties = associatePropertiesToResource(nodeTypeVertex, toscaElement, derivedResources); + if (associateProperties != StorageOperationStatus.OK) { + return associateProperties; + } + StorageOperationStatus associateAdditionaInfo = associateAdditionalInfoToResource(nodeTypeVertex, toscaElement); + if (associateAdditionaInfo != StorageOperationStatus.OK) { + return associateAdditionaInfo; + } + if (needConnectToCatalog(toscaElement)) { + StorageOperationStatus associateToCatalog = associateToCatalogRoot(nodeTypeVertex); + if (associateToCatalog != StorageOperationStatus.OK) { + return associateToCatalog; + } + } + return StorageOperationStatus.OK; + } + + private boolean needConnectToCatalog(ToscaElement toscaElement) { + Boolean isAbstract = (Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT); + if (isAbstract != null && isAbstract) { + return false; + } + return toscaElement.isHighestVersion(); + } + + private StorageOperationStatus associateToCatalogRoot(GraphVertex nodeTypeVertex) { + Either catalog = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT); + if (catalog.isRight()) { + log.debug("Failed to fetch catalog vertex. error {}", catalog.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(catalog.right().value()); + } + JanusGraphOperationStatus + createEdge = janusGraphDao + .createEdge(catalog.left().value(), nodeTypeVertex, EdgeLabelEnum.CATALOG_ELEMENT, null); + + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge); + } + + protected StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType, List derivedResources) { + // Note : currently only one derived supported!!!! + Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.PROPERTIES); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map propertiesAll = dataFromDerived.left().value(); + + Map properties = nodeType.getProperties(); + + if (properties != null) { + properties.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { + String uid = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId(), p.getName()); + p.setUniqueId(uid); + }); + + Either, String> eitherMerged = ToscaDataDefinition.mergeDataMaps(propertiesAll, properties); + if (eitherMerged.isRight()) { + // TODO re-factor error handling - moving BL to operation resulted in loss of info about the invalid property + log.debug("property {} cannot be overriden", eitherMerged.right().value()); + return StorageOperationStatus.INVALID_PROPERTY; + } + } + if (!propertiesAll.isEmpty()) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES, EdgeLabelEnum.PROPERTIES, propertiesAll); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateAdditionalInfoToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType) { + Map additionalInformation = nodeType.getAdditionalInformation(); + if (additionalInformation != null) { + Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, additionalInformation); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + protected Either, StorageOperationStatus> getDataFromDerived(List derivedResources, EdgeLabelEnum edge) { + Map propertiesAll = new HashMap<>(); + + if (derivedResources != null && !derivedResources.isEmpty()) { + for (GraphVertex derived : derivedResources) { + Either, JanusGraphOperationStatus> derivedProperties = janusGraphDao + .getChildrenVertecies(derived, edge, JsonParseFlagEnum.ParseJson); + if (derivedProperties.isRight()) { + if (derivedProperties.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + log.debug("Failed to get properties for derived from {} error {}", derived.getUniqueId(), derivedProperties.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(derivedProperties.right().value())); + } else { + continue; + } + } + List propList = derivedProperties.left().value(); + for (GraphVertex propV : propList) { + Map propertiesFromDerived = (Map) propV.getJson(); + if (propertiesFromDerived != null) { + propertiesFromDerived.entrySet().forEach(x -> x.getValue().setOwnerIdIfEmpty(derived.getUniqueId())); + propertiesAll.putAll(propertiesFromDerived); + } + } + } + } + return Either.left(propertiesAll); + } + + protected JanusGraphOperationStatus setArtifactsFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ARTIFACTS); + if (result.isLeft()) { + toscaElement.setArtifacts(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + result = getDataFromGraph(componentV, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); + if (result.isLeft()) { + toscaElement.setDeploymentArtifacts(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + result = getDataFromGraph(componentV, EdgeLabelEnum.TOSCA_ARTIFACTS); + if (result.isLeft()) { + toscaElement.setToscaArtifacts(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + protected JanusGraphOperationStatus setAllVersions(GraphVertex componentV, ToscaElement toscaElement) { + Map allVersion = new HashMap<>(); + + allVersion.put((String) componentV.getMetadataProperty(GraphPropertyEnum.VERSION), componentV.getUniqueId()); + ArrayList allChildrenAndParants = new ArrayList<>(); + Either childResourceRes = janusGraphDao + .getChildVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + while (childResourceRes.isLeft()) { + GraphVertex child = childResourceRes.left().value(); + allChildrenAndParants.add(child); + childResourceRes = janusGraphDao + .getChildVertex(child, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + } + JanusGraphOperationStatus operationStatus = childResourceRes.right().value(); + + if (operationStatus != JanusGraphOperationStatus.NOT_FOUND) { + return operationStatus; + } else { + Either parentResourceRes = janusGraphDao + .getParentVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + while (parentResourceRes.isLeft()) { + GraphVertex parent = parentResourceRes.left().value(); + allChildrenAndParants.add(parent); + parentResourceRes = janusGraphDao + .getParentVertex(parent, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + } + operationStatus = parentResourceRes.right().value(); + if (operationStatus != JanusGraphOperationStatus.NOT_FOUND) { + return operationStatus; + } else { + allChildrenAndParants.stream().filter(vertex -> { + Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED); + return (isDeleted == null || !isDeleted); + }).forEach(vertex -> allVersion.put((String) vertex.getMetadataProperty(GraphPropertyEnum.VERSION), vertex.getUniqueId())); + + toscaElement.setAllVersions(allVersion); + return JanusGraphOperationStatus.OK; + } + } + } + + protected Either, StorageOperationStatus> getFollowedComponent(String userId, Set lifecycleStates, Set lastStateStates, ComponentTypeEnum neededType) { + + Either, StorageOperationStatus> result = null; + + Map props = null; + + if (userId != null) { + props = new EnumMap<>(GraphPropertyEnum.class); + // for Designer retrieve specific user + props.put(GraphPropertyEnum.USERID, userId); + } + // in case of user id == null -> get all users by label + // for Tester and Admin retrieve all users + Either, JanusGraphOperationStatus> usersByCriteria = janusGraphDao + .getByCriteria(VertexTypeEnum.USER, props, JsonParseFlagEnum.NoParse); + if (usersByCriteria.isRight()) { + log.debug("Failed to fetch users by criteria {} error {}", props, usersByCriteria.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(usersByCriteria.right().value())); + } + List users = usersByCriteria.left().value(); + + List components = new ArrayList<>(); + List componentsPerUser; + for (GraphVertex userV : users) { + + HashSet ids = new HashSet<>(); + Either, JanusGraphOperationStatus> childrenVertecies = janusGraphDao + .getChildrenVertecies(userV, EdgeLabelEnum.STATE, JsonParseFlagEnum.NoParse); + if (childrenVertecies.isRight() && childrenVertecies.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.STATE, childrenVertecies.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childrenVertecies.right().value())); + } + + // get all resource with current state + if (childrenVertecies.isLeft()) { + componentsPerUser = fetchComponents(lifecycleStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.STATE); + + if (componentsPerUser != null) { + for (T comp : componentsPerUser) { + ids.add(comp.getUniqueId()); + components.add(comp); + } + } + } + if (lastStateStates != null && !lastStateStates.isEmpty()) { + // get all resource with last state + childrenVertecies = janusGraphDao + .getChildrenVertecies(userV, EdgeLabelEnum.LAST_STATE, JsonParseFlagEnum.NoParse); + if (childrenVertecies.isRight() && childrenVertecies.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.LAST_STATE, childrenVertecies.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childrenVertecies.right().value())); + } + if (childrenVertecies.isLeft()) { + boolean isFirst; + componentsPerUser = fetchComponents(lastStateStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.LAST_STATE); + if (componentsPerUser != null) { + for (T comp : componentsPerUser) { + isFirst = true; + + if (ids.contains(comp.getUniqueId())) { + isFirst = false; + } + if (isFirst) { + components.add(comp); + } + + } + } + } + } + + } // whlile users + ; + result = Either.left(components); + return result; + + } + + private List fetchComponents(Set lifecycleStates, List vertices, ComponentTypeEnum neededType, EdgeLabelEnum edgelabel) { + List components = new ArrayList<>(); + for (GraphVertex node : vertices) { + + Iterator edges = node.getVertex().edges(Direction.IN, edgelabel.name()); + while (edges.hasNext()) { + Edge edge = edges.next(); + String stateStr = (String) janusGraphDao.getProperty(edge, EdgePropertyEnum.STATE); + + LifecycleStateEnum nodeState = LifecycleStateEnum.findState(stateStr); + if (nodeState == null) { + log.debug("no supported STATE {} for element {}", stateStr, node.getUniqueId()); + continue; + } + if (lifecycleStates != null && lifecycleStates.contains(nodeState)) { + + Boolean isDeleted = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_DELETED); + Boolean isArchived = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED); + if (isDeleted != null && isDeleted || isArchived != null && isArchived) { + log.trace("Deleted/Archived element {}, discard", node.getUniqueId()); + continue; + } + + Boolean isHighest = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); + if (isHighest) { + + ComponentTypeEnum componentType = node.getType(); + // get only latest versions + + if (componentType == null) { + log.debug("No supported type {} for vertex {}", componentType, node.getUniqueId()); + continue; + } + if (neededType == componentType) { + switch (componentType) { + case SERVICE: + case PRODUCT: + handleNode(components, node, componentType); + break; + case RESOURCE: + Boolean isAbtract = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT); + if (isAbtract == null || !isAbtract) { + handleNode(components, node, componentType); + } // if not abstract + break; + default: + log.debug("not supported node type {}", componentType); + break; + }// case + } // needed type + } + } // if + } // while edges + } // while resources + return components; + } + + protected void handleNode(List components, GraphVertex vertexComponent, ComponentTypeEnum nodeType) { + + Either component = getLightComponent(vertexComponent, nodeType, new ComponentParametersView(true)); + if (component.isRight()) { + log.debug("Failed to get component for id = {} error : {} skip resource", vertexComponent.getUniqueId(), component.right().value()); + } else { + components.add(component.left().value()); + } + } + + protected Either getLightComponent(String componentUid, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) { + Either getVertexRes = janusGraphDao.getVertexById(componentUid); + if (getVertexRes.isRight()) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexRes.right().value())); + } + return getLightComponent(getVertexRes.left().value(), nodeType, parametersFilter); + } + + protected Either getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) { + + log.trace("Starting to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId()); + + janusGraphDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata); + + T toscaElement = convertToComponent(vertexComponent); + + JanusGraphOperationStatus status = setCreatorFromGraph(vertexComponent, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + + status = setLastModifierFromGraph(vertexComponent, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = setCategoriesFromGraph(vertexComponent, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + if (!parametersFilter.isIgnoreAllVersions()) { + status = setAllVersions(vertexComponent, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (!parametersFilter.isIgnoreCapabilities()) { + status = setCapabilitiesFromGraph(vertexComponent, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + if (!parametersFilter.isIgnoreRequirements()) { + status = setRequirementsFromGraph(vertexComponent, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } + log.debug("Ended to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId()); + return Either.left(toscaElement); + } + + @SuppressWarnings("unchecked") + protected T convertToComponent(GraphVertex componentV) { + ToscaElement toscaElement = null; + VertexTypeEnum label = componentV.getLabel(); + switch (label) { + case NODE_TYPE: + toscaElement = new NodeType(); + break; + case TOPOLOGY_TEMPLATE: + toscaElement = new TopologyTemplate(); + break; + default: + log.debug("Not supported tosca type {}", label); + break; + } + + Map jsonMetada = componentV.getMetadataJson(); + if (toscaElement != null) { + toscaElement.setMetadata(jsonMetada); + } + return (T) toscaElement; + } + + protected JanusGraphOperationStatus setResourceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) { + + Either childVertex = janusGraphDao + .getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(), childVertex.right().value()); + return childVertex.right().value(); + } + Vertex subCategoryV = childVertex.left().value(); + catalogComponent.setSubCategoryNormalizedName((String) subCategoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); + Either parentVertex = janusGraphDao + .getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); + Vertex categoryV = parentVertex.left().value(); + catalogComponent.setCategoryNormalizedName((String) categoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); + + return JanusGraphOperationStatus.OK; + } + + protected JanusGraphOperationStatus setServiceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) { + Either childVertex = janusGraphDao + .getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(), childVertex.right().value()); + return childVertex.right().value(); + } + Vertex categoryV = childVertex.left().value(); + catalogComponent.setCategoryNormalizedName((String) categoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); + + return JanusGraphOperationStatus.OK; + } + + protected JanusGraphOperationStatus setResourceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + List categories = new ArrayList<>(); + SubCategoryDefinition subcategory; + + Either childVertex = janusGraphDao + .getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value()); + return childVertex.right().value(); + } + GraphVertex subCategoryV = childVertex.left().value(); + Map metadataProperties = subCategoryV.getMetadataProperties(); + subcategory = new SubCategoryDefinition(); + subcategory.setUniqueId(subCategoryV.getUniqueId()); + subcategory.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME)); + subcategory.setName((String) metadataProperties.get(GraphPropertyEnum.NAME)); + + Type listTypeSubcat = new TypeToken>() { + }.getType(); + List iconsfromJsonSubcat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeSubcat); + subcategory.setIcons(iconsfromJsonSubcat); + + Either parentVertex = janusGraphDao + .getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); + if (parentVertex.isRight()) { + log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value()); + return childVertex.right().value(); + } + GraphVertex categoryV = parentVertex.left().value(); + metadataProperties = categoryV.getMetadataProperties(); + + CategoryDefinition category = new CategoryDefinition(); + category.setUniqueId(categoryV.getUniqueId()); + category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME)); + category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME)); + + Type listTypeCat = new TypeToken>() { + }.getType(); + List iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeCat); + category.setIcons(iconsfromJsonCat); + + category.addSubCategory(subcategory); + categories.add(category); + toscaElement.setCategories(categories); + + return JanusGraphOperationStatus.OK; + } + + public Either updateToscaElement(T toscaElementToUpdate, GraphVertex elementV, ComponentParametersView filterResult) { + Either result = null; + + log.debug("In updateToscaElement. received component uid = {}", (toscaElementToUpdate == null ? null : toscaElementToUpdate.getUniqueId())); + if (toscaElementToUpdate == null) { + log.error("Service object is null"); + result = Either.right(StorageOperationStatus.BAD_REQUEST); + return result; + } + + String modifierUserId = toscaElementToUpdate.getLastUpdaterUserId(); + if (modifierUserId == null || modifierUserId.isEmpty()) { + log.error("UserId is missing in the request."); + result = Either.right(StorageOperationStatus.BAD_REQUEST); + return result; + } + Either findUser = findUserVertex(modifierUserId); + + if (findUser.isRight()) { + JanusGraphOperationStatus status = findUser.right().value(); + log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, modifierUserId, status); + return result; + } + + GraphVertex modifierV = findUser.left().value(); + String toscaElementId = toscaElementToUpdate.getUniqueId(); + + Either parentVertex = janusGraphDao + .getParentVertex(elementV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse); + if (parentVertex.isRight()) { + log.debug("Failed to fetch last modifier for tosca element with id {} error {}", toscaElementId, parentVertex.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertex.right().value())); + } + GraphVertex userV = parentVertex.left().value(); + String currentModifier = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); + + String prevSystemName = (String) elementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME); + + if (currentModifier.equals(modifierUserId)) { + log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier."); + } else { + log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId); + StorageOperationStatus status = moveLastModifierEdge(elementV, modifierV); + log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + return result; + } + } + + final long currentTimeMillis = System.currentTimeMillis(); + log.debug("Going to update the last Update Date of the resource from {} to {}", elementV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE), currentTimeMillis); + elementV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currentTimeMillis); + + StorageOperationStatus checkCategories = validateCategories(toscaElementToUpdate, elementV); + if (checkCategories != StorageOperationStatus.OK) { + result = Either.right(checkCategories); + return result; + } + + // update all data on vertex + fillToscaElementVertexData(elementV, toscaElementToUpdate, JsonParseFlagEnum.ParseMetadata); + + Either updateElement = janusGraphDao.updateVertex(elementV); + + if (updateElement.isRight()) { + log.error("Failed to update resource {}. status is {}", toscaElementId, updateElement.right().value()); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value())); + return result; + } + GraphVertex updateElementV = updateElement.left().value(); + + // DE230195 in case resource name changed update TOSCA artifacts + // file names accordingly + String newSystemName = (String) updateElementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME); + if (newSystemName != null && !newSystemName.equals(prevSystemName)) { + Either, JanusGraphOperationStatus> resultToscaArt = getDataFromGraph(updateElementV, EdgeLabelEnum.TOSCA_ARTIFACTS); + if (resultToscaArt.isRight()) { + log.debug("Failed to get tosca artifact from graph for tosca element {} error {}", toscaElementId, resultToscaArt.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resultToscaArt.right().value())); + } + + Map toscaArtifacts = resultToscaArt.left().value(); + if (toscaArtifacts != null) { + for (Entry artifact : toscaArtifacts.entrySet()) { + generateNewToscaFileName(toscaElementToUpdate.getComponentType().getValue().toLowerCase(), newSystemName, artifact.getValue()); + } + // TODO call to new Artifact operation in order to update list of artifacts + + } + } + + if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.RESOURCE) { + StorageOperationStatus resultDerived = updateDerived(toscaElementToUpdate, updateElementV); + if (resultDerived != StorageOperationStatus.OK) { + log.debug("Failed to update from derived data for element {} error {}", toscaElementId, resultDerived); + return Either.right(resultDerived); + } + } + + Either updatedResource = getToscaElement(updateElementV, filterResult); + if (updatedResource.isRight()) { + log.error("Failed to fetch tosca element {} after update , error {}", toscaElementId, updatedResource.right().value()); + result = Either.right(StorageOperationStatus.BAD_REQUEST); + return result; + } + + T updatedResourceValue = updatedResource.left().value(); + result = Either.left(updatedResourceValue); + + return result; + } + + protected StorageOperationStatus moveLastModifierEdge(GraphVertex elementV, GraphVertex modifierV) { + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + janusGraphDao.moveEdge(elementV, modifierV, EdgeLabelEnum.LAST_MODIFIER, Direction.IN)); + } + + protected StorageOperationStatus moveCategoryEdge(GraphVertex elementV, GraphVertex categoryV) { + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + janusGraphDao.moveEdge(elementV, categoryV, EdgeLabelEnum.CATEGORY, Direction.OUT)); + } + + private void generateNewToscaFileName(String componentType, String componentName, ArtifactDataDefinition 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")); + } + + protected StorageOperationStatus validateResourceCategory(T toscaElementToUpdate, GraphVertex elementV) { + StorageOperationStatus status = StorageOperationStatus.OK; + List newCategoryList = toscaElementToUpdate.getCategories(); + CategoryDefinition newCategory = newCategoryList.get(0); + + Either childVertex = janusGraphDao + .getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value()); + } + GraphVertex subCategoryV = childVertex.left().value(); + Map metadataProperties = subCategoryV.getMetadataProperties(); + String subCategoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); + + Either parentVertex = janusGraphDao + .getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); + if (parentVertex.isRight()) { + log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value()); + } + GraphVertex categoryV = parentVertex.left().value(); + metadataProperties = categoryV.getMetadataProperties(); + String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); + + boolean categoryWasChanged = false; + + String newCategoryName = newCategory.getName(); + SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0); + String newSubCategoryName = newSubcategory.getName(); + if (newCategoryName != null && !newCategoryName.equals(categoryNameCurrent)) { + // the category was changed + categoryWasChanged = true; + } else { + // the sub-category was changed + if (newSubCategoryName != null && !newSubCategoryName.equals(subCategoryNameCurrent)) { + log.debug("Going to update the category of the resource from {} to {}", categoryNameCurrent, newCategory); + categoryWasChanged = true; + } + } + if (categoryWasChanged) { + Either getCategoryVertex = getResourceCategoryVertex(elementV.getUniqueId(), newSubCategoryName, newCategoryName); + + if (getCategoryVertex.isRight()) { + return getCategoryVertex.right().value(); + } + GraphVertex newCategoryV = getCategoryVertex.left().value(); + status = moveCategoryEdge(elementV, newCategoryV); + log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status); + } + return status; + } + + public Either, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType, List excludeTypes, boolean isHighestVersions) { + Either, JanusGraphOperationStatus> listOfComponents; + if (isHighestVersions) { + listOfComponents = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.NoParse); + } else { + listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes); + } + + if (listOfComponents.isRight() && listOfComponents.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(listOfComponents.right().value())); + } + List result = new ArrayList<>(); + if (listOfComponents.isLeft()) { + List highestAndAllCertified = listOfComponents.left().value(); + if (highestAndAllCertified != null && !highestAndAllCertified.isEmpty()) { + for (GraphVertex vertexComponent : highestAndAllCertified) { + Either component = getLightComponent(vertexComponent, componentType, new ComponentParametersView(true)); + if (component.isRight()) { + log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), component.right().value()); + return Either.right(component.right().value()); + } else { + result.add(component.left().value()); + } + } + } + } + return Either.left(result); + } + + public Either, StorageOperationStatus> getElementCatalogData(boolean isCatalog, List excludeTypes) { + StopWatch stopWatch = new StopWatch(); + stopWatch.start(); + + Map existInCatalog = new HashMap<>(); + Either, JanusGraphOperationStatus> verticesEither = janusGraphDao.getCatalogOrArchiveVerticies(isCatalog); + if (verticesEither.isRight()) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(verticesEither.right().value())); + } + Iterator vertices = verticesEither.left().value(); + while (vertices.hasNext()) { + handleCatalogComponent(existInCatalog, vertices.next(), excludeTypes); + } + stopWatch.stop(); + String timeToFetchElements = stopWatch.prettyPrint(); + log.info("time to fetch all catalog elements: {}", timeToFetchElements); + return Either.left(existInCatalog.values().stream().collect(Collectors.toList())); + } + + private void handleCatalogComponent(Map existInCatalog, Vertex vertex, List excludeTypes) { + VertexProperty property = vertex.property(GraphPropertiesDictionary.METADATA.getProperty()); + String json = (String) property.value(); + Map metadatObj = JsonParserUtils.toMap(json); + + String uniqueId = (String) metadatObj.get(JsonPresentationFields.UNIQUE_ID.getPresentation()); + Boolean isDeleted = (Boolean) metadatObj.get(JsonPresentationFields.IS_DELETED.getPresentation()); + + + if (isAddToCatalog(excludeTypes, metadatObj) && (existInCatalog.get(uniqueId) == null && (isDeleted == null || !isDeleted.booleanValue()))) { + CatalogComponent catalogComponent = new CatalogComponent(); + catalogComponent.setUniqueId(uniqueId); + + catalogComponent.setComponentType(ComponentTypeEnum.valueOf((String) metadatObj.get(JsonPresentationFields.COMPONENT_TYPE.getPresentation()))); + catalogComponent.setVersion((String) metadatObj.get(JsonPresentationFields.VERSION.getPresentation())); + catalogComponent.setName((String) metadatObj.get(JsonPresentationFields.NAME.getPresentation())); + catalogComponent.setIcon((String) metadatObj.get(JsonPresentationFields.ICON.getPresentation())); + catalogComponent.setLifecycleState((String) metadatObj.get(JsonPresentationFields.LIFECYCLE_STATE.getPresentation())); + catalogComponent.setLastUpdateDate((Long) metadatObj.get(JsonPresentationFields.LAST_UPDATE_DATE.getPresentation())); + catalogComponent.setDistributionStatus((String) metadatObj.get(JsonPresentationFields.DISTRIBUTION_STATUS.getPresentation())); + Object resourceType = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation()); + if (resourceType != null) { + catalogComponent.setResourceType((String) resourceType); + } + + if (catalogComponent.getComponentType() == ComponentTypeEnum.SERVICE) { + setServiceCategoryFromGraphV(vertex, catalogComponent); + + } else { + setResourceCategoryFromGraphV(vertex, catalogComponent); + } + List tags = (List) metadatObj.get(JsonPresentationFields.TAGS.getPresentation()); + if (tags != null) { + catalogComponent.setTags(tags); + } + existInCatalog.put(uniqueId, catalogComponent); + } + } + + private boolean isAddToCatalog(List excludeTypes, Map metadatObj) { + boolean isAddToCatalog = true; + Object resourceTypeStr = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation()); + if (resourceTypeStr != null) { + ResourceTypeEnum resourceType = ResourceTypeEnum.getType((String) resourceTypeStr); + if (!CollectionUtils.isEmpty(excludeTypes)) { + Optional op = excludeTypes.stream().filter(rt -> rt == resourceType).findAny(); + if (op.isPresent()) + isAddToCatalog = false; + } + } + return isAddToCatalog; + } + + public Either, JanusGraphOperationStatus> getListOfHighestComponents(ComponentTypeEnum + componentType, List excludeTypes, JsonParseFlagEnum parseFlag) { + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map propertiesHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + if (componentType == ComponentTypeEnum.RESOURCE) { + propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, false); + propertiesHasNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes); + } + propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + propertiesHasNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683 + + return janusGraphDao + .getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, parseFlag); + } + + // highest + (certified && !highest) + public Either, JanusGraphOperationStatus> getListOfHighestAndAllCertifiedComponents + (ComponentTypeEnum componentType, List excludeTypes) { + long startFetchAllStates = System.currentTimeMillis(); + Either, JanusGraphOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.ParseMetadata); + + Map propertiesToMatchCertified = new EnumMap<>(GraphPropertyEnum.class); + Map propertiesHasNotToMatchCertified = new EnumMap<>(GraphPropertyEnum.class); + propertiesToMatchCertified.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + propertiesToMatchCertified.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + if (componentType == ComponentTypeEnum.RESOURCE) { + propertiesToMatchCertified.put(GraphPropertyEnum.IS_ABSTRACT, false); + propertiesHasNotToMatchCertified.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes); + } + + propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true); + propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683 + propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + Either, JanusGraphOperationStatus> certifiedNotHighestNodes = janusGraphDao + .getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified, JsonParseFlagEnum.ParseMetadata); + if (certifiedNotHighestNodes.isRight() && certifiedNotHighestNodes.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return Either.right(certifiedNotHighestNodes.right().value()); + } + + long endFetchAllStates = System.currentTimeMillis(); + + List allNodes = new ArrayList<>(); + + if (certifiedNotHighestNodes.isLeft()) { + allNodes.addAll(certifiedNotHighestNodes.left().value()); + } + if (highestNodes.isLeft()) { + allNodes.addAll(highestNodes.left().value()); + } + + log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates); + return Either.left(allNodes); + } + + protected Either, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum + componentType) { + + // get all components marked for delete + Map props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.IS_DELETED, true); + props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + + Either, JanusGraphOperationStatus> componentsToDelete = janusGraphDao + .getByCriteria(null, props, JsonParseFlagEnum.NoParse); + + if (componentsToDelete.isRight()) { + JanusGraphOperationStatus error = componentsToDelete.right().value(); + if (error.equals(JanusGraphOperationStatus.NOT_FOUND)) { + log.trace("no components to delete"); + return Either.left(new ArrayList<>()); + } else { + log.info("failed to find components to delete. error : {}", error.name()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error)); + } + } + return Either.left(componentsToDelete.left().value()); + } + + protected JanusGraphOperationStatus setAdditionalInformationFromGraph(GraphVertex componentV, ToscaElement + toscaElement) { + Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ADDITIONAL_INFORMATION); + if (result.isLeft()) { + toscaElement.setAdditionalInformation(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + + // -------------------------------------------- + public abstract Either getToscaElement(String uniqueId, ComponentParametersView componentParametersView); + + public abstract Either getToscaElement(GraphVertex toscaElementVertex, ComponentParametersView componentParametersView); + + public abstract Either deleteToscaElement(GraphVertex toscaElementVertex); + + public abstract Either createToscaElement(ToscaElement toscaElement); + + protected abstract JanusGraphOperationStatus + setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement); + + protected abstract JanusGraphOperationStatus + setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement); + + protected abstract JanusGraphOperationStatus + setRequirementsFromGraph(GraphVertex componentV, T toscaElement); + + protected abstract StorageOperationStatus + validateCategories(T toscaElementToUpdate, GraphVertex elementV); + + protected abstract StorageOperationStatus + updateDerived(T toscaElementToUpdate, GraphVertex updateElementV); + + public abstract void fillToscaElementVertexData(GraphVertex elementV, T + toscaElementToUpdate, JsonParseFlagEnum flag); + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java new file mode 100644 index 0000000000..43f3487924 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java @@ -0,0 +1,2792 @@ +/*- + * ============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.jsonjanusgraph.operations; + +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.*; +import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.catalog.CatalogComponent; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; +import org.openecomp.sdc.be.model.operations.StorageException; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.resources.data.ComponentMetadataData; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.*; +import java.util.Map.Entry; +import java.util.function.BiPredicate; +import java.util.stream.Collectors; + +import static java.util.Objects.requireNonNull; +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; + + +@org.springframework.stereotype.Component("tosca-operation-facade") +public class ToscaOperationFacade { + + // region - Fields + + private static final String COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch a component with and UniqueId {}, error: {}"; + private static final String FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS = "Failed to find recently added property {} on the resource {}. Status is {}. "; + private static final String FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS = "Failed to get updated resource {}. Status is {}. "; + private static final String FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS = "Failed to add the property {} to the resource {}. Status is {}. "; + private static final String SERVICE = "service"; + private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}"; + private static final String COMPONENT_CREATED_SUCCESSFULLY = "Component created successfully!!!"; + private static final String COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch component with and unique id {}, error: {}"; + @Autowired + private NodeTypeOperation nodeTypeOperation; + @Autowired + private TopologyTemplateOperation topologyTemplateOperation; + @Autowired + private NodeTemplateOperation nodeTemplateOperation; + @Autowired + private GroupsOperation groupsOperation; + @Autowired + private HealingJanusGraphDao janusGraphDao; + + private static final Logger log = Logger.getLogger(ToscaOperationFacade.class.getName()); + // endregion + + // region - ToscaElement - GetById + public static final String PROXY_SUFFIX = "_proxy"; + + public Either getToscaFullElement(String componentId) { + ComponentParametersView filters = new ComponentParametersView(); + filters.setIgnoreCapabiltyProperties(false); + filters.setIgnoreForwardingPath(false); + return getToscaElement(componentId, filters); + } + + public Either getToscaElement(String componentId) { + + return getToscaElement(componentId, JsonParseFlagEnum.ParseAll); + + } + + public Either getToscaElement(String componentId, ComponentParametersView filters) { + + Either getVertexEither = janusGraphDao + .getVertexById(componentId, filters.detectParseFlag()); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + + } + return getToscaElementByOperation(getVertexEither.left().value(), filters); + } + + public Either getToscaElement(String componentId, JsonParseFlagEnum parseFlag) { + + Either getVertexEither = janusGraphDao + .getVertexById(componentId, parseFlag); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + + } + return getToscaElementByOperation(getVertexEither.left().value()); + } + + public Either getToscaElement(GraphVertex componentVertex) { + return getToscaElementByOperation(componentVertex); + } + + public Either validateComponentExists(String componentId) { + + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + JanusGraphOperationStatus status = getVertexEither.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + return Either.left(false); + } else { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + } + } + return Either.left(true); + } + + public Either findLastCertifiedToscaElementByUUID(T component) { + Map props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.UUID, component.getUUID()); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + Either, JanusGraphOperationStatus> getVertexEither = janusGraphDao + .getByCriteria(ModelConverter.getVertexType(component), props); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + + } + return getToscaElementByOperation(getVertexEither.left().value().get(0)); + } + + // endregion + // region - ToscaElement - GetByOperation + private Either getToscaElementByOperation(GraphVertex componentV) { + return getToscaElementByOperation(componentV, new ComponentParametersView()); + } + + private Either getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) { + VertexTypeEnum label = componentV.getLabel(); + + ToscaElementOperation toscaOperation = getToscaElementOperation(componentV); + log.debug("getToscaElementByOperation: toscaOperation={}", toscaOperation.getClass()); + Either toscaElement; + String componentId = componentV.getUniqueId(); + if (toscaOperation != null) { + log.debug("Need to fetch tosca element for id {}", componentId); + toscaElement = toscaOperation.getToscaElement(componentV, filters); + } else { + log.debug("not supported tosca type {} for id {}", label, componentId); + toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST); + } + if (toscaElement.isRight()) { + return Either.right(toscaElement.right().value()); + } + return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value())); + } + + // endregion + private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) { + VertexTypeEnum label = componentV.getLabel(); + switch (label) { + case NODE_TYPE: + return nodeTypeOperation; + case TOPOLOGY_TEMPLATE: + return topologyTemplateOperation; + default: + return null; + } + } + + public Either createToscaComponent(T resource) { + ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource); + + ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource); + Either createToscaElement = toscaElementOperation.createToscaElement(toscaElement); + if (createToscaElement.isLeft()) { + log.debug(COMPONENT_CREATED_SUCCESSFULLY); + T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value()); + return Either.left(dataModel); + } + return Either.right(createToscaElement.right().value()); + } + + // region - ToscaElement Delete + public StorageOperationStatus markComponentToDelete(Component componentToDelete) { + + if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) { + // component already marked for delete + return StorageOperationStatus.OK; + } else { + + Either getResponse = janusGraphDao + .getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll); + if (getResponse.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentToDelete.getUniqueId(), getResponse.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResponse.right().value()); + + } + GraphVertex componentV = getResponse.left().value(); + + // same operation for node type and topology template operations + Either result = nodeTypeOperation.markComponentToDelete(componentV); + if (result.isRight()) { + return result.right().value(); + } + return StorageOperationStatus.OK; + } + } + + public Either deleteToscaComponent(String componentId) { + + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + + } + Either deleteElement = deleteToscaElement(getVertexEither.left().value()); + if (deleteElement.isRight()) { + log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value()); + return Either.right(deleteElement.right().value()); + } + T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value()); + + return Either.left(dataModel); + } + + private Either deleteToscaElement(GraphVertex componentV) { + VertexTypeEnum label = componentV.getLabel(); + Either toscaElement; + Object componentId = componentV.getUniqueId(); + switch (label) { + case NODE_TYPE: + log.debug("Need to fetch node type for id {}", componentId); + toscaElement = nodeTypeOperation.deleteToscaElement(componentV); + break; + case TOPOLOGY_TEMPLATE: + log.debug("Need to fetch topology template for id {}", componentId); + toscaElement = topologyTemplateOperation.deleteToscaElement(componentV); + break; + default: + log.debug("not supported tosca type {} for id {}", label, componentId); + toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST); + break; + } + return toscaElement; + } + // endregion + + private ToscaElementOperation getToscaElementOperation(Component component) { + return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation; + } + + public Either getLatestByToscaResourceName(String toscaResourceName) { + return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); + } + + public Either getFullLatestComponentByToscaResourceName(String toscaResourceName) { + ComponentParametersView fetchAllFilter = new ComponentParametersView(); + fetchAllFilter.setIgnoreForwardingPath(true); + fetchAllFilter.setIgnoreCapabiltyProperties(false); + return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter); + } + + public Either getLatestByName(String resourceName) { + return getLatestByName(GraphPropertyEnum.NAME, resourceName); + + } + + public StorageOperationStatus validateCsarUuidUniqueness(String csarUUID) { + + Map properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID); + + Either, JanusGraphOperationStatus> resources = janusGraphDao + .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata); + + if (resources.isRight()) { + if (resources.right().value() == JanusGraphOperationStatus.NOT_FOUND) { + return StorageOperationStatus.OK; + } else { + log.debug("failed to get resources from graph with property name: {}", csarUUID); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resources.right().value()); + } + } + return StorageOperationStatus.ENTITY_ALREADY_EXISTS; + + } + + public Either, StorageOperationStatus> getFollowed(String userId, Set lifecycleStates, Set lastStateStates, ComponentTypeEnum componentType) { + Either, StorageOperationStatus> followedResources; + if (componentType == ComponentTypeEnum.RESOURCE) { + followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); + } else { + followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); + } + + Set components = new HashSet<>(); + if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) { + return Either.right(followedResources.right().value()); + } + if (followedResources.isLeft()) { + List toscaElements = followedResources.left().value(); + toscaElements.forEach(te -> { + T component = ModelConverter.convertFromToscaElement(te); + components.add(component); + }); + } + return Either.left(components); + } + + public Either getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) { + + return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata); + } + + public Either getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) { + + Either result = null; + Map props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + Either, JanusGraphOperationStatus> getLatestRes = janusGraphDao + .getByCriteria(vertexType, props, parseFlag); + + if (getLatestRes.isRight()) { + JanusGraphOperationStatus status = getLatestRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + if (result == null) { + List resources = getLatestRes.left().value(); + double version = 0.0; + GraphVertex highestResource = null; + for (GraphVertex resource : resources) { + double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION)); + if (resourceVersion > version) { + version = resourceVersion; + highestResource = resource; + } + } + result = getToscaFullElement(highestResource.getUniqueId()); + } + return result; + } + + public Either validateToscaResourceNameExists(String templateName) { + Either validateUniquenessRes = validateToscaResourceNameUniqueness(templateName); + if (validateUniquenessRes.isLeft()) { + return Either.left(!validateUniquenessRes.left().value()); + } + return validateUniquenessRes; + } + + public Either dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { + return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef); + } + + /** + * Allows to get fulfilled requirement by relation and received predicate + */ + public Either getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate predicate) { + return nodeTemplateOperation.getFulfilledRequirementByRelation(componentId, instanceId, relation, predicate); + } + + /** + * Allows to get fulfilled capability by relation and received predicate + */ + public Either getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate predicate) { + return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate); + } + + public StorageOperationStatus associateResourceInstances(String componentId, List relations) { + Either, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations); + if (status.isRight()) { + return status.right().value(); + } + return StorageOperationStatus.OK; + } + + protected Either validateToscaResourceNameUniqueness(String name) { + + Map properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name); + + Either, JanusGraphOperationStatus> resources = janusGraphDao + .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata); + + if (resources.isRight() && resources.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + log.debug("failed to get resources from graph with property name: {}", name); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resources.right().value())); + } + List resourceList = (resources.isLeft() ? resources.left().value() : null); + if (isNotEmpty(resourceList)) { + if (log.isDebugEnabled()) { + StringBuilder builder = new StringBuilder(); + for (GraphVertex resourceData : resourceList) { + builder.append(resourceData.getUniqueId() + "|"); + } + log.debug("resources with property name:{} exists in graph. found {}", name, builder); + } + return Either.left(false); + } else { + log.debug("resources with property name:{} does not exists in graph", name); + return Either.left(true); + } + + } + + // region - Component Update + + public Either overrideComponent(Resource newComponent, Resource oldComponent) { + + copyArtifactsToNewComponent(newComponent, oldComponent); + + Either componentVEither = janusGraphDao + .getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse); + if (componentVEither.isRight()) { + log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(componentVEither.right().value())); + } + GraphVertex componentv = componentVEither.left().value(); + Either parentVertexEither = janusGraphDao + .getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + if (parentVertexEither.isRight() && parentVertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertexEither.right().value())); + } + + Either deleteToscaComponent = deleteToscaElement(componentv); + if (deleteToscaComponent.isRight()) { + log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value()); + return Either.right(deleteToscaComponent.right().value()); + } + Either createToscaComponent = createToscaComponent(newComponent); + if (createToscaComponent.isRight()) { + log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value()); + return Either.right(createToscaComponent.right().value()); + } + Resource newElement = createToscaComponent.left().value(); + Either newVersionEither = janusGraphDao + .getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse); + if (newVersionEither.isRight()) { + log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(newVersionEither.right().value())); + } + if (parentVertexEither.isLeft()) { + GraphVertex previousVersionV = parentVertexEither.left().value(); + JanusGraphOperationStatus + createEdge = janusGraphDao + .createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null); + if (createEdge != JanusGraphOperationStatus.OK) { + log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge)); + } + } + return Either.left(newElement); + } + + void copyArtifactsToNewComponent(Resource newComponent, Resource oldComponent) { + // TODO - check if required + Map toscaArtifacts = oldComponent.getToscaArtifacts(); + if (toscaArtifacts != null && !toscaArtifacts.isEmpty()) { + toscaArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE)); + } + newComponent.setToscaArtifacts(toscaArtifacts); + + Map artifacts = oldComponent.getArtifacts(); + if (artifacts != null && !artifacts.isEmpty()) { + artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE)); + } + newComponent.setArtifacts(artifacts); + + Map depArtifacts = oldComponent.getDeploymentArtifacts(); + if (depArtifacts != null && !depArtifacts.isEmpty()) { + depArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE)); + } + newComponent.setDeploymentArtifacts(depArtifacts); + + newComponent.setGroups(oldComponent.getGroups()); + newComponent.setLastUpdateDate(null); + newComponent.setHighestVersion(true); + } + + public Either updateToscaElement(T componentToUpdate) { + return updateToscaElement(componentToUpdate, new ComponentParametersView()); + } + + public Either updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) { + String componentId = componentToUpdate.getUniqueId(); + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + } + GraphVertex elementV = getVertexEither.left().value(); + ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV); + + ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate); + Either updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult); + if (updateToscaElement.isRight()) { + log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value()); + return Either.right(updateToscaElement.right().value()); + } + return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value())); + } + + private Either getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag) { + return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView()); + } + + private Either getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag, ComponentParametersView filter) { + Either result; + + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(property, nodeName); + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either, JanusGraphOperationStatus> highestResources = janusGraphDao + .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag); + if (highestResources.isRight()) { + JanusGraphOperationStatus status = highestResources.right().value(); + log.debug("failed to find resource with name {}. status={} ", nodeName, status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + return result; + } + + List resources = highestResources.left().value(); + double version = 0.0; + GraphVertex highestResource = null; + for (GraphVertex vertex : resources) { + Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION); + double resourceVersion = Double.parseDouble((String) versionObj); + if (resourceVersion > version) { + version = resourceVersion; + highestResource = vertex; + } + } + return getToscaElementByOperation(highestResource, filter); + } + + // endregion + // region - Component Get By .. + private Either getLatestByName(GraphPropertyEnum property, String nodeName) { + return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata); + } + + public Either, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) { + + Either, StorageOperationStatus> result = null; + Either getComponentRes; + List components = new ArrayList<>(); + List componentVertices; + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName); + if (componentType != null) + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either, JanusGraphOperationStatus> getComponentsRes = janusGraphDao + .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + if (getComponentsRes.isRight()) { + JanusGraphOperationStatus status = getComponentsRes.right().value(); + log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + if (result == null) { + componentVertices = getComponentsRes.left().value(); + for (GraphVertex componentVertex : componentVertices) { + getComponentRes = getToscaElementByOperation(componentVertex); + if (getComponentRes.isRight()) { + log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value()); + result = Either.right(getComponentRes.right().value()); + break; + } + T componentBySystemName = getComponentRes.left().value(); + log.debug("Found component, id: {}", componentBySystemName.getUniqueId()); + components.add(componentBySystemName); + } + } + if (result == null) { + result = Either.left(components); + } + return result; + } + + public Either getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) { + return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll); + } + + public Either getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) { + Either result; + + Map hasProperties = new EnumMap<>(GraphPropertyEnum.class); + Map hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); + + hasProperties.put(GraphPropertyEnum.NAME, name); + hasProperties.put(GraphPropertyEnum.VERSION, version); + hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); + if (componentType != null) { + hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + } + Either, JanusGraphOperationStatus> getResourceRes = janusGraphDao + .getByCriteria(null, hasProperties, hasNotProperties, parseFlag); + if (getResourceRes.isRight()) { + JanusGraphOperationStatus status = getResourceRes.right().value(); + log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + return result; + } + return getToscaElementByOperation(getResourceRes.left().value().get(0)); + } + + public Either, StorageOperationStatus> getCatalogOrArchiveComponents(boolean isCatalog, List excludeTypes) { + List excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name())) + .collect(Collectors.toList()); + return topologyTemplateOperation.getElementCatalogData(isCatalog, excludedResourceTypes); + } + + // endregion + public Either, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List excludeTypes, boolean isHighestVersions) { + List components = new ArrayList<>(); + Either, StorageOperationStatus> catalogDataResult; + List toscaElements = new ArrayList<>(); + List excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name())) + .collect(Collectors.toList()); + + switch (componentType) { + case RESOURCE: + catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions); + if (catalogDataResult.isRight()) { + return Either.right(catalogDataResult.right().value()); + } + toscaElements = catalogDataResult.left().value(); + break; + case SERVICE: + if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) { + break; + } + catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions); + if (catalogDataResult.isRight()) { + return Either.right(catalogDataResult.right().value()); + } + toscaElements = catalogDataResult.left().value(); + break; + default: + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType); + return Either.right(StorageOperationStatus.BAD_REQUEST); + } + toscaElements.forEach(te -> { + T component = ModelConverter.convertFromToscaElement(te); + components.add(component); + }); + return Either.left(components); + } + + public Either, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) { + Either, StorageOperationStatus> allComponentsMarkedForDeletion; + switch (componentType) { + case RESOURCE: + allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType); + break; + case SERVICE: + case PRODUCT: + allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType); + break; + default: + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType); + return Either.right(StorageOperationStatus.BAD_REQUEST); + } + if (allComponentsMarkedForDeletion.isRight()) { + return Either.right(allComponentsMarkedForDeletion.right().value()); + } + List allMarked = allComponentsMarkedForDeletion.left().value(); + return Either.left(checkIfInUseAndDelete(allMarked)); + } + + private List checkIfInUseAndDelete(List allMarked) { + final List forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF); + List deleted = new ArrayList<>(); + + for (GraphVertex elementV : allMarked) { + boolean isAllowedToDelete = true; + + for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) { + Either belongingEdgeByCriteria = janusGraphDao + .getBelongingEdgeByCriteria(elementV, edgeLabelEnum, null); + if (belongingEdgeByCriteria.isLeft()){ + log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId()); + isAllowedToDelete = false; + break; + } + } + + if (isAllowedToDelete) { + Either deleteToscaElement = deleteToscaElement(elementV); + if (deleteToscaElement.isRight()) { + log.debug("Failed to delete marked element UniqueID {}, Name {}, error {}", elementV.getUniqueId(), elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value()); + continue; + } + deleted.add(elementV.getUniqueId()); + } + } + return deleted; + } + + public Either, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) { + Either, StorageOperationStatus> allComponentsMarkedForDeletion; + switch (componentType) { + case RESOURCE: + allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType); + break; + case SERVICE: + case PRODUCT: + allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType); + break; + default: + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType); + return Either.right(StorageOperationStatus.BAD_REQUEST); + } + if (allComponentsMarkedForDeletion.isRight()) { + return Either.right(allComponentsMarkedForDeletion.right().value()); + } + return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(GraphVertex::getUniqueId).collect(Collectors.toList())); + } + + // region - Component Update + public Either, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) { + + Either, StorageOperationStatus> result = null; + Either updateContainerComponentRes = null; + if (StringUtils.isEmpty(componentInstance.getIcon())) { + componentInstance.setIcon(origComponent.getIcon()); + } + String nameToFindForCounter = componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy ? componentInstance.getSourceModelName() + PROXY_SUFFIX : origComponent.getName(); + String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter); + Either, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), + ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user); + + if (addResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName()); + result = Either.right(addResult.right().value()); + } + if (result == null) { + updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId()); + if (updateContainerComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName()); + result = Either.right(updateContainerComponentRes.right().value()); + } + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value()); + String createdInstanceId = addResult.left().value().getRight(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName()); + result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId)); + } + return result; + } + + public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map resourcesInstancesMap, boolean allowDeleted) { + + StorageOperationStatus result = null; + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId()); + + Either metadataVertex = janusGraphDao + .getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll); + if (metadataVertex.isRight()) { + JanusGraphOperationStatus status = metadataVertex.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; + } + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + } + if (result == null) { + result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted); + } + return result; + } + + public Either, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) { + + Either, StorageOperationStatus> result = null; + + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName()); + componentInstance.setIcon(origComponent.getIcon()); + Either, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), + ModelConverter.convertToToscaElement(origComponent), componentInstance); + if (updateResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName()); + result = Either.right(updateResult.right().value()); + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft()); + String createdInstanceId = updateResult.left().value().getRight(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName()); + result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId)); + } + return result; + } + + public Either updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) { + return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView()); + } + + public Either updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, ComponentParametersView filter) { + + Either result = null; + + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName()); + + Either updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter); + if (updateResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName()); + result = Either.right(updateResult.right().value()); + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value()); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName()); + result = Either.left(updatedComponent); + } + return result; + } + // endregion + + public Either, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) { + + Either, StorageOperationStatus> result = null; + + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); + + Either, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId); + if (updateResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); + result = Either.right(updateResult.right().value()); + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft()); + String deletedInstanceId = updateResult.left().value().getRight(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName()); + result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId)); + } + return result; + } + + private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) { + Integer nextCounter = 0; + if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) { + String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName); + Integer maxCounter = getMaxCounterFromNamesAndIds(containerComponent, normalizedName); + if (maxCounter != null) { + nextCounter = maxCounter + 1; + } + } + return nextCounter.toString(); + } + + /** + * @return max counter of component instance Id's, null if not found + */ + private Integer getMaxCounterFromNamesAndIds(Component containerComponent, String normalizedName) { + List countersInNames = containerComponent.getComponentInstances().stream() + .filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)) + .map(ci -> ci.getNormalizedName().split(normalizedName)[1]) + .collect(Collectors.toList()); + List countersInIds = containerComponent.getComponentInstances().stream() + .filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)) + .map(ci -> ci.getUniqueId().split(normalizedName)[1]) + .collect(Collectors.toList()); + List namesAndIdsList = new ArrayList<>(countersInNames); + namesAndIdsList.addAll(countersInIds); + return getMaxInteger(namesAndIdsList); + } + + private Integer getMaxInteger(List counters) { + Integer maxCounter = 0; + Integer currCounter = null; + for (String counter : counters) { + try { + currCounter = Integer.parseInt(counter); + if (maxCounter < currCounter) { + maxCounter = currCounter; + } + } catch (NumberFormatException e) { + continue; + } + } + return currCounter == null ? null : maxCounter; + } + + public Either associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { + return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef); + + } + + public Either, StorageOperationStatus> createAndAssociateInputs(Map inputs, String componentId) { + + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue()))); + + StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId); + + if (StorageOperationStatus.OK == status) { + log.debug(COMPONENT_CREATED_SUCCESSFULLY); + List inputsResList = null; + if (inputsMap != null && !inputsMap.isEmpty()) { + inputsResList = inputsMap.values().stream() + .map(InputDefinition::new) + .collect(Collectors.toList()); + } + return Either.left(inputsResList); + } + return Either.right(status); + + } + + public Either, StorageOperationStatus> addInputsToComponent(Map inputs, String componentId) { + + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDefinition(e.getValue()))); + + StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME); + + if (StorageOperationStatus.OK == status) { + log.debug(COMPONENT_CREATED_SUCCESSFULLY); + List inputsResList = null; + if (inputsMap != null && !inputsMap.isEmpty()) { + inputsResList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList()); + } + return Either.left(inputsResList); + } + return Either.right(status); + + } + + /** + * Add data types into a Component. + * + * @param dataTypes datatypes to be added. the key should be each name of data type. + * @param componentId unique ID of Component. + * @return list of data types. + */ + public Either, StorageOperationStatus> addDataTypesToComponent(Map dataTypes, String componentId) { + + log.trace("#addDataTypesToComponent - enter, componentId={}", componentId); + + /* get component vertex */ + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + /* not found / error */ + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + } + GraphVertex vertex = getVertexEither.left().value(); + log.trace("#addDataTypesToComponent - get vertex ok"); + + // convert DataTypeDefinition to DataTypeDataDefinition + Map dataTypeDataMap = dataTypes.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> convertDataTypeToDataTypeData(e.getValue()))); + + // add datatype(s) to the Component. + // if child vertex does not exist, it will be created. + StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, + EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeDataMap, JsonPresentationFields.NAME); + + if (StorageOperationStatus.OK == status) { + log.debug(COMPONENT_CREATED_SUCCESSFULLY); + List inputsResList = null; + if (!dataTypes.isEmpty()) { + inputsResList = new ArrayList<>(dataTypes.values()); + } + return Either.left(inputsResList); + } + + log.trace("#addDataTypesToComponent - leave"); + return Either.right(status); + } + + private DataTypeDataDefinition convertDataTypeToDataTypeData(DataTypeDefinition dataType) { + DataTypeDataDefinition dataTypeData = new DataTypeDataDefinition(dataType); + if (CollectionUtils.isNotEmpty(dataType.getProperties())) { + List propertyDataList = dataType.getProperties().stream() + .map(PropertyDataDefinition::new).collect(Collectors.toList()); + dataTypeData.setPropertiesData(propertyDataList); + } + + // if "derivedFrom" data_type exists, copy the name to "derivedFromName" + if (dataType.getDerivedFrom() != null && StringUtils.isNotEmpty(dataType.getDerivedFrom().getName())) { + // if names are different, log it + if (!StringUtils.equals(dataTypeData.getDerivedFromName(), dataType.getDerivedFrom().getName())) { + log.debug("#convertDataTypeToDataTypeData - derivedFromName(={}) overwritten by derivedFrom.name(={})", + dataType.getDerivedFromName(), dataType.getDerivedFrom().getName()); + } + dataTypeData.setDerivedFromName(dataType.getDerivedFrom().getName()); + } + + // supply "name" field to toscaPresentationValue in each datatype object for DAO operations + dataTypeData.setToscaPresentationValue(JsonPresentationFields.NAME, dataType.getName()); + return dataTypeData; + } + + + public Either, StorageOperationStatus> getComponentInputs(String componentId) { + + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + + } + + Either toscaElement = + topologyTemplateOperation.getToscaElement(componentId); + if(toscaElement.isRight()) { + return Either.right(toscaElement.right().value()); + } + + TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement.left().value(); + + Map inputsMap = topologyTemplate.getInputs(); + + List inputs = new ArrayList<>(); + if(MapUtils.isNotEmpty(inputsMap)) { + inputs = + inputsMap.values().stream().map(p -> new InputDefinition(p)).collect(Collectors.toList()); + } + + return Either.left(inputs); + } + + public Either, StorageOperationStatus> updateInputsToComponent(List inputs, String componentId) { + + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + + } + + GraphVertex vertex = getVertexEither.left().value(); + List inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList()); + + StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME); + + if (StorageOperationStatus.OK == status) { + log.debug(COMPONENT_CREATED_SUCCESSFULLY); + List inputsResList = null; + if (inputsAsDataDef != null && !inputsAsDataDef.isEmpty()) { + inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList()); + } + return Either.left(inputsResList); + } + return Either.right(status); + + } + + // region - ComponentInstance + public Either>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map> instProperties, String componentId) { + + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map instPropsMap = new HashMap<>(); + if (instProperties != null) { + + MapPropertiesDataDefinition propertiesMap; + for (Entry> entry : instProperties.entrySet()) { + propertiesMap = new MapPropertiesDataDefinition(); + + propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e))); + + instPropsMap.put(entry.getKey(), propertiesMap); + } + } + + StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap); + + if (StorageOperationStatus.OK == status) { + log.debug(COMPONENT_CREATED_SUCCESSFULLY); + return Either.left(instProperties); + } + return Either.right(status); + + } + + /** + * saves the instInputs as the updated instance inputs of the component container in DB + */ + public Either>, StorageOperationStatus> updateComponentInstanceInputsToComponent(Map> instInputs, String componentId) { + if (instInputs == null || instInputs.isEmpty()) { + return Either.left(instInputs); + } + StorageOperationStatus status; + for (Entry> inputsPerIntance : instInputs.entrySet()) { + List toscaDataListPerInst = inputsPerIntance.getValue(); + List pathKeysPerInst = new ArrayList<>(); + pathKeysPerInst.add(inputsPerIntance.getKey()); + status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status); + return Either.right(status); + } + } + + return Either.left(instInputs); + } + + /** + * saves the instProps as the updated instance properties of the component container in DB + */ + public Either>, StorageOperationStatus> updateComponentInstancePropsToComponent(Map> instProps, String componentId) { + if (instProps == null || instProps.isEmpty()) { + return Either.left(instProps); + } + StorageOperationStatus status; + for (Entry> propsPerIntance : instProps.entrySet()) { + List toscaDataListPerInst = propsPerIntance.getValue(); + List pathKeysPerInst = new ArrayList<>(); + pathKeysPerInst.add(propsPerIntance.getKey()); + status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status); + return Either.right(status); + } + } + + return Either.left(instProps); + } + + public Either>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map> instInputs, String componentId) { + + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + + } + GraphVertex vertex = getVertexEither.left().value(); + Map instPropsMap = new HashMap<>(); + if (instInputs != null) { + + MapPropertiesDataDefinition propertiesMap; + for (Entry> entry : instInputs.entrySet()) { + propertiesMap = new MapPropertiesDataDefinition(); + + propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e))); + + instPropsMap.put(entry.getKey(), propertiesMap); + } + } + + StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap); + + if (StorageOperationStatus.OK == status) { + log.debug(COMPONENT_CREATED_SUCCESSFULLY); + return Either.left(instInputs); + } + return Either.right(status); + + } + + public Either>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map> instProperties) { + requireNonNull(instProperties); + StorageOperationStatus status; + for (Entry> entry : instProperties.entrySet()) { + List props = entry.getValue(); + String componentInstanceId = entry.getKey(); + if (!isEmpty(props)) { + for (ComponentInstanceInput property : props) { + List componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanceId); + Optional instanceProperty = componentInstancesInputs.stream() + .filter(p -> p.getName().equals(property.getName())) + .findAny(); + if (instanceProperty.isPresent()) { + status = updateComponentInstanceInput(containerComponent, componentInstanceId, property); + } else { + status = addComponentInstanceInput(containerComponent, componentInstanceId, property); + } + if (status != StorageOperationStatus.OK) { + log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanceId, status); + return Either.right(status); + } else { + log.trace("instance input {} for instance {} updated", property, componentInstanceId); + } + } + } + } + return Either.left(instProperties); + } + + public Either>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map> instProperties) { + requireNonNull(instProperties); + for (Entry> entry : instProperties.entrySet()) { + List props = entry.getValue(); + String componentInstanceId = entry.getKey(); + List originalComponentInstProps = + containerComponent.getComponentInstancesProperties().get(componentInstanceId); + Map> containerComponentCapabilities = containerComponent.getCapabilities(); + + if(isEmpty(props)) { + continue; + } + for (ComponentInstanceProperty property : props) { + StorageOperationStatus status = null; + String propertyParentUniqueId = property.getParentUniqueId(); + Optional + capPropDefinition = getPropertyCapability(propertyParentUniqueId, containerComponent); + if(capPropDefinition.isPresent() && MapUtils.isNotEmpty(containerComponentCapabilities)) { + status = populateAndUpdateInstanceCapProperty(containerComponent, componentInstanceId, + containerComponentCapabilities, property, capPropDefinition.get()); + } + if(status == null) { + status = updateOrAddComponentInstanceProperty(containerComponent, componentInstanceId, + originalComponentInstProps, property); + } + if(status != StorageOperationStatus.OK) { + return Either.right(status); + } + } + } + return Either.left(instProperties); + } + + private StorageOperationStatus populateAndUpdateInstanceCapProperty(Component containerComponent, String componentInstanceId, + Map> containerComponentCapabilities, + ComponentInstanceProperty property, + CapabilityDefinition capabilityDefinition) { + List capabilityDefinitions = containerComponentCapabilities.get(capabilityDefinition.getType()); + if(CollectionUtils.isEmpty(capabilityDefinitions)) { + return null; + } + Optional capDefToGetProp = capabilityDefinitions.stream() + .filter(cap -> cap.getUniqueId().equals(capabilityDefinition.getUniqueId()) && cap.getPath().size() == 1).findAny(); + if(capDefToGetProp.isPresent()) { + return updateInstanceCapabilityProperty(containerComponent, componentInstanceId, property, capDefToGetProp.get()); + } + return null; + } + + private static Optional getPropertyCapability(String propertyParentUniqueId, + Component containerComponent) { + + Map> componentCapabilities = containerComponent.getCapabilities(); + if(MapUtils.isEmpty(componentCapabilities)){ + return Optional.empty(); + } + List capabilityDefinitionList = componentCapabilities.values() + .stream().flatMap(Collection::stream).collect(Collectors.toList()); + if(CollectionUtils.isEmpty(capabilityDefinitionList)){ + return Optional.empty(); + } + return capabilityDefinitionList.stream() + .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId)) + .findAny(); + } + + private StorageOperationStatus updateOrAddComponentInstanceProperty(Component containerComponent, + String componentInstanceId, List originalComponentInstProps, + ComponentInstanceProperty property) + { + StorageOperationStatus status; + // check if the property already exists or not + Optional instanceProperty = originalComponentInstProps.stream() + .filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); + if (instanceProperty.isPresent()) { + status = updateComponentInstanceProperty(containerComponent, componentInstanceId, property); + } else { + status = addComponentInstanceProperty(containerComponent, componentInstanceId, property); + } + if (status != StorageOperationStatus.OK) { + log.debug("Failed to update instance property {} for instance {} error {} ", + property, componentInstanceId, status); + } + return status; + } + + public StorageOperationStatus updateInstanceCapabilityProperty(Component containerComponent, String componentInstanceId, + ComponentInstanceProperty property, + CapabilityDefinition capabilityDefinition) { + Optional fetchedCIOptional = containerComponent.getComponentInstanceById(componentInstanceId); + if(!fetchedCIOptional.isPresent()) { + return StorageOperationStatus.GENERAL_ERROR; + } + Either getComponentRes = + getToscaFullElement(fetchedCIOptional.get().getComponentUid()); + if(getComponentRes.isRight()) { + return StorageOperationStatus.GENERAL_ERROR; + } + Optional componentOptional = isNodeServiceProxy(getComponentRes.left().value()); + String propOwner; + if(!componentOptional.isPresent()) { + propOwner = componentInstanceId; + } else { + propOwner = fetchedCIOptional.get().getSourceModelUid(); + } + StorageOperationStatus status; + StringBuffer sb = new StringBuffer(componentInstanceId); + sb.append(ModelConverter.CAP_PROP_DELIM).append(propOwner).append(ModelConverter.CAP_PROP_DELIM) + .append(capabilityDefinition.getType()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getName()); + String capKey = sb.toString(); + status = updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceId, capKey, property); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to update instance capability property {} for instance {} error {} ", property, + componentInstanceId, status); + return status; + } + return StorageOperationStatus.OK; + } + + private Optional isNodeServiceProxy(Component component) { + if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) { + return Optional.empty(); + } + Resource resource = (Resource) component; + ResourceTypeEnum resType = resource.getResourceType(); + if(resType.equals(ResourceTypeEnum.ServiceProxy)) { + return Optional.of(component); + } + return Optional.empty(); + } + + public StorageOperationStatus associateDeploymentArtifactsToInstances(Map> instDeploymentArtifacts, String componentId, User user) { + + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map instArtMap = new HashMap<>(); + if (instDeploymentArtifacts != null) { + + MapArtifactDataDefinition artifactsMap; + for (Entry> entry : instDeploymentArtifacts.entrySet()) { + Map artList = entry.getValue(); + Map artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME); + + instArtMap.put(entry.getKey(), artifactsMap); + } + } + + return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap); + + } + + public StorageOperationStatus associateArtifactsToInstances(Map> instArtifacts, String componentId) { + + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map instArtMap = new HashMap<>(); + if (instArtifacts != null) { + + MapArtifactDataDefinition artifactsMap; + for (Entry> entry : instArtifacts.entrySet()) { + Map artList = entry.getValue(); + Map artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + artifactsMap = new MapArtifactDataDefinition(artifacts); + + instArtMap.put(entry.getKey(), artifactsMap); + } + } + + return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap); + + } + + public StorageOperationStatus associateInstAttributeToComponentToInstances(Map> instArttributes, String componentId) { + + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map instAttr = new HashMap<>(); + if (instArttributes != null) { + + MapPropertiesDataDefinition attributesMap; + for (Entry> entry : instArttributes.entrySet()) { + attributesMap = new MapPropertiesDataDefinition(); + attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e))); + instAttr.put(entry.getKey(), attributesMap); + } + } + + return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr); + + } + // endregion + + public StorageOperationStatus associateOrAddCalculatedCapReq(Map>> instCapabilties, Map>> instReg, String componentId) { + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()); + + } + + GraphVertex vertex = getVertexEither.left().value(); + + Map calcRequirements = new HashMap<>(); + + Map calcCapabilty = new HashMap<>(); + Map calculatedCapabilitiesProperties = new HashMap<>(); + if (instCapabilties != null) { + for (Entry>> entry : instCapabilties.entrySet()) { + + Map> caps = entry.getValue(); + Map mapToscaDataDefinition = new HashMap<>(); + for (Entry> instCapability : caps.entrySet()) { + mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()))); + } + + ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey()); + MapListCapabilityDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance); + + MapCapabilityProperty mapCapabilityProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true); + + calcCapabilty.put(entry.getKey().getUniqueId(), capMap); + calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabilityProperty); + } + } + + if (instReg != null) { + for (Entry>> entry : instReg.entrySet()) { + + Map> req = entry.getValue(); + Map mapToscaDataDefinition = new HashMap<>(); + for (Entry> instReq : req.entrySet()) { + mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList()))); + } + + MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey())); + + calcRequirements.put(entry.getKey().getUniqueId(), capMap); + } + } + + return topologyTemplateOperation.associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties); + } + + private Either, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map hasProps, Map hasNotProps) { + List services = new ArrayList<>(); + List states = new ArrayList<>(); + // include props + hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + // exclude props + states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + hasNotProps.put(GraphPropertyEnum.STATE, states); + hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); + hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true); + return fetchServicesByCriteria(services, hasProps, hasNotProps); + } + + private Either, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) { + List services = null; + Map hasProps = new EnumMap<>(GraphPropertyEnum.class); + Map hasNotProps = new EnumMap<>(GraphPropertyEnum.class); + fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType); + Either, JanusGraphOperationStatus> getRes = janusGraphDao + .getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata); + if (getRes.isRight()) { + if (getRes.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) { + return Either.left(new ArrayList<>()); + } else { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value())); + } + } + // region -> Fetch non checked-out services + if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals(SERVICE) && VertexTypeEnum.NODE_TYPE == vertexType) { + Either, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class)); + if (result.isRight()) { + log.debug("Failed to fetch services for"); + return Either.right(result.right().value()); + } + services = result.left().value(); + if (log.isTraceEnabled() && isEmpty(services)) + log.trace("No relevant services available"); + } + // endregion + List nonAbstractLatestComponents = new ArrayList<>(); + ComponentParametersView params = new ComponentParametersView(true); + params.setIgnoreAllVersions(false); + for (GraphVertex vertexComponent : getRes.left().value()) { + Either componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params); + if (componentRes.isRight()) { + log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value()); + return Either.right(componentRes.right().value()); + } else { + Component component = ModelConverter.convertFromToscaElement(componentRes.left().value()); + nonAbstractLatestComponents.add(component); + } + } + if (CollectionUtils.isNotEmpty(services)) { + nonAbstractLatestComponents.addAll(services); + } + return Either.left(nonAbstractLatestComponents); + } + + public Either getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) { + + Either result; + Map hasProperties = new EnumMap<>(GraphPropertyEnum.class); + hasProperties.put(GraphPropertyEnum.UUID, componentUuid); + if (isHighest != null) { + hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest); + } + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683 + + Either, JanusGraphOperationStatus> getRes = janusGraphDao + .getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag); + if (getRes.isRight()) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value())); + } else { + List latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList()); + ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0) + : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get(); + result = Either.left(latestVersion); + } + return result; + } + + public Either getComponentMetadata(String componentId) { + Either result; + Either getRes = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); + if (getRes.isRight()) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value())); + } else { + ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value()); + result = Either.left(componentMetadata); + } + return result; + } + + public Either, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, ComponentTypeEnum componentTypeEnum, + String internalComponentType, List componentUids) { + + List components = new ArrayList<>(); + if (componentUids == null) { + Either, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, componentTypeEnum, internalComponentType); + if (componentUidsRes.isRight()) { + return Either.right(componentUidsRes.right().value()); + } + componentUids = componentUidsRes.left().value(); + } + if (!isEmpty(componentUids)) { + for (String componentUid : componentUids) { + ComponentParametersView componentParametersView = buildComponentViewForNotAbstract(); + if ("vl".equalsIgnoreCase(internalComponentType)) { + componentParametersView.setIgnoreCapabilities(false); + componentParametersView.setIgnoreRequirements(false); + } + Either getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView); + if (getToscaElementRes.isRight()) { + log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value()); + return Either.right(getToscaElementRes.right().value()); + } + Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value()); + nullifySomeComponentProperties(component); + components.add(component); + } + } + return Either.left(components); + } + + public void nullifySomeComponentProperties(Component component) { + component.setContactId(null); + component.setCreationDate(null); + component.setCreatorUserId(null); + component.setCreatorFullName(null); + component.setLastUpdateDate(null); + component.setLastUpdaterUserId(null); + component.setLastUpdaterFullName(null); + component.setNormalizedName(null); + } + + private Either, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) { + + Either, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum, internalComponentType); + if (getToscaElementsRes.isRight()) { + return Either.right(getToscaElementsRes.right().value()); + } + List collection = getToscaElementsRes.left().value(); + List componentUids; + if (collection == null) { + componentUids = new ArrayList<>(); + } else { + componentUids = collection.stream() + .map(Component::getUniqueId) + .collect(Collectors.toList()); + } + return Either.left(componentUids); + } + + private ComponentParametersView buildComponentViewForNotAbstract() { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreCategories(false); + componentParametersView.setIgnoreAllVersions(false); + return componentParametersView; + } + + public Either validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { + Either result = validateComponentNameUniqueness(name, resourceType, componentType); + if (result.isLeft()) { + result = Either.left(!result.left().value()); + } + return result; + } + + public Either validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { + VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE; + String normalizedName = ValidationUtils.normaliseComponentName(name); + Map properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName); + properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + + Either, JanusGraphOperationStatus> vertexEither = janusGraphDao + .getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse); + if (vertexEither.isRight() && vertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value())); + } + List vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; + if (vertexList != null && !vertexList.isEmpty()) { + return Either.left(false); + } else { + return Either.left(true); + } + } + + private void fillNodeTypePropsMap(Map hasProps, Map hasNotProps, String internalComponentType) { + switch (internalComponentType.toLowerCase()) { + case "vf": + case "cvfc": + hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFCMT.name(), ResourceTypeEnum.Configuration.name())); + break; + case SERVICE: + case "pnf": + case "cr": + hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name())); + break; + case "vl": + hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name()); + break; + default: + break; + } + } + + private void fillTopologyTemplatePropsMap(Map hasProps, Map hasNotProps, ComponentTypeEnum componentTypeEnum) { + switch (componentTypeEnum) { + case RESOURCE: + hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + break; + case SERVICE: + hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + break; + default: + break; + } + hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name()); + } + + private void fillPropsMap(Map hasProps, Map hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) { + hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + + hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); + hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true); + hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + if (VertexTypeEnum.NODE_TYPE == internalVertexType) { + hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract); + if (internalComponentType != null) { + fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType); + } + } else { + fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum); + } + } + + private List getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) { + List internalVertexTypes = new ArrayList<>(); + if (ComponentTypeEnum.RESOURCE == componentTypeEnum) { + internalVertexTypes.add(VertexTypeEnum.NODE_TYPE); + } + if (ComponentTypeEnum.SERVICE == componentTypeEnum || SERVICE.equalsIgnoreCase(internalComponentType)) { + internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE); + } + return internalVertexTypes; + } + + public Either, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) { + List internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType); + List result = new ArrayList<>(); + for (VertexTypeEnum vertexType : internalVertexTypes) { + Either, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, componentTypeEnum, internalComponentType, vertexType); + if (listByVertexType.isRight()) { + return listByVertexType; + } + result.addAll(listByVertexType.left().value()); + } + return Either.left(result); + + } + + private Either, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid, Map additionalPropertiesToMatch) { + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + if (additionalPropertiesToMatch != null) { + propertiesToMatch.putAll(additionalPropertiesToMatch); + } + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + return getComponentListByUuid(componentUuid, propertiesToMatch); + } + + public Either getComponentByUuidAndVersion(String componentUuid, String version) { + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid); + propertiesToMatch.put(GraphPropertyEnum.VERSION, version); + + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + Either, JanusGraphOperationStatus> vertexEither = janusGraphDao + .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + if (vertexEither.isRight()) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value())); + } + + List vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; + if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) { + return Either.right(StorageOperationStatus.NOT_FOUND); + } + + return getToscaElementByOperation(vertexList.get(0)); + } + + public Either, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map additionalPropertiesToMatch) { + + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + + if (additionalPropertiesToMatch != null) { + propertiesToMatch.putAll(additionalPropertiesToMatch); + } + + propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid); + + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683 + + Either, JanusGraphOperationStatus> vertexEither = janusGraphDao + .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + + if (vertexEither.isRight()) { + log.debug("Couldn't fetch metadata for component with uuid {}, error: {}", componentUuid, vertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value())); + } + List vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; + + if (vertexList == null || vertexList.isEmpty()) { + log.debug("Component with uuid {} was not found", componentUuid); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + + ArrayList latestComponents = new ArrayList<>(); + for (GraphVertex vertex : vertexList) { + Either toscaElementByOperation = getToscaElementByOperation(vertex); + + if (toscaElementByOperation.isRight()) { + log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId()); + return Either.right(toscaElementByOperation.right().value()); + } + + latestComponents.add(toscaElementByOperation.left().value()); + } + + if (latestComponents.size() > 1) { + for (Component component : latestComponents) { + if (component.isHighestVersion()) { + LinkedList highestComponent = new LinkedList<>(); + highestComponent.add(component); + return Either.left(highestComponent); + } + } + } + + return Either.left(latestComponents); + } + + public Either getLatestServiceByUuid(String serviceUuid) { + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + return getLatestComponentByUuid(serviceUuid, propertiesToMatch); + } + + public Either getLatestComponentByUuid(String componentUuid) { + return getLatestComponentByUuid(componentUuid, null); + } + + public Either getLatestComponentByUuid(String componentUuid, Map propertiesToMatch) { + + Either, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch); + + if (latestVersionListEither.isRight()) { + return Either.right(latestVersionListEither.right().value()); + } + + List latestVersionList = latestVersionListEither.left().value(); + + if (latestVersionList.isEmpty()) { + return Either.right(StorageOperationStatus.NOT_FOUND); + } + Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get(); + + return Either.left(component); + } + + public Either, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) { + + List resources = new ArrayList<>(); + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract); + if (isHighest != null) { + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest); + } + propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either, JanusGraphOperationStatus> getResourcesRes = janusGraphDao + .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + + if (getResourcesRes.isRight()) { + log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResourcesRes.right().value())); + } + List resourceVerticies = getResourcesRes.left().value(); + for (GraphVertex resourceV : resourceVerticies) { + Either getResourceRes = getToscaElement(resourceV); + if (getResourceRes.isRight()) { + return Either.right(getResourceRes.right().value()); + } + resources.add(getResourceRes.left().value()); + } + return Either.left(resources); + } + + public Either getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) { + Either result; + + Map hasProperties = new EnumMap<>(GraphPropertyEnum.class); + Map hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); + + hasProperties.put(GraphPropertyEnum.NAME, name); + hasProperties.put(GraphPropertyEnum.VERSION, version); + hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); + + Either, JanusGraphOperationStatus> getResourceRes = janusGraphDao + .getByCriteria(null, hasProperties, hasNotProperties, parseFlag); + if (getResourceRes.isRight()) { + JanusGraphOperationStatus status = getResourceRes.right().value(); + log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + return result; + } + return getToscaElementByOperation(getResourceRes.left().value().get(0)); + } + + public Either getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) { + return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, JsonParseFlagEnum.ParseAll); + } + + public Either getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, JsonParseFlagEnum parseFlag) { + Map props = new EnumMap<>(GraphPropertyEnum.class); + Map propsHasNot = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.CSAR_UUID, csarUUID); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + if (componentType != null) { + props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + } + propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); + + GraphVertex resourceMetadataData = null; + List resourceMetadataDataList = null; + Either, JanusGraphOperationStatus> byCsar = janusGraphDao + .getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata); + if (byCsar.isRight()) { + if (JanusGraphOperationStatus.NOT_FOUND == byCsar.right().value()) { + // Fix Defect DE256036 + if (StringUtils.isEmpty(systemName)) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + JanusGraphOperationStatus.NOT_FOUND)); + } + + props.clear(); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + props.put(GraphPropertyEnum.SYSTEM_NAME, systemName); + Either, JanusGraphOperationStatus> bySystemname = janusGraphDao + .getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata); + if (bySystemname.isRight()) { + log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(bySystemname.right().value())); + } + if (bySystemname.left().value().size() > 2) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size()); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + resourceMetadataDataList = bySystemname.left().value(); + if (resourceMetadataDataList.size() == 1) { + resourceMetadataData = resourceMetadataDataList.get(0); + } else { + for (GraphVertex curResource : resourceMetadataDataList) { + if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) { + resourceMetadataData = curResource; + break; + } + } + } + if (resourceMetadataData == null) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions"); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) { + log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID); + // correct error will be returned from create flow. with all + // correct audit records!!!!! + return Either.right(StorageOperationStatus.NOT_FOUND); + } + return getToscaElement((String) resourceMetadataData.getUniqueId()); + } + } else { + resourceMetadataDataList = byCsar.left().value(); + if (resourceMetadataDataList.size() > 2) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size()); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + if (resourceMetadataDataList.size() == 1) { + resourceMetadataData = resourceMetadataDataList.get(0); + } else { + for (GraphVertex curResource : resourceMetadataDataList) { + if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) { + resourceMetadataData = curResource; + break; + } + } + } + if (resourceMetadataData == null) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions"); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + return getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag); + } + return null; + } + + public Either validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) { + + String currentTemplateNameChecked = templateNameExtends; + + while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) { + Either latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked); + + if (latestByToscaResourceName.isRight()) { + return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value()); + } + + Resource value = latestByToscaResourceName.left().value(); + + if (value.getDerivedFrom() != null) { + currentTemplateNameChecked = value.getDerivedFrom().get(0); + } else { + currentTemplateNameChecked = null; + } + } + + return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false); + } + + public Either, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) { + Map props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + Map propsHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + Either, JanusGraphOperationStatus> resourcesByTypeEither = janusGraphDao + .getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata); + + if (resourcesByTypeEither.isRight()) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resourcesByTypeEither.right().value())); + } + + List vertexList = resourcesByTypeEither.left().value(); + List components = new ArrayList<>(); + + for (GraphVertex vertex : vertexList) { + components.add(getToscaElementByOperation(vertex, filterBy).left().value()); + } + + return Either.left(components); + } + + public void commit() { + janusGraphDao.commit(); + } + + public Either updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) { + Either updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus); + if (updateDistributionStatus.isRight()) { + return Either.right(updateDistributionStatus.right().value()); + } + GraphVertex serviceV = updateDistributionStatus.left().value(); + service.setDistributionStatus(distributionStatus); + service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE)); + return Either.left(service); + } + + public Either updateComponentLastUpdateDateOnGraph(Component component) { + + Either result = null; + GraphVertex serviceVertex; + Either updateRes = null; + Either getRes = janusGraphDao + .getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata); + if (getRes.isRight()) { + JanusGraphOperationStatus status = getRes.right().value(); + log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + if (result == null) { + serviceVertex = getRes.left().value(); + long lastUpdateDate = System.currentTimeMillis(); + serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate); + component.setLastUpdateDate(lastUpdateDate); + updateRes = janusGraphDao.updateVertex(serviceVertex); + if (updateRes.isRight()) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateRes.right().value())); + } + } + if (result == null) { + result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value())); + } + return result; + } + + public HealingJanusGraphDao getJanusGraphDao() { + return janusGraphDao; + } + + public Either, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set distStatus) { + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + + return getServicesWithDistStatus(distStatus, propertiesToMatch); + } + + public Either, StorageOperationStatus> getServicesWithDistStatus(Set distStatus, Map additionalPropertiesToMatch) { + + List servicesAll = new ArrayList<>(); + + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) { + propertiesToMatch.putAll(additionalPropertiesToMatch); + } + + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + if (distStatus != null && !distStatus.isEmpty()) { + for (DistributionStatusEnum state : distStatus) { + propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name()); + Either, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch); + if (fetchServicesByCriteria.isRight()) { + return fetchServicesByCriteria; + } else { + servicesAll = fetchServicesByCriteria.left().value(); + } + } + return Either.left(servicesAll); + } else { + return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch); + } + } + + private Either, StorageOperationStatus> fetchServicesByCriteria(List servicesAll, Map propertiesToMatch, Map propertiesNotToMatch) { + Either, JanusGraphOperationStatus> getRes = janusGraphDao + .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + if (getRes.isRight()) { + if (getRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value())); + } + } else { + for (GraphVertex vertex : getRes.left().value()) { + Either getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true)); + + if (getServiceRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value()); + return Either.right(getServiceRes.right().value()); + } else { + servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value())); + } + } + } + return Either.left(servicesAll); + } + + public void rollback() { + janusGraphDao.rollback(); + } + + public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map finalDeploymentArtifacts) { + Map instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + + return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts); + } + + public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map artifacts) { + StorageOperationStatus status = StorageOperationStatus.OK; + if (MapUtils.isNotEmpty(artifacts)) { + Map instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts); + } + return status; + } + + public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) { + return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId); + } + + public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List groupInstances) { + return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances); + } + + public Either addPropertyToComponent(String propertyName, + PropertyDefinition newPropertyDefinition, + Component component) { + + Either result = null; + Either getUpdatedComponentRes = null; + newPropertyDefinition.setName(propertyName); + + StorageOperationStatus status = getToscaElementOperation(component) + .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the component {}. Status is {}. ", propertyName, component.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreProperties(false); + filter.setIgnoreInputs(false); + getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + PropertyDefinition newProperty = null; + List properties = + (getUpdatedComponentRes.left().value()).getProperties(); + if (CollectionUtils.isNotEmpty(properties)) { + Optional propertyOptional = properties.stream().filter( + propertyEntry -> propertyEntry.getName().equals(propertyName)).findAny(); + if (propertyOptional.isPresent()) { + newProperty = propertyOptional.get(); + } + } + if (newProperty == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the component {}. Status is {}. ", propertyName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } else { + result = Either.left(newProperty); + } + } + return result; + } + public StorageOperationStatus deletePropertyOfComponent(Component component, String propertyName) { + return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME); + } + + public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) { + return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME); + } + + public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) { + return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME); + } + + /** + * Deletes a data type from a component. + * @param component the container which has the data type + * @param dataTypeName the data type name to be deleted + * @return Operation result. + */ + public StorageOperationStatus deleteDataTypeOfComponent(Component component, String dataTypeName) { + return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeName, JsonPresentationFields.NAME); + } + + public Either updatePropertyOfComponent(Component component, + PropertyDefinition newPropertyDefinition) { + + Either getUpdatedComponentRes = null; + Either result = null; + StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreProperties(false); + getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + Optional newProperty = (getUpdatedComponentRes.left().value()) + .getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny(); + if (newProperty.isPresent()) { + result = Either.left(newProperty.get()); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + return result; + } + + + + public Either addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { + + Either getUpdatedComponentRes = null; + Either result = null; + if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) { + String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName()); + newAttributeDef.setUniqueId(attUniqueId); + } + + StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreAttributesFrom(false); + getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + Optional newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); + if (newAttribute.isPresent()) { + result = Either.left(newAttribute.get()); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + return result; + } + + public Either updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { + + Either getUpdatedComponentRes = null; + Either result = null; + StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreAttributesFrom(false); + getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + Optional newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); + if (newProperty.isPresent()) { + result = Either.left(newProperty.get()); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + return result; + } + + public Either updateInputOfComponent(Component component, InputDefinition newInputDefinition) { + + Either getUpdatedComponentRes = null; + Either result = null; + StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreInputs(false); + getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + Optional updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny(); + if (updatedInput.isPresent()) { + result = Either.left(updatedInput.get()); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + return result; + } + + /** + * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename + * + * @param containerComponent - container such as service + * @param componentInstance - context component + * @param componentInstanceId - id + * @return - successfull/failed status + **/ + public Either cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId) { + String uniqueId = componentInstance.getUniqueId(); + StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status); + return Either.right(status); + } + if (componentInstance.getGroupInstances() != null) { + status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances()); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status); + return Either.right(status); + } + } + return Either.left(status); + } + + public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List groups, Map> groupInstancesArtifacts) { + return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts); + } + + public Either, StorageOperationStatus> updateGroupsOnComponent(Component component, List updatedGroups) { + return groupsOperation.updateGroups(component, updatedGroups, true); + } + + public Either, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, String instanceId, List updatedGroupInstances) { + return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances); + } + + public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List groupInstances) { + return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances); + } + + public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map deploymentArtifacts) { + return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts); + } + + public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { + return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property); + } + + public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List properties) { + return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties); + } + + + public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { + return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property); + } + + public StorageOperationStatus updateComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property){ + return nodeTemplateOperation.updateComponentInstanceAttribute(containerComponent, componentInstanceId, property); + } + + public StorageOperationStatus addComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property){ + return nodeTemplateOperation.addComponentInstanceAttribute(containerComponent, componentInstanceId, property); + } + + public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { + return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property); + } + + public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List instanceInputs) { + return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs); + } + + public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { + return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property); + } + + public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) { + this.nodeTypeOperation = nodeTypeOperation; + } + + public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) { + this.topologyTemplateOperation = topologyTemplateOperation; + } + + public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, List inputsToDelete) { + return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList())); + } + + public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityUniqueId, ComponentInstanceProperty property) { + return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityUniqueId, property); + } + + public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) { + return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId) + .map(instanceCapProps -> topologyTemplateOperation.updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps)) + .orElse(StorageOperationStatus.NOT_FOUND); + } + + public StorageOperationStatus updateComponentInstanceInterfaces(Component containerComponent, String componentInstanceUniqueId) { + MapInterfaceDataDefinition mapInterfaceDataDefinition = + convertComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId); + return topologyTemplateOperation + .updateComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId, mapInterfaceDataDefinition); + } + + public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) { + Map mapCapabiltyPropertyMap = + convertComponentCapabilitiesProperties(containerComponent); + return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap); + } + + public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) { + StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES); + if (status == StorageOperationStatus.OK) { + status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS); + } + if (status == StorageOperationStatus.OK) { + status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES); + } + return status; + } + + public Either shouldUpgradeToLatestDerived(Resource clonedResource) { + String componentId = clonedResource.getUniqueId(); + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + + } + GraphVertex nodeTypeV = getVertexEither.left().value(); + + ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource); + + Either shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV); + if (shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value()) { + log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + } + if (shouldUpdateDerivedVersion.isLeft()) { + return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value())); + } + return Either.left(clonedResource); + } + + /** + * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId + */ + public Either, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) { + return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId); + } + + private MapInterfaceDataDefinition convertComponentInstanceInterfaces(Component currComponent, + String componentInstanceId) { + MapInterfaceDataDefinition mapInterfaceDataDefinition = new MapInterfaceDataDefinition(); + List componentInterface = currComponent.getComponentInstancesInterfaces().get(componentInstanceId); + + if(CollectionUtils.isNotEmpty(componentInterface)) { + componentInterface.stream().forEach(interfaceDef -> mapInterfaceDataDefinition.put + (interfaceDef.getUniqueId(), interfaceDef)); + } + + return mapInterfaceDataDefinition; + } + + private Map convertComponentCapabilitiesProperties(Component currComponent) { + Map map = ModelConverter.extractCapabilityPropertiesFromGroups(currComponent.getGroups(), true); + map.putAll(ModelConverter.extractCapabilityProperteisFromInstances(currComponent.getComponentInstances(), true)); + return map; + } + + private Optional convertComponentInstanceProperties(Component component, String instanceId) { + return component.fetchInstanceById(instanceId) + .map(ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), instanceId)); + } + + public Either associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) { + Either result = null; + Either getVertexEither; + getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); + if (getVertexEither.isRight()) { + log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + } else { + if (getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE) { + log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel()); + result = Either.right(StorageOperationStatus.BAD_REQUEST); + } + } + if (result == null) { + StorageOperationStatus status = topologyTemplateOperation.addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + } + if (result == null) { + result = Either.left(policyDefinition); + } + return result; + } + + public StorageOperationStatus associatePoliciesToComponent(String componentId, List policies) { + log.debug("#associatePoliciesToComponent - associating policies for component {}.", componentId); + return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata) + .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies), + DaoStatusConverter::convertJanusGraphStatusToStorageStatus); + } + + public Either updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition) { + Either result = null; + Either getVertexEither; + getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + } + if (result == null) { + StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + } + if (result == null) { + result = Either.left(policyDefinition); + } + return result; + } + + public StorageOperationStatus updatePoliciesOfComponent(String componentId, List policyDefinition) { + log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId); + return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse) + .right() + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus) + .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition), + err -> err); + } + + public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) { + StorageOperationStatus status = null; + Either getVertexEither = janusGraphDao + .getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + status = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()); + } + if (status == null) { + status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId); + } + return status; + } + + public boolean canAddGroups(String componentId) { + GraphVertex vertex = janusGraphDao.getVertexById(componentId) + .left() + .on(this::onJanusGraphError); + return topologyTemplateOperation.hasEdgeOfType(vertex, EdgeLabelEnum.GROUPS); + } + + GraphVertex onJanusGraphError(JanusGraphOperationStatus toe) { + throw new StorageException( + DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toe)); + } + + public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId){ + topologyTemplateOperation + .updateNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId)); + } + + public void revertNamesOfCalculatedCapabilitiesRequirements(String componentId) { + topologyTemplateOperation + .revertNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId)); + } + + private TopologyTemplate getTopologyTemplate(String componentId) { + return (TopologyTemplate)topologyTemplateOperation + .getToscaElement(componentId, getFilterComponentWithCapProperties()) + .left() + .on(this::throwStorageException); + } + + private ComponentParametersView getFilterComponentWithCapProperties() { + ComponentParametersView filter = new ComponentParametersView(); + filter.setIgnoreCapabiltyProperties(false); + return filter; + } + + private ToscaElement throwStorageException(StorageOperationStatus status) { + throw new StorageException(status); + } + + public Either isComponentInUse(String componentId) { + final List forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF); + Either vertexById = janusGraphDao.getVertexById(componentId); + if (vertexById.isLeft()) { + for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) { + Iterator edgeItr = vertexById.left().value().getVertex().edges(Direction.IN, edgeLabelEnum.name()); + if(edgeItr != null && edgeItr.hasNext()){ + return Either.left(true); + } + } + } + return Either.left(false); + } + + public Either, StorageOperationStatus> getComponentListByInvariantUuid + (String componentInvariantUuid, Map additionalPropertiesToMatch) { + + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + if (MapUtils.isNotEmpty(additionalPropertiesToMatch)) { + propertiesToMatch.putAll(additionalPropertiesToMatch); + } + propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, componentInvariantUuid); + + Either, JanusGraphOperationStatus> vertexEither = janusGraphDao + .getByCriteria(null, propertiesToMatch, JsonParseFlagEnum.ParseMetadata); + + if (vertexEither.isRight()) { + log.debug("Couldn't fetch metadata for component with type {} and invariantUUId {}, error: {}", componentInvariantUuid, vertexEither.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value())); + } + List vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; + + if (vertexList == null || vertexList.isEmpty()) { + log.debug("Component with invariantUUId {} was not found", componentInvariantUuid); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + + ArrayList components = new ArrayList<>(); + for (GraphVertex vertex : vertexList) { + Either toscaElementByOperation = getToscaElementByOperation(vertex); + if (toscaElementByOperation.isRight()) { + log.debug("Could not fetch the following Component by Invariant UUID {}", vertex.getUniqueId()); + return Either.right(toscaElementByOperation.right().value()); + } + components.add(toscaElementByOperation.left().value()); + } + + return Either.left(components); + } + + public Either, StorageOperationStatus> getParentComponents(String componentId) { + List parentComponents = new ArrayList<>(); + final List relationEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF); + Either vertexById = janusGraphDao.getVertexById(componentId); + if (vertexById.isLeft()) { + for (EdgeLabelEnum edgeLabelEnum : relationEdgeLabelEnums) { + Either parentVertexEither = janusGraphDao + .getParentVertex(vertexById.left().value(), edgeLabelEnum, JsonParseFlagEnum.ParseJson); + if(parentVertexEither.isLeft()){ + Either componentEither = getToscaElement(parentVertexEither.left().value().getUniqueId()); + if(componentEither.isLeft()){ + parentComponents.add(componentEither.left().value()); + } + } + } + } + return Either.left(parentComponents); + } + public void updateCapReqPropertiesOwnerId(String componentId) { + topologyTemplateOperation + .updateCapReqPropertiesOwnerId(componentId, getTopologyTemplate(componentId)); + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperation.java new file mode 100644 index 0000000000..3596fff3ec --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperation.java @@ -0,0 +1,231 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import org.janusgraph.core.JanusGraphVertex; +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.model.ComponentDependency; +import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Component +public class UpgradeOperation extends BaseOperation { + private static final Logger log = Logger.getLogger(UpgradeOperation.class.getName()); + + public Either, StorageOperationStatus> getComponentDependencies(String componentId) { + Either vertexById = janusGraphDao.getVertexById(componentId); + if (vertexById.isRight()) { + log.debug("Failed to fetch vertex with id {} error {}", componentId, vertexById.right().value()); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexById.right().value())); + } + List dependencies = new ArrayList<>(); + + GraphVertex vertex = vertexById.left().value(); + + StorageOperationStatus status = fillDependenciesByVertex(componentId, dependencies, vertex); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + + GraphVertex vertexToStart = vertex; + Function> getNextElement = vertexP -> janusGraphDao + .getParentVertex(vertexP, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll); + status = handleVersionChain(componentId, dependencies, vertex, getNextElement); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + vertex = vertexToStart; + getNextElement = vertexP -> janusGraphDao + .getChildVertex(vertexP, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll); + status = handleVersionChain(componentId, dependencies, vertex, getNextElement); + + return status == StorageOperationStatus.OK ? Either.left(dependencies) : Either.right(status); + } + + private StorageOperationStatus handleVersionChain(String componentId, List dependencies, GraphVertex vertexToStart, Function> getNextElement) { + + StorageOperationStatus status; + boolean nextInChain = true; + GraphVertex vertex = vertexToStart; + Either nextInChainV; + while (nextInChain) { + nextInChainV = getNextElement.apply(vertex); + if (nextInChainV.isRight()) { + nextInChain = false; + } else { + vertex = nextInChainV.left().value(); + status = fillDependenciesByVertex(componentId, dependencies, vertex); + if (status != StorageOperationStatus.OK) { + return status; + } + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus fillDependenciesByVertex(String componentId, List dependencies, GraphVertex vertex) { + StorageOperationStatus status = StorageOperationStatus.OK; + if ( needToAddToDepenedency(vertex) ) { + ComponentDependency dependency = fillDataFromVertex(vertex, null, null); + + List dependList = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF); + for (EdgeLabelEnum label : dependList) { + status = fillDependenciesByLabel(componentId, vertex, dependency, label); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to create dependencies for component {} and label {} status {}", componentId, label, status); + break; + } + } + if (status == StorageOperationStatus.OK) { + dependencies.add(dependency); + } + } + return status; + } + private boolean needToAddToDepenedency(GraphVertex vertex){ + Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED); + Boolean isArchived = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED); + return ( isDeleted == Boolean.TRUE || isArchived == Boolean.TRUE) ? false : true; + } + + private StorageOperationStatus fillDependenciesByLabel(String componentId, GraphVertex vertex, ComponentDependency dependency, EdgeLabelEnum label) { + Either, JanusGraphOperationStatus> parentVertecies = janusGraphDao + .getParentVertecies(vertex, label, JsonParseFlagEnum.ParseAll); + if (parentVertecies.isRight() && parentVertecies.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + log.debug("Failed to fetch parent verticies by label INSTANCE_OF for vertex with id {} error {}", componentId, parentVertecies.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertecies.right().value()); + } + if (parentVertecies.isLeft()) { + List existIn = new ArrayList<>( ); + parentVertecies.left().value().forEach(v -> handleHighestVersion(vertex, label, existIn, v) ); + dependency.addDependencies(existIn); + } + return StorageOperationStatus.OK; + } + + private void handleHighestVersion(GraphVertex vertexOrigin, EdgeLabelEnum label, List exisIn, GraphVertex containerVertex) { + Boolean isHighest = (Boolean) containerVertex.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); + if ( isHighest && needToAddToDepenedency(containerVertex) ) { + JanusGraphVertex janusGraphVertex = containerVertex.getVertex(); + Iterator edges = janusGraphVertex.edges(Direction.OUT, EdgeLabelEnum.VERSION.name()); + //verify that it is a last version - highest by version number + if ( edges == null || !edges.hasNext() ){ + ComponentDependency container = fillDataFromVertex(containerVertex, vertexOrigin.getUniqueId(), label); + boolean addToDependency = true; + if (label == EdgeLabelEnum.ALLOTTED_OF) { + //in case of not full allotted chain not add to dependency list + addToDependency = findAllottedChain(containerVertex, container); + } + if ( addToDependency ){ + exisIn.add(container); + } + } + } + } + + private boolean findAllottedChain(GraphVertex vertex, ComponentDependency container) { + Either, JanusGraphOperationStatus> parentVertecies = janusGraphDao + .getParentVertecies(vertex, EdgeLabelEnum.INSTANCE_OF, JsonParseFlagEnum.ParseAll); + if (parentVertecies.isLeft()) { + List existIn = new ArrayList<>(); + parentVertecies.left().value().forEach(v -> { + Boolean isHighest = (Boolean) v.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); + if ( isHighest && needToAddToDepenedency(v) ) { + JanusGraphVertex janusGraphVertex = v.getVertex(); + Iterator edges = janusGraphVertex.edges(Direction.OUT, EdgeLabelEnum.VERSION.name()); + //verify that it is a last version - highest by version number + if ( edges == null || !edges.hasNext() ){ + ComponentDependency parentContainer = fillDataFromVertex(v, vertex.getUniqueId(), EdgeLabelEnum.INSTANCE_OF); + existIn.add(parentContainer); + } + } + }); + if ( !existIn.isEmpty() ){ + container.setDependencies(existIn); + return true; + } + } + return false; + } + + private ComponentDependency fillDataFromVertex(GraphVertex v, String originId, EdgeLabelEnum edgeLabel) { + ComponentDependency container = new ComponentDependency(); + container.setName((String) v.getMetadataProperty(GraphPropertyEnum.NAME)); + container.setVersion((String) v.getMetadataProperty(GraphPropertyEnum.VERSION)); + container.setUniqueId(v.getUniqueId()); + container.setType((String) v.getMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE)); + container.setIcon((String) v.getJsonMetadataField(JsonPresentationFields.ICON)); + container.setState((String) v.getMetadataProperty(GraphPropertyEnum.STATE)); + + if (edgeLabel == EdgeLabelEnum.PROXY_OF || edgeLabel == EdgeLabelEnum.ALLOTTED_OF) { + findInstanceNames(v, originId, edgeLabel, container); + } + return container; + } + + private void findInstanceNames(GraphVertex v, String originId, EdgeLabelEnum edgeLabel, ComponentDependency container) { + Map jsonComposition = (Map) v.getJson(); + CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + JanusGraphVertex vertex = v.getVertex(); + Iterator edges = vertex.edges(Direction.OUT, edgeLabel.name()); + while (edges != null && edges.hasNext()) { + Edge edge = edges.next(); + JanusGraphVertex inVertex = (JanusGraphVertex) edge.inVertex(); + String id = (String) janusGraphDao.getProperty(inVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()); + if (id.equals(originId)) { + List instanceOnEdge = (List) janusGraphDao + .getProperty(edge, EdgePropertyEnum.INSTANCES); + Map componentInstances = compositionDataDefinition.getComponentInstances(); + + if (componentInstances != null) { + List ciNames = componentInstances + .values() + .stream() + .filter(ci -> instanceOnEdge.contains(ci.getUniqueId())) + .map(ComponentInstanceDataDefinition::getName) + .collect(Collectors.toList()); + if (ciNames != null && !ciNames.isEmpty()) { + container.setInstanceNames(ciNames); + break; + } + } + } + } + } + + public List getInstanceIdFromAllottedEdge(String resourceId, String serviceInvariantUUID) { + Either vertexById = janusGraphDao.getVertexById(resourceId); + if ( vertexById.isLeft() ){ + GraphVertex vertexG = vertexById.left().value(); + JanusGraphVertex vertex = vertexG.getVertex(); + Iterator edges = vertex.edges(Direction.OUT, EdgeLabelEnum.ALLOTTED_OF.name()); + while ( edges != null && edges.hasNext() ){ + Edge edge = edges.next(); + JanusGraphVertex inVertex = (JanusGraphVertex)edge.inVertex(); + String vertexInInvUUID = (String) janusGraphDao + .getProperty(inVertex, GraphPropertyEnum.INVARIANT_UUID.getProperty()); + if ( vertexInInvUUID.equals(serviceInvariantUUID) ){ + return (List) janusGraphDao.getProperty(edge, EdgePropertyEnum.INSTANCES) ; + } + } + } + return new ArrayList<>(); + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityRequirementNameResolver.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityRequirementNameResolver.java new file mode 100644 index 0000000000..c4b7882e50 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityRequirementNameResolver.java @@ -0,0 +1,394 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.utils; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.utils.ComponentUtilities; +import org.openecomp.sdc.common.log.wrappers.Logger; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; +import static org.apache.commons.lang3.StringUtils.isBlank; + +public class CapabilityRequirementNameResolver { + + private static final Logger log = Logger.getLogger(CapabilityRequirementNameResolver.class); + private static final String PATH_DELIMITER = "."; + + private CapabilityRequirementNameResolver() { + } + + public static void updateNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId, String ownerName, Function originGetter) { + Map componentCacheToRepair = new HashMap<>(); + log.debug("#updateNamesOfCalculatedCapabilitiesRequirements"); + updateCalculatedCapabilitiesNames(componentCacheToRepair, toscaElement, ownerId, ownerName, originGetter); + updateCalculatedRequirementsNames(componentCacheToRepair, toscaElement, ownerId, ownerName, originGetter); + updateCalculatedCapabilitiesPropertiesKeys(toscaElement, ownerId); + } + + private static void updateCalculatedCapabilitiesPropertiesKeys(TopologyTemplate toscaElement, String ownerId) { + if (calCapPropertiesExist(toscaElement, ownerId)) { + MapCapabilityProperty newProps = new MapCapabilityProperty(); + toscaElement.getCalculatedCapabilitiesProperties().get(ownerId) + .getMapToscaDataDefinition() + .forEach((k, v) -> updateAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps)); + if (MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) { + toscaElement.getCalculatedCapabilitiesProperties().put(ownerId, newProps); + } + } + } + + private static boolean calCapPropertiesExist(TopologyTemplate toscaElement, String ownerId) { + return toscaElement.getCalculatedCapabilitiesProperties() != null + && toscaElement.getCalculatedCapabilitiesProperties().get(ownerId) != null + && MapUtils.isNotEmpty(toscaElement.getCalculatedCapabilitiesProperties().get(ownerId).getMapToscaDataDefinition()) + && capabilitiesExist(toscaElement, ownerId); + } + + private static void updateCalculatedRequirementsNames(Map componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, String ownerName, Function originGetter) { + if (requirementsExist(toscaElement, ownerId)) { + String prefix = ownerName + PATH_DELIMITER; + repairReqNames(componentCacheToRepair, toscaElement, ownerId, originGetter); + toscaElement.getCalculatedRequirements().get(ownerId) + .getMapToscaDataDefinition().values().stream() + .flatMap(l -> l.getListToscaDataDefinition().stream()) + .forEach(r -> { + if (isRequiredToRepair(r.getName())) { + BeEcompErrorManager.getInstance() + .logBeComponentMissingError("The empty name of the requirement was found. Id: " + r.getUniqueId() + ", ownerId: " + ownerId + ", ownerName: " + ownerName, + toscaElement.getComponentType().getValue(), toscaElement.getName()); + } + if (ComponentUtilities.isNotUpdatedCapReqName(prefix, r.getName(), r.getPreviousName())) { + if (StringUtils.isNotEmpty(r.getPreviousName())) { + r.setParentName(r.getPreviousName()); + } + r.setPreviousName(r.getName()); + } + r.setName(prefix + r.getPreviousName()); + }); + } + } + + private static boolean requirementsExist(TopologyTemplate toscaElement, String ownerId) { + return toscaElement.getCalculatedRequirements() != null + && toscaElement.getCalculatedRequirements().get(ownerId) != null + && MapUtils.isNotEmpty(toscaElement.getCalculatedRequirements().get(ownerId).getMapToscaDataDefinition()); + } + + private static void updateCalculatedCapabilitiesNames(Map componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, String ownerName, Function originGetter) { + if (capabilitiesExist(toscaElement, ownerId)) { + String prefix = ownerName + PATH_DELIMITER; + repairCapNames(componentCacheToRepair, toscaElement, ownerId, originGetter); + toscaElement.getCalculatedCapabilities().get(ownerId) + .getMapToscaDataDefinition().values().stream() + .flatMap(l -> l.getListToscaDataDefinition().stream()) + .forEach(c -> { + if (isRequiredToRepair(c.getName())) { + BeEcompErrorManager.getInstance() + .logBeComponentMissingError("The empty name of the capability was found. Id: " + c.getUniqueId() + ", ownerId: " + ownerId + ", ownerName: " + ownerName, + toscaElement.getComponentType().getValue(), toscaElement.getName()); + } + if (ComponentUtilities.isNotUpdatedCapReqName(prefix, c.getName(), c.getPreviousName())) { + if (StringUtils.isNotEmpty(c.getPreviousName())) { + c.setParentName(c.getPreviousName()); + } + c.setPreviousName(c.getName()); + } + c.setName(prefix + c.getPreviousName()); + }); + } + } + + private static boolean capabilitiesExist(TopologyTemplate toscaElement, String ownerId) { + return toscaElement.getCalculatedCapabilities() != null + && toscaElement.getCalculatedCapabilities().get(ownerId) != null + && MapUtils.isNotEmpty(toscaElement.getCalculatedCapabilities().get(ownerId).getMapToscaDataDefinition()); + } + + private static void repairCapNames(Map componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, Function originGetter) { + log.debug("#repairCapNames"); + boolean emptyNameFound = toscaElement.getCalculatedCapabilities() != null + && toscaElement.getCalculatedCapabilities().get(ownerId) != null + && toscaElement.getCalculatedCapabilities().get(ownerId).getMapToscaDataDefinition() != null + && toscaElement.getCalculatedCapabilities().get(ownerId).getMapToscaDataDefinition().values() + .stream() + .filter(Objects::nonNull) + .flatMap(l -> l.getListToscaDataDefinition().stream()) + .filter(Objects::nonNull) + .anyMatch(c -> isRequiredToRepair(c.getName())); + + ComponentInstanceDataDefinition instance = toscaElement.getComponentInstances() != null ? + toscaElement.getComponentInstances().get(ownerId) : null; + if (instance != null && emptyNameFound) { + log.debug("#repairCapNames - Going to repair the name of the capability for the owner {}. ", ownerId); + toscaElement.getCalculatedCapabilities().get(ownerId) + .getMapToscaDataDefinition().values() + .stream() + .flatMap(l -> l.getListToscaDataDefinition().stream()) + .forEach(c -> repairCapName(componentCacheToRepair, instance, c, originGetter)); + } + } + + private static void repairReqNames(Map componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, Function originGetter) { + log.debug("#repairReqNames"); + boolean emptyNameFound = toscaElement.getCalculatedRequirements() != null + && toscaElement.getCalculatedRequirements().get(ownerId) != null + && toscaElement.getCalculatedRequirements().get(ownerId).getMapToscaDataDefinition() != null + && toscaElement.getCalculatedRequirements().get(ownerId).getMapToscaDataDefinition().values() + .stream() + .filter(Objects::nonNull) + .flatMap(l -> l.getListToscaDataDefinition().stream()) + .filter(Objects::nonNull) + .anyMatch(r -> isRequiredToRepair(r.getName())); + + ComponentInstanceDataDefinition instance = toscaElement.getComponentInstances() != null ? + toscaElement.getComponentInstances().get(ownerId) : null; + if (instance != null && emptyNameFound) { + log.debug("#repairReqNames - Going to repair the name of the requirement for the owner {}. ", ownerId); + toscaElement.getCalculatedRequirements().get(ownerId) + .getMapToscaDataDefinition().values() + .stream() + .flatMap(l -> l.getListToscaDataDefinition().stream()) + .forEach(r -> repairReqName(componentCacheToRepair, instance, r, originGetter)); + } + } + + private static void repairCapName(Map componentCacheToRepair, ComponentInstanceDataDefinition instance, CapabilityDataDefinition capability, Function originGetter) { + if (isRequiredToRepair(capability.getName())) { + log.debug("#repairTopologyTemplateCapName - Going to build the name for the capability: ", capability.getUniqueId()); + buildSetCapName(componentCacheToRepair, capability, instance, originGetter); + } + } + + private static boolean isRequiredToRepair(String name) { + boolean isRequiredToRepair = StringUtils.isEmpty(name) || name.endsWith(".null") || name.contains(".null."); + if (isRequiredToRepair) { + log.debug("#isRequiredToRepair - The name {} should be repaired. ", name); + } else { + log.debug("#isRequiredToRepair - The name {} should not be repaired. ", name); + } + return isRequiredToRepair; + } + + private static void repairReqName(Map componentCacheToRepair, ComponentInstanceDataDefinition instance, RequirementDataDefinition requirement, Function originGetter) { + if (isRequiredToRepair(requirement.getName())) { + log.debug("#repairTopologyTemplateCapName - Going to build the name for the requirement: ", requirement.getUniqueId()); + buildSetReqName(componentCacheToRepair, requirement, instance, originGetter); + } + } + + private static void updateAndAddCalculatedCapabilitiesProperties(String stringKey, MapPropertiesDataDefinition properties, MapListCapabilityDataDefinition calculatedCapabilities, MapCapabilityProperty newProps) { + String[] key = stringKey.split(ModelConverter.CAP_PROP_DELIM); + String capType = key[key.length - 2]; + String capName = key[key.length - 1]; + Optional foundCapOpt = calculatedCapabilities.getMapToscaDataDefinition().get(capType) + .getListToscaDataDefinition().stream() + .filter(c -> StringUtils.isNotEmpty(c.getPreviousName()) && c.getPreviousName().equals(capName)) + .findFirst(); + foundCapOpt.ifPresent(capabilityDataDefinition -> key[key.length - 1] = capabilityDataDefinition.getName()); + newProps.put(buildCaLCapPropKey(key), properties); + } + + public static void revertNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId, Function originGetter) { + Map componentCacheToRepair = new HashMap<>(); + log.debug("#revertNamesOfCalculatedCapabilitiesRequirements"); + revertCalculatedCapabilitiesPropertiesKeys(componentCacheToRepair, toscaElement, ownerId, originGetter); + revertCalculatedCapabilitiesNames(toscaElement, ownerId); + revertCalculatedRequirementsNames(componentCacheToRepair, toscaElement, ownerId, originGetter); + } + + private static void revertCalculatedCapabilitiesPropertiesKeys(Map componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, Function originGetter) { + repairCapNames(componentCacheToRepair, toscaElement, ownerId, originGetter); + if (calCapPropertiesExist(toscaElement, ownerId)) { + MapCapabilityProperty newProps = new MapCapabilityProperty(); + toscaElement.getCalculatedCapabilitiesProperties().get(ownerId) + .getMapToscaDataDefinition() + .forEach((k, v) -> revertAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps)); + if (MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) { + toscaElement.getCalculatedCapabilitiesProperties().put(ownerId, newProps); + } + } + } + + private static void revertCalculatedRequirementsNames(Map componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, Function originGetter) { + repairReqNames(componentCacheToRepair, toscaElement, ownerId, originGetter); + if (requirementsExist(toscaElement, ownerId)) { + toscaElement.getCalculatedRequirements().get(ownerId) + .getMapToscaDataDefinition().values().stream() + .flatMap(l -> l.getListToscaDataDefinition().stream()) + .forEach(CapabilityRequirementNameResolver::revertReqNames); + } + } + + private static void revertReqNames(RequirementDataDefinition requirement) { + if (StringUtils.isNotEmpty(requirement.getPreviousName())) { + requirement.setName(requirement.getPreviousName()); + requirement.setPreviousName(requirement.getParentName()); + } + } + + private static void revertCalculatedCapabilitiesNames(TopologyTemplate toscaElement, String ownerId) { + if (capabilitiesExist(toscaElement, ownerId)) { + toscaElement.getCalculatedCapabilities().get(ownerId) + .getMapToscaDataDefinition().values().stream() + .flatMap(l -> l.getListToscaDataDefinition().stream()) + .forEach(CapabilityRequirementNameResolver::revertCapNames); + } + } + + private static void revertCapNames(CapabilityDataDefinition capability) { + if (StringUtils.isNotEmpty(capability.getPreviousName())) { + capability.setName(capability.getPreviousName()); + capability.setPreviousName(capability.getParentName()); + } + } + + private static void revertAndAddCalculatedCapabilitiesProperties(String stringKey, MapPropertiesDataDefinition properties, MapListCapabilityDataDefinition calculatedCapabilities, MapCapabilityProperty newProps) { + String[] key = stringKey.split(ModelConverter.CAP_PROP_DELIM); + String capType = key[key.length - 2]; + String capName = key[key.length - 1]; + Optional foundCapOpt = calculatedCapabilities.getMapToscaDataDefinition().get(capType) + .getListToscaDataDefinition().stream() + .filter(c -> c.getName().equals(capName) && StringUtils.isNotEmpty(c.getPreviousName())) + .findFirst(); + foundCapOpt.ifPresent(capabilityDataDefinition -> key[key.length - 1] = capabilityDataDefinition.getPreviousName()); + newProps.put(buildCaLCapPropKey(key), properties); + } + + private static String buildCaLCapPropKey(String[] keyArray) { + StringBuilder key = new StringBuilder(); + for (int i = 0; i < keyArray.length; ++i) { + key.append(keyArray[i]); + if (i < keyArray.length - 1) { + key.append(ModelConverter.CAP_PROP_DELIM); + } + } + return key.toString(); + } + + private static void buildSetCapName(Map componentsCache, CapabilityDataDefinition capability, ComponentInstanceDataDefinition instance, Function originGetter) { + List reducedPath = capability.getOwnerId() != null ? getReducedPathByOwner(capability.getPath(), capability.getOwnerId()) : getReducedPath(capability.getPath()); + log.debug("reducedPath for ownerId {}, reducedPath {} ", capability.getOwnerId(), reducedPath); + reducedPath.remove(reducedPath.size() - 1); + ToscaElement originComponent = getOriginComponent(componentsCache, instance, originGetter); + String name = isRequiredToRepair(capability.getParentName()) ? + extractNameFromUniqueId(capability.getUniqueId()) : capability.getParentName(); + StringBuilder repairedName = buildSubstitutedName(componentsCache, originComponent, reducedPath, originGetter); + log.debug("#buildSetCapName - The name for the capability was built: {}", repairedName); + + capability.setName(repairedName.append(name).toString()); + if (isRequiredToRepair(capability.getPreviousName())) { + capability.setPreviousName(capability.getName().substring(capability.getName().indexOf(PATH_DELIMITER) + 1)); + } + if (isRequiredToRepair(capability.getParentName())) { + capability.setParentName(name); + } + } + + private static void buildSetReqName(Map componentsCache, RequirementDataDefinition requirement, ComponentInstanceDataDefinition instance, Function originGetter) { + List reducedPath = requirement.getOwnerId() != null ? getReducedPathByOwner(requirement.getPath(), requirement.getOwnerId()) : getReducedPath(requirement.getPath()); + log.debug("reducedPath for ownerId {}, reducedPath {} ", requirement.getOwnerId(), reducedPath); + reducedPath.remove(reducedPath.size() - 1); + ToscaElement originComponent = getOriginComponent(componentsCache, instance, originGetter); + String name = isRequiredToRepair(requirement.getParentName()) ? + extractNameFromUniqueId(requirement.getUniqueId()) : requirement.getParentName(); + + StringBuilder repairedName = buildSubstitutedName(componentsCache, originComponent, reducedPath, originGetter); + log.debug("#buildSetReqName - The name for the capability was built: ", repairedName); + requirement.setName(repairedName.append(name).toString()); + if (isRequiredToRepair(requirement.getPreviousName())) { + requirement.setPreviousName(requirement.getName().substring(requirement.getName().indexOf(PATH_DELIMITER) + 1)); + } + if (isRequiredToRepair(requirement.getParentName())) { + requirement.setParentName(name); + } + } + + private static String extractNameFromUniqueId(String uniqueId) { + String[] uid = uniqueId.split("\\."); + return uid[uid.length - 1]; + } + + private static StringBuilder buildSubstitutedName(Map componentsCache, ToscaElement originComponent, List path, Function originGetter) { + StringBuilder substitutedName = new StringBuilder(); + log.debug("#buildSubstitutedName"); + if (isNotEmpty(path) && isTopologyTemplateNotCvfc(originComponent)) { + log.debug("#buildSubstitutedName"); + List reducedPath = getReducedPath(path); + Collections.reverse(reducedPath); + appendNameRecursively(componentsCache, originComponent, reducedPath.iterator(), substitutedName, originGetter); + } + return substitutedName; + } + + private static boolean isTopologyTemplateNotCvfc(ToscaElement originComponent) { + return originComponent.getToscaType() == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE && originComponent.getResourceType() != ResourceTypeEnum.CVFC; + } + + private static ToscaElement getOriginComponent(Map componentsCache, ComponentInstanceDataDefinition instance, Function originGetter) { + if (componentsCache.containsKey(getActualComponentUid(instance))) { + return componentsCache.get(getActualComponentUid(instance)); + } + ToscaElement origin = originGetter.apply(instance); + componentsCache.put(origin.getUniqueId(), origin); + return origin; + } + + public static String getActualComponentUid(ComponentInstanceDataDefinition instance) { + return instance.getIsProxy() ? instance.getSourceModelUid() : instance.getComponentUid(); + } + + private static List getReducedPath(List path) { + return path.stream().distinct().collect(Collectors.toList()); + } + + private static void appendNameRecursively(Map componentsCache, ToscaElement originComponent, Iterator instanceIdIter, StringBuilder substitutedName, Function originGetter) { + log.debug("#appendNameRecursively"); + if (isTopologyTemplateNotCvfc(originComponent) + && MapUtils.isNotEmpty(((TopologyTemplate) originComponent).getComponentInstances()) && instanceIdIter.hasNext()) { + + String ownerId = instanceIdIter.next(); + Optional instanceOpt = ((TopologyTemplate) originComponent).getComponentInstances().values().stream().filter(i -> i.getUniqueId().equals(ownerId)).findFirst(); + if (instanceOpt.isPresent()) { + substitutedName.append(instanceOpt.get().getNormalizedName()).append(PATH_DELIMITER); + ToscaElement getOriginRes = getOriginComponent(componentsCache, instanceOpt.get(), originGetter); + appendNameRecursively(componentsCache, getOriginRes, instanceIdIter, substitutedName, originGetter); + } else if (MapUtils.isNotEmpty(((TopologyTemplate) originComponent).getGroups())) { + Optional groupOpt = ((TopologyTemplate) originComponent).getGroups().values().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst(); + groupOpt.ifPresent(groupDataDefinition -> substitutedName.append(groupDataDefinition.getName()).append(PATH_DELIMITER)); + } else { + log.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId, originComponent.getUniqueId()); + } + } + } + + private static List getReducedPathByOwner(List path, String ownerId) { + log.debug("ownerId {}, path {} ", ownerId, path); + if (CollectionUtils.isEmpty(path)) { + log.debug("cannot perform reduce by owner, path to component is empty"); + return path; + } + if (isBlank(ownerId)) { + log.debug("cannot perform reduce by owner, component owner is empty"); + return path; + } + //reduce by owner + Map map = path.stream().collect(Collectors.toMap(it -> dropLast(it, PATH_DELIMITER), Function.identity(), (a, b) -> a.endsWith(ownerId) ? a : b)); + //reduce list&duplicates and preserve order + return path.stream().distinct().filter(it -> map.values().contains(it)).collect(Collectors.toList()); + } + + private static String dropLast(String path, String delimiter) { + if (isBlank(path) || isBlank(delimiter)) { + return path; + } + return path.substring(0, path.lastIndexOf(delimiter)); + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/IdMapper.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/IdMapper.java new file mode 100644 index 0000000000..cc28ae4f83 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/IdMapper.java @@ -0,0 +1,53 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.utils; + +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; +import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ExternalReferencesOperation; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.stereotype.Component; + +import java.util.Map; +import java.util.Optional; + +/** + * Created by yavivi on 12/02/2018. + */ +@Component +public class IdMapper { + + private static final Logger log = Logger.getLogger(ExternalReferencesOperation.class.getName()); + + public String mapComponentNameToUniqueId(String componentInstanceName, GraphVertex serviceVertex) { + return map(componentInstanceName, serviceVertex, true); + } + + public String mapUniqueIdToComponentNameTo(String compUniqueId, GraphVertex serviceVertex) { + return map(compUniqueId, serviceVertex, false); + } + + private String map(String componentUniqueIdOrName, GraphVertex serviceVertex, boolean fromCompName) { + String result = null; + try { + Map jsonComposition = (Map) serviceVertex.getJson(); + CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + + Optional componentInstanceDataDefinitionOptional = null; + if (fromCompName) { + componentInstanceDataDefinitionOptional = compositionDataDefinition.getComponentInstances().values().stream().filter(c -> c.getNormalizedName().equals(componentUniqueIdOrName)).findAny(); + result = componentInstanceDataDefinitionOptional.get().getUniqueId(); + log.debug("Compponent Instance Unique Id = {}", result); + } else { + componentInstanceDataDefinitionOptional = compositionDataDefinition.getComponentInstances().values().stream().filter(c -> c.getUniqueId().equals(componentUniqueIdOrName)).findAny(); + result = componentInstanceDataDefinitionOptional.get().getNormalizedName(); + log.debug("Compponent Instance Normalized Name = {}", result); + } + + } catch (Exception e) { + log.error("Failed to map UUID or Normalized name of " + componentUniqueIdOrName, e); + } + return result; + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java new file mode 100644 index 0000000000..cd34ad5c18 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java @@ -0,0 +1,1730 @@ +/*- + * ============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.T + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.jsonjanusgraph.utils; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang.BooleanUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.builder.ReflectionToStringBuilder; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.NodeType; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum; +import org.openecomp.sdc.be.resources.data.ComponentMetadataData; +import org.openecomp.sdc.be.resources.data.ProductMetadataData; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.resources.data.ServiceMetadataData; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.util.*; +import java.util.Map.Entry; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class ModelConverter { + public static final String CAP_PROP_DELIM = "#"; + private static final Logger log = Logger.getLogger(ModelConverter.class); + + @SuppressWarnings("unchecked") + public static T convertToToscaElement(Component component) { + if (isAtomicComponent(component)) { + return (T) convertToNodeType(component); + } + return (T) convertToTopologyTemplate(component); + } + + @SuppressWarnings("unchecked") + public static T convertFromToscaElement(ToscaElement toscaElement) { + switch (toscaElement.getComponentType()) { + case RESOURCE: + return (T) convertToResource(toscaElement); + case SERVICE: + case PRODUCT: + return (T) convertToService(toscaElement); + default: + return null; + } + } + + public static boolean isAtomicComponent(Component component) { + ComponentTypeEnum componentType = component.getComponentType(); + if (!componentType.equals(ComponentTypeEnum.RESOURCE)) { + return false; + } + Resource resource = (Resource) component; + ResourceTypeEnum resType = resource.getResourceType(); + return isAtomicComponent(resType); + } + + public static boolean isAtomicComponent(ResourceTypeEnum resourceType) { + if (resourceType == null) { + return false; + } + return resourceType.isAtomicType(); + } + + // ********************************************************** + public static VertexTypeEnum getVertexType(Component component) { + VertexTypeEnum vertexType; + if (isAtomicComponent(component)) { + vertexType = VertexTypeEnum.NODE_TYPE; + } else { + vertexType = VertexTypeEnum.TOPOLOGY_TEMPLATE; + } + return vertexType; + } + + public static VertexTypeEnum getVertexType(String resourceTypeName) { + VertexTypeEnum vertexType = null; + ResourceTypeEnum resourceType = ResourceTypeEnum.getTypeByName(resourceTypeName); + if (isAtomicComponent(resourceType)) { + vertexType = VertexTypeEnum.NODE_TYPE; + } else { + vertexType = VertexTypeEnum.TOPOLOGY_TEMPLATE; + } + return vertexType; + } + + + + private static Service convertToService(ToscaElement toscaElement) { + Service service = new Service(); + convertComponentFields(service, toscaElement); + + convertServiceSpecificFields(toscaElement, service); + + TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; + + convertComponentInstances(topologyTemplate, service); + + convertInputs(topologyTemplate, service); + + convertProperties(topologyTemplate, service); + + convertPolicies(topologyTemplate, service); + + convertProperties(topologyTemplate, service); + + convertPolicies(topologyTemplate, service); + + convertGroups(topologyTemplate, service); + + setCapabilitiesToComponentAndGroups(topologyTemplate, service); + + convertPolicies(topologyTemplate, service); + + convertRelations(topologyTemplate, service); + + convertArtifacts(topologyTemplate, service); + + convertServiceApiArtifacts(topologyTemplate, service); + + convertServicePaths(topologyTemplate, service); + + convertServiceInterfaces(topologyTemplate, service); + + convertDataTypes(topologyTemplate, service); + + convertNodeFiltersComponents(topologyTemplate, service); + setCapabilitiesToComponent(topologyTemplate, service); + setRequirementsToComponent(topologyTemplate, service); + return service; + } + + private static void convertServiceSpecificFields(ToscaElement toscaElement, Service service) { + service.setProjectCode((String) toscaElement.getMetadataValue(JsonPresentationFields.PROJECT_CODE)); + service.setDistributionStatus(DistributionStatusEnum + .findState((String) toscaElement.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS))); + service.setEcompGeneratedNaming( + (Boolean) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.ECOMP_GENERATED_NAMING, true)); + service.setNamingPolicy((String) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.NAMING_POLICY, + StringUtils.EMPTY)); + service.setEnvironmentContext( + (String) toscaElement.getMetadataValue(JsonPresentationFields.ENVIRONMENT_CONTEXT)); + service.setInstantiationType((String) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.INSTANTIATION_TYPE, StringUtils.EMPTY)); + } + + private static Resource convertToResource(ToscaElement toscaElement) { + Resource resource = new Resource(); + convertComponentFields(resource, toscaElement); + + resource.setResourceType(toscaElement.getResourceType()); + if (toscaElement.getToscaType() == ToscaElementTypeEnum.NODE_TYPE) { + NodeType nodeType = (NodeType) toscaElement; + resource.setDerivedFrom(nodeType.getDerivedFrom()); + resource.setDerivedList(nodeType.getDerivedList()); + resource.setAbstract((Boolean) nodeType.getMetadataValue(JsonPresentationFields.IS_ABSTRACT)); + convertAttributes(nodeType, resource); + convertCapabilities(nodeType, resource); + convertRequirements(nodeType, resource); + convertInterfaces(nodeType, resource); + + } else { + TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; + if (resource.getResourceType() == ResourceTypeEnum.VF || resource.getResourceType() == ResourceTypeEnum.PNF) { + resource.setCsarUUID((String) topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID)); + resource.setCsarVersion((String) topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_VERSION)); + resource.setImportedToscaChecksum((String) topologyTemplate.getMetadataValue(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM)); + convertInterfaces(topologyTemplate, resource); + + } + convertComponentInstances(topologyTemplate, resource); + convertRelations(topologyTemplate, resource); + convertInputs(topologyTemplate, resource); + convertGroups(topologyTemplate, resource); + setCapabilitiesToComponentAndGroups(topologyTemplate, resource); + convertPolicies(topologyTemplate, resource); + convertNodeFiltersComponents(topologyTemplate, resource); + convertProperties(topologyTemplate, resource); + setCapabilitiesToComponent(topologyTemplate, resource); + setRequirementsToComponent(topologyTemplate, resource); + convertDataTypes(topologyTemplate, resource); + } + convertArtifacts(toscaElement, resource); + convertAdditionalInformation(toscaElement, resource); + + return resource; + } + + private static void convertInterfaces(TopologyTemplate toscaElement, Resource resource) { + Map interfaces = toscaElement.getInterfaces(); + Map copy; + if (interfaces != null) { + copy = interfaces.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDefinition(e.getValue()))); + } else { + copy = new HashMap<>(); + } + resource.setInterfaces(copy); + } + + private static void convertServiceInterfaces(TopologyTemplate toscaElement, Service service) { + Map interfaces = toscaElement.getInterfaces(); + Map copy; + if (interfaces != null) { + copy = interfaces.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDefinition(e.getValue()))); + } else { + copy = new HashMap<>(); + } + service.setInterfaces(copy); + } + + private static void convertAttributes(NodeType nodeType, Resource resource) { + Map attributes = nodeType.getAttributes(); + if (attributes != null) { + List attrs = attributes.values().stream().map(dataDef -> ModelConverter.fromDataDefinition(resource.getUniqueId(), dataDef)).collect(Collectors.toList()); + resource.setAttributes(attrs); + } + } + + private static PropertyDefinition fromDataDefinition(String resourceId, PropertyDataDefinition dataDefinition) { + PropertyDefinition attributeDefinition = new PropertyDefinition(dataDefinition); + attributeDefinition.setParentUniqueId(resourceId); + return attributeDefinition; + } + + private static void convertInterfaces(NodeType nodeType, Resource resource) { + Map interfaceArtifacts = nodeType.getInterfaceArtifacts(); + if (interfaceArtifacts != null) { + Map interfaces = interfaceArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new InterfaceDefinition(en.getValue()))); + resource.setInterfaces(interfaces); + } + } + + /** + * Converts component instances of topology template to component instances of resource + * + * @param topologyTemplate + * @param component + */ + public static void convertComponentInstances(TopologyTemplate topologyTemplate, Component component) { + + if (MapUtils.isNotEmpty(topologyTemplate.getComponentInstances())) { + + setComponentInstancesAttributesToComponent(topologyTemplate, component); + + setComponentInstancesPropertiesToComponent(topologyTemplate, component); + + setComponentInstancesInputsToComponent(topologyTemplate, component); + + setComponentInstancesToComponent(topologyTemplate, component); + + setComponentInstancesCapabilitiesToComponentAndCI(topologyTemplate, component); + + setComponentInstancesRequirementsToComponent(topologyTemplate, component); + + setComponentInstancesArtifactsToComponent(topologyTemplate, component); + + setComponentInstancesInterfacesToComponent(topologyTemplate, component); + + } + } + + private static void setComponentInstancesArtifactsToComponent(TopologyTemplate topologyTemplate, Component component) { + Map instDeploymentArtifacts = topologyTemplate.getInstDeploymentArtifacts(); + Map instanceArtifacts = topologyTemplate.getInstanceArtifacts(); + + List instances = component.getComponentInstances(); + if (instDeploymentArtifacts != null && instances != null) { + instDeploymentArtifacts.entrySet().forEach(e -> { + Optional ci = instances.stream().filter(i -> i.getUniqueId().equals(e.getKey())).findFirst(); + if (ci.isPresent()) { + Map mapToscaDataDefinition = e.getValue().getMapToscaDataDefinition(); + Map deplArt = mapToscaDataDefinition.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue()))); + + ci.get().setDeploymentArtifacts(deplArt); + } + }); + } + if (instanceArtifacts != null && instances != null) { + instanceArtifacts.entrySet().forEach(e -> { + Optional ci = instances.stream().filter(i -> i.getUniqueId().equals(e.getKey())).findFirst(); + if (ci.isPresent()) { + Map mapToscaDataDefinition = e.getValue().getMapToscaDataDefinition(); + Map deplArt = mapToscaDataDefinition.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue()))); + + ci.get().setArtifacts(deplArt); + } + }); + } + + } + + public static void convertComponentInstances(Component component, TopologyTemplate topologyTemplate) { + + if (!CollectionUtils.isEmpty(component.getComponentInstances())) { + + setComponentInstancesAttributesToTopologyTemplate(component, topologyTemplate); + + setComponentInstancesPropertiesToTopologyTemplate(component, topologyTemplate); + + setComponentInstancesInputsToTopologyTemplate(component, topologyTemplate); + + setComponentInstancesToTopologyTemplate(component, topologyTemplate); + + setComponentInstancesArtifactsToTopologyTemplate(component, topologyTemplate); + } + } + + public static void convertRelations(TopologyTemplate topologyTemplate, Component component) { + Map relations = topologyTemplate.getRelations(); + List componentRelations; + if (relations != null && !relations.isEmpty()) { + componentRelations = relations.values().stream().map(ModelConverter::convertRelation).collect(Collectors.toList()); + + } else { + componentRelations = new ArrayList<>(); + } + component.setComponentInstancesRelations(componentRelations); + + } + + public static RequirementCapabilityRelDef convertRelation(RelationshipInstDataDefinition relation) { + RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef(); + requirementCapabilityRelDef.setFromNode(relation.getFromId()); + requirementCapabilityRelDef.setToNode(relation.getToId()); + requirementCapabilityRelDef.setOriginUI(BooleanUtils.isTrue(relation.isOriginUI())); + + CapabilityRequirementRelationship rel = new CapabilityRequirementRelationship(); + RelationshipInfo relationshipPair = getRelationshipInfo(relation); + rel.setRelation(relationshipPair); + requirementCapabilityRelDef.setRelationships(Arrays.asList(rel)); + + return requirementCapabilityRelDef; + } + + /** + * @param relation + * @return + */ + private static RelationshipInfo getRelationshipInfo(RelationshipInstDataDefinition relation) { + RelationshipInfo relationshipPair = new RelationshipInfo(); + + relationshipPair.setId(relation.getUniqueId()); + + relationshipPair.setCapabilityOwnerId(relation.getCapabilityOwnerId()); + relationshipPair.setCapabilityUid(relation.getCapabilityId()); + relationshipPair.setCapability(relation.getCapability()); + + relationshipPair.setRequirementOwnerId(relation.getRequirementOwnerId()); + relationshipPair.setRequirementUid(relation.getRequirementId()); + relationshipPair.setRequirement(relation.getRequirement()); + + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType(relation.getType()); + relationshipPair.setRelationships(relationship); + + return relationshipPair; + } + + + public static List convertRelationToToscaRelation(RequirementCapabilityRelDef relation) { + + List relationsList = new ArrayList<>(); + + List relationship = relation.getRelationships(); + relationship.forEach(p -> { + RelationshipInstDataDefinition requirementCapabilityRelDef = new RelationshipInstDataDefinition(); + requirementCapabilityRelDef.setFromId(relation.getFromNode()); + requirementCapabilityRelDef.setToId(relation.getToNode()); + requirementCapabilityRelDef.setUniqueId(p.getRelation().getId()); + requirementCapabilityRelDef.setCapabilityOwnerId(p.getRelation().getCapabilityOwnerId()); + requirementCapabilityRelDef.setCapabilityId(p.getRelation().getCapabilityUid()); + requirementCapabilityRelDef.setRequirementOwnerId(p.getRelation().getRequirementOwnerId()); + requirementCapabilityRelDef.setRequirementId(p.getRelation().getRequirementUid()); + requirementCapabilityRelDef.setRequirement(p.getRelation().getRequirement()); + requirementCapabilityRelDef.setType(p.getRelation().getRelationship().getType()); + requirementCapabilityRelDef.setCapability(p.getRelation().getCapability()); + + relationsList.add(requirementCapabilityRelDef); + }); + + return relationsList; + } + + private static void convertCapabilities(Component component, TopologyTemplate topologyTemplate) { + convertTopologyTemplateCapabilities(component, topologyTemplate); + if(componentInstancesCapabilitiesExist(component) || groupsCapabilitiesExist(component)){ + topologyTemplate.setCalculatedCapabilities(new HashMap<>()); + topologyTemplate.setCalculatedCapabilitiesProperties(new HashMap<>()); + } + convertComponentInstancesCapabilities(component, topologyTemplate); + convertGroupsCapabilities(component, topologyTemplate); + } + + private static void convertGroupsCapabilities(Component component, TopologyTemplate topologyTemplate) { + if(groupsCapabilitiesExist(component)){ + component.getGroups() + .stream() + .filter(g -> MapUtils.isNotEmpty(g.getCapabilities())) + .forEach(g -> addCapabilities(topologyTemplate, g.getCapabilities(), g.getUniqueId())); + } + } + + private static void convertTopologyTemplateCapabilities(Component component, ToscaElement toscaElement) { + Map> capabilities = component.getCapabilities(); + + Map toscaCapMap = new HashMap<>(); + Map toscaCapPropMap = new HashMap<>(); + + if (MapUtils.isNotEmpty(capabilities )) { + capabilities.forEach((s, caps) -> { + if (CollectionUtils.isNotEmpty(caps)) { + List capList = caps.stream().filter(capabilityDefinition -> capabilityDefinition.getOwnerId() + .equals(component.getUniqueId())).map(CapabilityDataDefinition::new).collect(Collectors.toList()); + + populateCapabilityMap(toscaCapMap, toscaCapPropMap, s, caps, capList); + } + } + ); + + toscaElement.setCapabilities(toscaCapMap); + toscaElement.setCapabilitiesProperties(toscaCapPropMap); + } + } + private static void populateCapabilityMap(Map toscaCapMap, + Map toscaCapPropMap, + String s, List caps, + List capList) { + ListCapabilityDataDefinition listCapabilityDataDefinition = new ListCapabilityDataDefinition(capList); + toscaCapMap.put(s, listCapabilityDataDefinition); + + for (CapabilityDefinition cap : caps) { + List capPrps = cap.getProperties(); + if (CollectionUtils.isNotEmpty(capPrps)) { + MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); + for (ComponentInstanceProperty cip : capPrps) { + PropertyDataDefinition propertyDataDefinition = new PropertyDataDefinition(cip); + propertyDataDefinition.setParentUniqueId(cap.getUniqueId()); + dataToCreate.put(cip.getName(), propertyDataDefinition); + } + toscaCapPropMap.put(s + CAP_PROP_DELIM + cap.getName(), dataToCreate); + } + } + } + + private static void convertTopologyTemplateRequirements(Component component, ToscaElement toscaElement) { + Map> requirements = component.getRequirements(); + + Map toscaReqMap = new HashMap<>(); + + if (MapUtils.isNotEmpty(requirements )) { + requirements.forEach((s, reqs)-> { + if (CollectionUtils.isNotEmpty(reqs)) { + List reqList = reqs.stream().filter(requirementDefinition -> requirementDefinition.getOwnerId() + .equals(component.getUniqueId())).map(RequirementDataDefinition::new).collect(Collectors.toList()); + + ListRequirementDataDefinition listRequirementDataDefinition = new ListRequirementDataDefinition(reqList); + toscaReqMap.put(s, listRequirementDataDefinition); + } + } + ); + toscaElement.setRequirements(toscaReqMap); + } + } + private static void convertComponentInstancesCapabilities(Component component, TopologyTemplate topologyTemplate) { + if (componentInstancesCapabilitiesExist(component)) { + component.getComponentInstances() + .stream() + .filter(i -> MapUtils.isNotEmpty(i.getCapabilities())) + .forEach(i -> addCapabilities(topologyTemplate, i.getCapabilities(), i.getUniqueId())); + } + } + + private static void addCapabilities(TopologyTemplate topologyTemplate, Map> capabilities, String ownerId) { + if (MapUtils.isNotEmpty(capabilities)) { + if (topologyTemplate.getCalculatedCapabilities() == null) { + topologyTemplate.setCalculatedCapabilities(new HashMap<>()); + } + topologyTemplate.getCalculatedCapabilities().put(ownerId, convertToMapListCapabiltyDataDefinition(capabilities)); + if (topologyTemplate.getCalculatedCapabilitiesProperties() == null) { + topologyTemplate.setCalculatedCapabilitiesProperties(new HashMap<>()); + } + topologyTemplate.getCalculatedCapabilitiesProperties().put(ownerId, convertToMapOfMapCapabiltyProperties(capabilities, ownerId)); + } + } + + private static boolean componentInstancesCapabilitiesExist(Component component) { + return component.getCapabilities() != null && component.getComponentInstances() != null + && component.getComponentInstances() + .stream() + .filter(ci->MapUtils.isNotEmpty(ci.getCapabilities())) + .findFirst() + .isPresent(); + } + private static boolean groupsCapabilitiesExist(Component component) { + return component.getCapabilities() != null && component.getGroups() != null + && component.getGroups() + .stream() + .filter(g->MapUtils.isNotEmpty(g.getCapabilities())) + .findFirst() + .isPresent(); + } + public static MapCapabilityProperty convertToMapOfMapCapabiltyProperties(Map> instCapabilities, String ownerId) { + return convertToMapOfMapCapabiltyProperties(instCapabilities, ownerId, false); + } + + public static MapCapabilityProperty convertToMapOfMapCapabiltyProperties(Map> capabilities, String ownerId, boolean fromCsar) { + + Map toscaCapPropMap = new HashMap<>(); + if(MapUtils.isNotEmpty(capabilities)) + capabilities.forEach((s, caps)-> { + + if (caps != null && !caps.isEmpty()) { + + MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); + + for (CapabilityDefinition cap : caps) { + List capPrps = cap.getProperties(); + if (capPrps != null) { + + for (ComponentInstanceProperty cip : capPrps) { + dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip)); + } + // format key of capability properties : + // VF instance in service : instanceId#ownerId#type#capName + // VFC instance ion VF : instanceId#ownerId#type#capName -> instanceId=ownerId + + StringBuilder sb = new StringBuilder(ownerId); + sb.append(CAP_PROP_DELIM); + if (fromCsar) { + sb.append(ownerId); + } else { + sb.append(cap.getOwnerId()); + } + sb.append(CAP_PROP_DELIM).append(s).append(CAP_PROP_DELIM).append(cap.getName()); + toscaCapPropMap.put(sb.toString(), new MapPropertiesDataDefinition(dataToCreate)); + } + } + } + } + ); + return new MapCapabilityProperty(toscaCapPropMap); + } + + private static MapListCapabilityDataDefinition convertToMapListCapabiltyDataDefinition(Map> instCapabilities) { + + Map mapToscaDataDefinition = new HashMap<>(); + for (Entry> instCapability : instCapabilities.entrySet()) { + mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()))); + } + + return new MapListCapabilityDataDefinition(mapToscaDataDefinition); + } + + private static void convertRequirements(Component component, TopologyTemplate topologyTemplate) { + + convertTopologyTemplateRequirements(component, topologyTemplate); + if (component.getRequirements() != null && component.getComponentInstances() != null) { + topologyTemplate.setCalculatedRequirements(new HashMap<>()); + for (ComponentInstance instance : component.getComponentInstances()) { + Map> instRequirements = instance.getRequirements(); + if (MapUtils.isNotEmpty(instRequirements)) { + if (topologyTemplate.getCalculatedRequirements() == null) { + topologyTemplate.setCalculatedRequirements(new HashMap<>()); + } + topologyTemplate.getCalculatedRequirements().put(instance.getUniqueId(), convertToMapListRequirementDataDefinition(instRequirements)); + } + } + } + } + + private static MapListRequirementDataDefinition convertToMapListRequirementDataDefinition(Map> instRequirements) { + + Map mapToscaDataDefinition = new HashMap<>(); + for (Entry> instRequirement : instRequirements.entrySet()) { + mapToscaDataDefinition.put(instRequirement.getKey(), new ListRequirementDataDefinition(instRequirement.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList()))); + } + + return new MapListRequirementDataDefinition(mapToscaDataDefinition); + } + + @SuppressWarnings("unchecked") + private static void convertComponentFields(Component component, ToscaElement toscaElement) { + component.setName(toscaElement.getName()); + component.setAllVersions(toscaElement.getAllVersions()); + component.setCategories(toscaElement.getCategories()); + component.setComponentType(toscaElement.getComponentType()); + component.setCreationDate(toscaElement.getCreationDate()); + component.setCreatorUserId(toscaElement.getCreatorUserId()); + component.setCreatorFullName(toscaElement.getCreatorFullName()); + component.setLastUpdateDate(toscaElement.getLastUpdateDate()); + component.setLastUpdaterFullName(toscaElement.getLastUpdaterFullName()); + component.setLastUpdaterUserId(toscaElement.getLastUpdaterUserId()); + component.setNormalizedName(toscaElement.getNormalizedName()); + + component.setLifecycleState(toscaElement.getLifecycleState()); + component.setVersion(toscaElement.getVersion()); + component.setHighestVersion(toscaElement.isHighestVersion()); + component.setUniqueId(toscaElement.getUniqueId()); + component.setSystemName((String) toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME)); + component.setDerivedFromGenericType(toscaElement.getDerivedFromGenericType()); + component.setDerivedFromGenericVersion(toscaElement.getDerivedFromGenericVersion()); + + Map properties = toscaElement.getProperties(); + if(MapUtils.isNotEmpty(properties)) { + List propertiesMap = properties.values().stream().map(x -> new PropertyDefinition(x)).collect(Collectors.toList()); + component.setProperties(propertiesMap); + } + + //archive + component.setArchived(toscaElement.isArchived() == null ? false : toscaElement.isArchived()); + + + //component.setArchiveTime(toscaElement.getArchiveTime() == null ? 0L : toscaElement.getArchiveTime()); + component.setArchiveTime(toscaElement.getArchiveTime()); + component.setVspArchived(toscaElement.isVspArchived() == null ? false : toscaElement.isVspArchived()); + + if (component.getComponentType() == ComponentTypeEnum.RESOURCE) { + Resource resource = (Resource) component; + resource.setAbstract((Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT)); + resource.setToscaResourceName((String) toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); + resource.setVendorName((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_NAME)); + resource.setVendorRelease((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_RELEASE)); + // field isn't mandatory , but shouldn't be null(should be an empty string instead) + if (((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)) != null){ + resource.setResourceVendorModelNumber((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)); + } else { + resource.setResourceVendorModelNumber(""); + } + } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) { + Service service = (Service) component; + if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)) != null){ + service.setServiceType((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)); + } else { + service.setServiceType(""); + } + if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)) != null){ + service.setServiceRole((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)); + } else { + service.setServiceRole(""); + } + } + component.setConformanceLevel((String) toscaElement.getMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL)); + component.setIcon((String) toscaElement.getMetadataValue(JsonPresentationFields.ICON)); + component.setDescription((String) toscaElement.getMetadataValue(JsonPresentationFields.DESCRIPTION)); + component.setTags((List) toscaElement.getMetadataValue(JsonPresentationFields.TAGS)); + component.setInvariantUUID((String) toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID)); + component.setContactId((String) toscaElement.getMetadataValue(JsonPresentationFields.CONTACT_ID)); + component.setUUID((String) toscaElement.getMetadataValue(JsonPresentationFields.UUID)); + component.setIsDeleted((Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED)); + component.setToscaType(toscaElement.getToscaType().getValue()); + } + + private static NodeType convertToNodeType(Component component) { + Resource resource = (Resource) component; + NodeType nodeType = new NodeType(); + nodeType.setDerivedFrom(resource.getDerivedFrom()); + nodeType.setDerivedList(resource.getDerivedList()); + nodeType.setResourceType(resource.getResourceType()); + convertCommonToscaData(component, nodeType); + convertAdditionalInformation(component, nodeType); + convertArtifacts(resource, nodeType); + convertCapabilities(resource, nodeType); + convertRequirements(resource, nodeType); + convertAttributes(resource, nodeType); + convertProperties(resource, nodeType); + convertInterfaces(resource, nodeType); + return nodeType; + } + + private static void convertProperties(Resource resource, NodeType nodeType) { + List properties = resource.getProperties(); + if (properties != null && !properties.isEmpty()) { + Map propertiesMap = properties.stream().collect(Collectors.toMap(PropertyDefinition::getName, PropertyDataDefinition::new)); + nodeType.setProperties(propertiesMap); + } + } + + private static void convertInterfaces(Resource resource, NodeType nodeType) { + Map interfaces = resource.getInterfaces(); + if (interfaces != null) { + Map interfaceArtifacts = interfaces.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, x -> new InterfaceDataDefinition(x.getValue()))); + nodeType.setInterfaceArtifacts(interfaceArtifacts); + } + } + + private static void convertAdditionalInformation(Component component, ToscaElement toscaElement) { + List additionalInformation = component.getAdditionalInformation(); + if (additionalInformation != null) { + Map addInfo = additionalInformation.stream().collect(Collectors.toMap(AdditionalInformationDefinition::getUniqueId, AdditionalInfoParameterDataDefinition::new)); + toscaElement.setAdditionalInformation(addInfo); + } + } + + private static void convertAdditionalInformation(ToscaElement toscaElement, Component resource) { + Map additionalInformation = toscaElement.getAdditionalInformation(); + if (additionalInformation != null) { + List addInfo = additionalInformation.values().stream().map(AdditionalInformationDefinition::new).collect(Collectors.toList()); + resource.setAdditionalInformation(addInfo); + } + } + + private static void convertArtifacts(ToscaElement toscaElement, Component component) { + Map artifacts = toscaElement.getArtifacts(); + Map copy; + if (artifacts != null) { + copy = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); + + } else { + copy = new HashMap<>(); + } + component.setArtifacts(copy); + + Map toscaArtifacts = toscaElement.getToscaArtifacts(); + if (toscaArtifacts != null) { + copy = toscaArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); + + } else { + copy = new HashMap<>(); + } + component.setToscaArtifacts(copy); + + Map deploymentArtifacts = toscaElement.getDeploymentArtifacts(); + if (deploymentArtifacts != null) { + copy = deploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); + + } else { + copy = new HashMap<>(); + } + component.setDeploymentArtifacts(copy); + } + + private static void convertNodeFiltersComponents(TopologyTemplate topologyTemplate, Component component) { + Map filters = topologyTemplate.getNodeFilterComponents(); + Map copy; + if (filters != null) { + copy = filters.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new CINodeFilterDataDefinition(e.getValue()))); + } else { + copy = new HashMap<>(); + } + component.setNodeFilterComponents(copy); + } + + private static void convertServiceApiArtifacts(TopologyTemplate topologyTemplate, Service service) { + Map serviceApiArtifacts = topologyTemplate.getServiceApiArtifacts(); + Map copy; + if (serviceApiArtifacts != null) { + copy = serviceApiArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); + + } else { + copy = new HashMap<>(); + } + service.setServiceApiArtifacts(copy); + } + private static void convertServicePaths(TopologyTemplate topologyTemplate, Service service) { + Map servicePaths = topologyTemplate.getForwardingPaths(); + Map copy; + if (servicePaths != null) { + copy = servicePaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ForwardingPathDataDefinition(e.getValue()))); + + } else { + copy = new HashMap<>(); + } + service.setForwardingPaths(copy); + } + + private static void convertArtifacts(Component component, ToscaElement toscaElement) { + Map artifacts = component.getArtifacts(); + if (artifacts != null) { + Map copy = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + toscaElement.setArtifacts(copy); + } + + Map toscaArtifacts = component.getToscaArtifacts(); + if (toscaArtifacts != null) { + Map copy = toscaArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + toscaElement.setToscaArtifacts(copy); + } + + Map deploymentArtifacts = component.getDeploymentArtifacts(); + if (deploymentArtifacts != null) { + Map copy = deploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + toscaElement.setDeploymentArtifacts(copy); + } + } + + private static void convertServiceApiArtifacts(Service service, TopologyTemplate topologyTemplate) { + Map serviceApiArtifacts = service.getServiceApiArtifacts(); + if (serviceApiArtifacts != null) { + Map copy = serviceApiArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + topologyTemplate.setServiceApiArtifacts(copy); + } + } + + private static void convertCapabilities(Component component, NodeType toscaElement) { + Map> capabilities = component.getCapabilities(); + + Map toscaCapMap = new HashMap<>(); + Map toscaCapPropMap = new HashMap<>(); + + if (capabilities != null && !capabilities.isEmpty()) { + capabilities.forEach((s, caps) -> { + + if (caps != null && !caps.isEmpty()) { + List capList = caps.stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()); + + populateCapabilityMap(toscaCapMap, toscaCapPropMap, s, caps, capList); + } + } + ); + + toscaElement.setCapabilities(toscaCapMap); + toscaElement.setCapabilitiesProperties(toscaCapPropMap); + } + } + + private static void convertAttributes(Resource component, NodeType nodeType) { + List attributes = component.getAttributes(); + if (attributes != null) { + Map attrsByName = attributes.stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity())); + nodeType.setAttributes(attrsByName); + } + } + + private static void convertRequirements(Resource component, NodeType nodeType) { + Map> requirements = component.getRequirements(); + + Map toscaReqMap = new HashMap<>(); + + if (requirements != null && !requirements.isEmpty()) { + requirements.forEach((s, reqs)-> { + + if (reqs != null && !reqs.isEmpty()) { + List reqList = reqs.stream().map(RequirementDataDefinition::new).collect(Collectors.toList()); + + ListRequirementDataDefinition listRequirementDataDefinition = new ListRequirementDataDefinition(reqList); + toscaReqMap.put(s, listRequirementDataDefinition); + } + } + ); + nodeType.setRequirements(toscaReqMap); + } + } + + private static void convertCapabilities(NodeType toscaElement, Component component) { + Map toscaCapabilities = toscaElement.getCapabilities(); + Map toscaCapPropMap = toscaElement.getCapabilitiesProperties(); + + Map> compCap = new HashMap<>(); + if (toscaCapabilities == null || toscaCapabilities.isEmpty()) + return; + toscaCapabilities.forEach((s, cap)-> { + + if (cap != null) { + List capDataList = cap.getListToscaDataDefinition(); + + if (capDataList != null && !capDataList.isEmpty()) { + List capList = capDataList.stream().map(CapabilityDefinition::new).collect(Collectors.toList()); + compCap.put(s, capList); + } + } + + } + ); + if (toscaCapPropMap != null && !toscaCapPropMap.isEmpty()) { + toscaCapPropMap.forEach((s, capProp)-> { + String[] result = s.split(CAP_PROP_DELIM); + if (capProp != null) { + Map capMap = capProp.getMapToscaDataDefinition(); + + if (capMap != null && !capMap.isEmpty()) { + List capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList()); + + List cap = compCap.get(result[0]); + Optional op = cap.stream().filter(c -> c.getName().equals(result[1])).findFirst(); + if (op.isPresent()) { + op.get().setProperties(capPropsList); + } + } + } + } + ); + } + + component.setCapabilities(compCap); + + } + + private static void convertGroups(TopologyTemplate toscaElement, Component component) { + Map toscaGroups = toscaElement.getGroups(); + List groupDefinitions = null; + if (MapUtils.isNotEmpty(toscaGroups)) { + groupDefinitions = toscaGroups.values().stream().map(GroupDefinition::new).collect(Collectors.toList()); + } + component.setGroups(groupDefinitions); + } + + private static void convertPolicies(TopologyTemplate toscaElement, Component component) { + Map policies = toscaElement.getPolicies(); + Map policyDefinitions = null; + if (MapUtils.isNotEmpty(policies)) { + policyDefinitions = policies.values().stream().map(PolicyDefinition::new).collect(Collectors.toMap(PolicyDefinition::getUniqueId, Function.identity())); + } + component.setPolicies(policyDefinitions); + } + + private static void convertGroups(Component component, TopologyTemplate toscaElement) { + List groupDefinitions = component.getGroups(); + Map groups = new HashMap<>(); + + if (groupDefinitions != null && groups.isEmpty()) { + groups = groupDefinitions.stream().collect(Collectors.toMap(GroupDefinition::getName, GroupDefinition::new)); + } + toscaElement.setGroups(groups); + } + + private static void convertPolicies(Component component, TopologyTemplate toscaElement) { + Map policyDefinitions = component.getPolicies(); + Map policies = new HashMap<>(); + if (MapUtils.isNotEmpty(policyDefinitions)) { + policies = policyDefinitions.values().stream().collect((Collectors.toMap(PolicyDefinition::getUniqueId, PolicyDataDefinition::new))); + } + toscaElement.setPolicies(policies); + } + + private static void convertRequirements(NodeType toscaElement, Component component) { + Map toscaRequirements = toscaElement.getRequirements(); + + Map> compReqs = new HashMap<>(); + if (toscaRequirements == null || toscaRequirements.isEmpty()) + return; + toscaRequirements.forEach((s, req) -> { + + if (req != null) { + List reqDataList = req.getListToscaDataDefinition(); + + if (reqDataList != null && !reqDataList.isEmpty()) { + List reqList = reqDataList.stream().map(RequirementDefinition::new).collect(Collectors.toList()); + compReqs.put(s, reqList); + } + } + } + ); + component.setRequirements(compReqs); + } + + private static TopologyTemplate convertToTopologyTemplate(Component component) { + TopologyTemplate topologyTemplate; + ComponentTypeEnum componentType = component.getComponentType(); + topologyTemplate = new TopologyTemplate(); + + if (componentType == ComponentTypeEnum.RESOURCE) { + Resource resource = (Resource) component; + topologyTemplate.setResourceType(resource.getResourceType()); + topologyTemplate.setMetadataValue(JsonPresentationFields.CSAR_UUID, resource.getCsarUUID()); + topologyTemplate.setMetadataValue(JsonPresentationFields.CSAR_VERSION, resource.getCsarVersion()); + topologyTemplate.setMetadataValue(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM, resource.getImportedToscaChecksum()); + convertTopologyTemplateInterfaces(resource, topologyTemplate); + } + if (componentType == ComponentTypeEnum.SERVICE) { + convertServiceSpecificEntities((Service) component, topologyTemplate); + } + convertCommonToscaData(component, topologyTemplate); + convertArtifacts(component, topologyTemplate); + + convertAdditionalInformation(component, topologyTemplate); + convertComponentInstances(component, topologyTemplate); + + convertInputs(component, topologyTemplate); + convertProperties(component, topologyTemplate); + convertCapabilities(component, topologyTemplate); + convertGroups(component, topologyTemplate); + convertPolicies(component, topologyTemplate); + convertRequirements(component, topologyTemplate); + convertRelationsToComposition(component, topologyTemplate); + + return topologyTemplate; + } + + private static void convertTopologyTemplateInterfaces(Resource resource, TopologyTemplate topologyTemplate) { + Map interfaces = resource.getInterfaces(); + if (interfaces != null && !interfaces.isEmpty()) { + Map copy = interfaces.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDataDefinition(e.getValue()))); + topologyTemplate.setInterfaces(copy); + } + } + + private static void convertServiceInterfaces(Service service, TopologyTemplate topologyTemplate) { + Map interfaces = service.getInterfaces(); + if (interfaces != null && !interfaces.isEmpty()) { + Map copy = interfaces.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDataDefinition(e.getValue()))); + topologyTemplate.setInterfaces(copy); + } + } + + private static void convertServiceSpecificEntities(Service service, TopologyTemplate topologyTemplate) { + convertServiceMetaData(service, topologyTemplate); + convertServiceApiArtifacts(service, topologyTemplate); + convertServicePaths(service,topologyTemplate); + convertServiceInterfaces(service, topologyTemplate); + } + + private static void convertServicePaths(Service service, TopologyTemplate topologyTemplate) { + Map servicePaths = service.getForwardingPaths(); + if (servicePaths != null && !servicePaths.isEmpty()) { + Map copy = servicePaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ForwardingPathDataDefinition(e.getValue()))); + topologyTemplate.setForwardingPaths(copy); + } + } + + private static void convertServiceMetaData(Service service, TopologyTemplate topologyTemplate) { + if (service.getDistributionStatus() != null) { + topologyTemplate.setMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS, + service.getDistributionStatus().name()); + } + topologyTemplate.setMetadataValue(JsonPresentationFields.PROJECT_CODE, service.getProjectCode()); + topologyTemplate.setMetadataValue(JsonPresentationFields.ECOMP_GENERATED_NAMING, + service.isEcompGeneratedNaming()); + topologyTemplate.setMetadataValue(JsonPresentationFields.NAMING_POLICY, service.getNamingPolicy()); + topologyTemplate.setMetadataValue(JsonPresentationFields.ENVIRONMENT_CONTEXT, service.getEnvironmentContext()); + topologyTemplate.setMetadataValue(JsonPresentationFields.INSTANTIATION_TYPE, service.getInstantiationType()); + + } + + private static void convertRelationsToComposition(Component component, TopologyTemplate topologyTemplate) { + List componentInstancesRelations = component.getComponentInstancesRelations(); + if (componentInstancesRelations != null) { + Map compositions = topologyTemplate.getCompositions(); + if (compositions == null) { + compositions = new HashMap<>(); + } + CompositionDataDefinition compositionDataDefinition = compositions.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + if (compositionDataDefinition == null) { + compositionDataDefinition = new CompositionDataDefinition(); + compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), compositionDataDefinition); + } + + Map relations = componentInstancesRelations.stream().flatMap(x -> convertRelationToToscaRelation(x).stream()).filter(i -> i.getUniqueId() != null) + .collect(Collectors.toMap(RelationshipInstDataDefinition::getUniqueId, Function.identity())); + compositionDataDefinition.setRelations(relations); + } + } + + private static void convertInputs(Component component, TopologyTemplate topologyTemplate) { + List inputsList = component.getInputs(); + if (inputsList != null && !inputsList.isEmpty()) { + + Map inputsMap = inputsList.stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity())); + topologyTemplate.setInputs(inputsMap); + } + + } + + private static void convertInputs(TopologyTemplate topologyTemplate, Component component) { + Map inputsMap = topologyTemplate.getInputs(); + if (inputsMap != null && !inputsMap.isEmpty()) { + List inputsList = inputsMap.values() + .stream() + .map(InputDefinition::new) + .collect(Collectors.toList()); + component.setInputs(inputsList); + } + } + + private static void convertProperties(Component component, TopologyTemplate topologyTemplate) { + List propertiesList = component.getProperties(); + if (propertiesList != null && !propertiesList.isEmpty()) { + Map propertiesMap = propertiesList.stream().map(i -> new PropertyDataDefinition(i)).collect(Collectors.toMap(i -> i.getName(), i -> i)); + topologyTemplate.setProperties(propertiesMap); + } + + } + + private static void convertProperties(TopologyTemplate topologyTemplate, Component component) { + Map proeprtiesMap = topologyTemplate.getProperties(); + if (proeprtiesMap != null && !proeprtiesMap.isEmpty()) { + Map copy = proeprtiesMap.entrySet().stream() + .collect(Collectors.toMap(entry -> entry.getKey(), entry -> new PropertyDefinition + (entry.getValue()))); + component.setProperties(new ArrayList<>(copy.values())); + } + } + + private static void convertDataTypes(TopologyTemplate topologyTemplate, Component component) { + Map dataTypeDataMap = topologyTemplate.getDataTypes(); + if (MapUtils.isNotEmpty(dataTypeDataMap)) { + List dataTypeMap = dataTypeDataMap.values().stream().map(e -> { + DataTypeDefinition dataType = new DataTypeDefinition(e); + + if(CollectionUtils.isNotEmpty(e.getPropertiesData())) { + log.debug("#convertDataTypes - propertiesData is not null. {}", + ReflectionToStringBuilder.toString(e.getPropertiesData())); + dataType.setProperties(e.getPropertiesData().stream() + .map(PropertyDefinition::new).collect(Collectors.toList())); + } else { + log.debug("#convertDataTypes - propertiesData is null. ignore."); + } + return dataType; + }).collect(Collectors.toList()); + component.setDataTypes(dataTypeMap); + } + } + + + private static void convertCommonToscaData(Component component, ToscaElement toscaElement) { + toscaElement.setUUID(component.getUUID()); + toscaElement.setUniqueId(component.getUniqueId()); + toscaElement.setSystemName(component.getSystemName()); + toscaElement.setLifecycleState(component.getLifecycleState()); + toscaElement.setComponentType(component.getComponentType()); + toscaElement.setNormalizedName(component.getNormalizedName()); + toscaElement.setMetadataValue(JsonPresentationFields.NAME, component.getName()); + toscaElement.setCategories(component.getCategories()); + toscaElement.setCreatorUserId(component.getCreatorUserId()); + toscaElement.setCreationDate(component.getCreationDate()); + toscaElement.setCreatorFullName(component.getCreatorFullName()); + toscaElement.setHighestVersion(component.isHighestVersion()); + toscaElement.setLastUpdateDate(component.getLastUpdateDate()); + toscaElement.setLastUpdaterFullName(component.getLastUpdaterFullName()); + toscaElement.setLastUpdaterUserId(component.getLastUpdaterUserId()); + toscaElement.setDerivedFromGenericType(component.getDerivedFromGenericType()); + toscaElement.setDerivedFromGenericVersion(component.getDerivedFromGenericVersion()); + + //Archive + toscaElement.setArchived(component.isArchived() == null ? false : component.isArchived()); + toscaElement.setArchiveTime(component.getArchiveTime() == null ? 0L : component.getArchiveTime()); + toscaElement.setVspArchived(component.isVspArchived() == null ? false : component.isVspArchived()); + + toscaElement.setLifecycleState(component.getLifecycleState()); + toscaElement.setMetadataValue(JsonPresentationFields.VERSION, component.getVersion()); + if (component.getComponentType() == ComponentTypeEnum.RESOURCE) { + toscaElement.setMetadataValue(JsonPresentationFields.IS_ABSTRACT, ((Resource) component).isAbstract()); + toscaElement.setMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME, ((Resource) component).getToscaResourceName()); + toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_NAME, ((Resource) component).getVendorName()); + toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_RELEASE, ((Resource) component).getVendorRelease()); + // field isn't mandatory , but shouldn't be null(should be an empty string instead) + if (((Resource) component).getResourceVendorModelNumber() != null){ + toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, ((Resource) component).getResourceVendorModelNumber()); + } else { + toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, ""); + } + } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) { + // field isn't mandatory , but shouldn't be null(should be an empty string instead) + if (((Service) component).getServiceType() != null){ + toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, ((Service) component).getServiceType()); + } else { + toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, ""); + } + if (((Service) component).getServiceRole() != null){ + toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, ((Service) component).getServiceRole()); + } else { + toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, ""); + } + } + toscaElement.setMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL, component.getConformanceLevel()); + toscaElement.setMetadataValue(JsonPresentationFields.IS_DELETED, component.getIsDeleted()); + toscaElement.setMetadataValue(JsonPresentationFields.ICON, component.getIcon()); + toscaElement.setMetadataValue(JsonPresentationFields.DESCRIPTION, component.getDescription()); + toscaElement.setMetadataValue(JsonPresentationFields.TAGS, component.getTags()); + toscaElement.setMetadataValue(JsonPresentationFields.INVARIANT_UUID, component.getInvariantUUID()); + toscaElement.setMetadataValue(JsonPresentationFields.CONTACT_ID, component.getContactId()); + } + + + + + private static void setComponentInstancesToComponent(TopologyTemplate topologyTemplate, Component component) { + + List componentInstances = new ArrayList<>(); + ComponentInstance currComponentInstance; + Map nodeFilterComponents = topologyTemplate.getNodeFilterComponents(); + + for (Map.Entry entry : topologyTemplate.getComponentInstances().entrySet()) { + String key = entry.getKey(); + currComponentInstance = new ComponentInstance(topologyTemplate.getComponentInstances().get(key)); + if (topologyTemplate.getInstGroups() != null && topologyTemplate.getInstGroups().containsKey(key)) { + List groupInstances = topologyTemplate.getInstGroups().get(key).getMapToscaDataDefinition().entrySet().stream().map(e -> new GroupInstance(e.getValue())).collect(Collectors.toList()); + currComponentInstance.setGroupInstances(groupInstances); + } + if(nodeFilterComponents != null && nodeFilterComponents.containsKey(key)){ + currComponentInstance.setNodeFilter(nodeFilterComponents.get(key)); + } + if(topologyTemplate.getInstProperties() != null && topologyTemplate.getInstProperties().containsKey(key) && topologyTemplate.getInstProperties().get(key) != null ){ + List instanceProps = topologyTemplate.getInstProperties().get(key).getMapToscaDataDefinition().entrySet().stream().map(e -> new PropertyDefinition(e.getValue())).collect(Collectors.toList()); + currComponentInstance.setProperties(instanceProps); + } + if(topologyTemplate.getInstInputs() != null && topologyTemplate.getInstInputs().containsKey(key) && topologyTemplate.getInstInputs().get(key) != null ){ + List instanceInputs = topologyTemplate.getInstInputs().get(key).getMapToscaDataDefinition().entrySet().stream().map(e -> new InputDefinition(e.getValue())).collect(Collectors.toList()); + currComponentInstance.setInputs(instanceInputs); + } + if(topologyTemplate.getComponentInstInterfaces() != null && topologyTemplate.getComponentInstInterfaces().containsKey(key) && topologyTemplate.getComponentInstInterfaces().get(key) != null ){ + Map interfacesMap = topologyTemplate.getComponentInstInterfaces().get(key).getMapToscaDataDefinition().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + currComponentInstance.setInterfaces(interfacesMap); + } + componentInstances.add(currComponentInstance); + + } + component.setComponentInstances(componentInstances); + } + + private static void setComponentInstancesInputsToComponent(TopologyTemplate topologyTemplate, Component component) { + if (topologyTemplate.getInstInputs() != null) { + Map> inputs = new HashMap<>(); + for (Entry entry : topologyTemplate.getInstInputs().entrySet()) { + if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { + String key = entry.getKey(); + List componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceInput(e.getValue())).collect(Collectors.toList()); + inputs.put(key, componentInstanceAttributes); + } + } + component.setComponentInstancesInputs(inputs); + } + } + + private static void setComponentInstancesPropertiesToComponent(TopologyTemplate topologyTemplate, Component component) { + if (topologyTemplate.getInstProperties() != null) { + Map> properties = new HashMap<>(); + for (Entry entry : topologyTemplate.getInstProperties().entrySet()) { + if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { + String key = entry.getKey(); + List componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceProperty(new PropertyDefinition(e.getValue()))) + .collect(Collectors.toList()); + properties.put(key, componentInstanceAttributes); + } + } + component.setComponentInstancesProperties(properties); + } + } + + private static void setComponentInstancesInterfacesToComponent(TopologyTemplate topologyTemplate, Component component) { + if (topologyTemplate.getInstInterfaces() != null) { + Map> interfaces = new HashMap<>(); + for (Entry entry : topologyTemplate.getInstInterfaces().entrySet()) { + if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { + String key = entry.getKey(); + List componentInstanceInterfaces = entry.getValue() + .getMapToscaDataDefinition().entrySet().stream().map(e -> new + ComponentInstanceInterface(e.getKey(), e.getValue())) + .collect(Collectors.toList()); + interfaces.put(key, componentInstanceInterfaces); + } + } + component.setComponentInstancesInterfaces(interfaces); + } + else if (topologyTemplate.getComponentInstInterfaces() != null) { + Map> interfaces = new HashMap<>(); + for (Entry entry : topologyTemplate.getComponentInstInterfaces().entrySet()) { + if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { + String key = entry.getKey(); + List componentInstanceInterfaces = entry.getValue() + .getMapToscaDataDefinition().entrySet().stream().map(e -> new + ComponentInstanceInterface(e.getKey(), e.getValue())) + .collect(Collectors.toList()); + interfaces.put(key, componentInstanceInterfaces); + } + } + component.setComponentInstancesInterfaces(interfaces); + } + + } + + private static void setComponentInstancesAttributesToComponent(TopologyTemplate topologyTemplate, Component component) { + if (topologyTemplate.getInstAttributes() != null) { + Map> attributes = new HashMap<>(); + for (Map.Entry entry : topologyTemplate.getInstAttributes().entrySet()) { + if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { + String key = entry.getKey(); + List componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceProperty(new ComponentInstanceProperty(e.getValue()))) + .collect(Collectors.toList()); + attributes.put(key, componentInstanceAttributes); + } + } + component.setComponentInstancesAttributes(attributes); + } + } + + private static void setComponentInstancesRequirementsToComponent(TopologyTemplate topologyTemplate, Component component) { + + if (topologyTemplate.getCalculatedRequirements() != null) { + // Requirements of component organized by capability + Map> instancesRequirements = new HashMap<>(); + + Map instancesMap = new HashMap<>(); + for (ComponentInstance currInstance : component.getComponentInstances()) { + instancesMap.put(currInstance.getUniqueId(), currInstance); + } + for (Map.Entry entry : topologyTemplate.getCalculatedRequirements().entrySet()) { + + String instanceId = entry.getKey(); + // Requirements of instance organized by capability + Map capsMapList = entry.getValue().getMapToscaDataDefinition(); + + if(capsMapList != null) { + for (Entry entryTypeList : capsMapList.entrySet()) { + String capabilityType = entryTypeList.getKey(); + List caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(RequirementDefinition::new).collect(Collectors.toList()); + if (instancesRequirements.containsKey(capabilityType)) { + instancesRequirements.get(capabilityType).addAll(caps); + } else { + instancesRequirements.put(capabilityType, caps); + } + if (MapUtils.isEmpty(instancesMap.get(instanceId).getRequirements())) { + instancesMap.get(instanceId).setRequirements(new HashMap<>()); + } + instancesMap.get(instanceId).getRequirements().put(capabilityType, new ArrayList<>(caps)); + } + } + } + component.setRequirements(instancesRequirements); + } + } + + private static void setComponentInstancesCapabilitiesToComponentAndCI(TopologyTemplate topologyTemplate, Component component) { + Map calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties(); + + if (topologyTemplate.getCalculatedCapabilities() != null) { + // capabilities of component organized by type + Map> instancesCapabilities = new HashMap<>(); + + Map instancesMap = new HashMap<>(); + for (ComponentInstance currInstance : component.getComponentInstances()) { + instancesMap.put(currInstance.getUniqueId(), currInstance); + } + for (Map.Entry entry : topologyTemplate.getCalculatedCapabilities().entrySet()) { + + String instanceId = entry.getKey(); + // capabilities of instance organized by type + Map capsMapList = entry.getValue().getMapToscaDataDefinition(); + + if(capsMapList != null) { + for (Entry entryTypeList : capsMapList.entrySet()) { + String capabilityType = entryTypeList.getKey(); + List caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(cap -> mergeInstCapabiltyWithProperty(cap, instanceId, calculatedCapProperties)).collect(Collectors.toList()); + if (instancesCapabilities.containsKey(capabilityType)) { + instancesCapabilities.get(capabilityType).addAll(caps); + } else { + instancesCapabilities.put(capabilityType, caps); + } + ComponentInstance instance = instancesMap.get(instanceId); + if (instance == null) { + log.error("instance is null for id {} entry {}", instanceId, entry.getValue().getToscaPresentationValue(JsonPresentationFields.NAME)); + } else { + if (MapUtils.isEmpty(instance.getCapabilities())) { + instance.setCapabilities(new HashMap<>()); + } + instance.getCapabilities().put(capabilityType, new ArrayList<>(caps)); + } + } + } + } + component.setCapabilities(instancesCapabilities); + } + } + + private static void setCapabilitiesToComponent(TopologyTemplate topologyTemplate, Component component) { + Map capabilities = topologyTemplate.getCapabilities(); + Map capabilitiesProperties = topologyTemplate.getCapabilitiesProperties(); + Map> allCapabilities = new HashMap<>(); + + if(MapUtils.isNotEmpty(capabilities)) { + allCapabilities.putAll(groupCapabilityByType(capabilities)); + } + + if(MapUtils.isNotEmpty(capabilitiesProperties)) { + capabilitiesProperties.forEach((s, capProp)-> { + String[] result = s.split(CAP_PROP_DELIM); + if (capProp != null) { + Map capMap = capProp.getMapToscaDataDefinition(); + + if (MapUtils.isNotEmpty(capMap)) { + List capPropsList = capMap.values().stream() + .map(ComponentInstanceProperty::new).collect(Collectors.toList()); + + List cap = allCapabilities.get(result[0]); + if (cap !=null) { + Optional op = cap.stream().filter(c -> c.getName() + .equals(result[1])).findFirst(); + op.ifPresent(capabilityDefinition -> capabilityDefinition.setProperties(capPropsList)); + } + } + } + } + ); + } + Map> componentCapabilities = component.getCapabilities(); + if(MapUtils.isNotEmpty(componentCapabilities)) { + mergeCapabilityMap(allCapabilities, componentCapabilities); + } + component.setCapabilities(allCapabilities); + } + + private static void mergeCapabilityMap(Map> map1, + Map> map2) { + map1.forEach((key1, val1) -> map2.forEach((key2, val2) -> { + if(key1.equals(key2)) { + val2.addAll(val1); + } + })); + map1.putAll(map2); + } + + private static Map> groupCapabilityByType(Map capabilities) { + Map> groupedCapabilities = new HashMap<>(); + + Set typesSet = new HashSet<>(); + List allCapabilityDefinitions = new ArrayList<>(); + for (Entry capabilitiesEntry : capabilities.entrySet()) { + typesSet.addAll( capabilitiesEntry.getValue().getListToscaDataDefinition() + .stream().map(CapabilityDataDefinition::getType).collect(Collectors.toSet())); + + allCapabilityDefinitions.addAll(capabilitiesEntry.getValue().getListToscaDataDefinition() + .stream().map(CapabilityDefinition::new).collect(Collectors.toList())); + } + + for(String capType : typesSet) { + groupedCapabilities.put(capType, allCapabilityDefinitions.stream() + .filter(capabilityDefinition -> capabilityDefinition.getType() + .equals(capType)).collect(Collectors.toList())); + } + return groupedCapabilities; + } + + private static void setRequirementsToComponent(TopologyTemplate topologyTemplate, Component component) { + Map requirements = topologyTemplate.getRequirements(); + Map> componentRequirements = component.getRequirements(); + if(MapUtils.isNotEmpty(requirements)) { + if(componentRequirements == null) { + componentRequirements = new HashMap<>(); + } + componentRequirements.putAll(groupRequirementByType(requirements)); + component.setRequirements(componentRequirements); + } + } + + private static Map> groupRequirementByType(Map requirements) { + Map> groupedRequirement = new HashMap<>(); + + Set typesSet = new HashSet<>(); + List allRequirements = new ArrayList<>(); + for (Entry requirementsEntry : requirements.entrySet()) { + typesSet.addAll( requirementsEntry.getValue().getListToscaDataDefinition() + .stream().map(RequirementDataDefinition::getCapability).collect(Collectors.toSet())); + + allRequirements.addAll(requirementsEntry.getValue().getListToscaDataDefinition() + .stream().map(RequirementDefinition::new).collect(Collectors.toList())); + } + + for(String capType : typesSet) { + groupedRequirement.put(capType, allRequirements.stream().filter(requirementDefinition -> + requirementDefinition.getCapability().equals(capType)).collect(Collectors.toList())); + } + return groupedRequirement; + + } + + + private static void setCapabilitiesToComponentAndGroups(TopologyTemplate topologyTemplate, Component component) { + + Map calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties(); + + if (capabilitiesAndGroupsExist(topologyTemplate, component)) { + Map groupsMap = component.getGroups().stream().collect(Collectors.toMap(GroupDefinition::getUniqueId,Function.identity())); + + for (Map.Entry entry : topologyTemplate.getCalculatedCapabilities().entrySet()) { + findSetCapabilitiesToComponentAndGroup(calculatedCapProperties, component, groupsMap, entry); + } + } + } + + private static boolean capabilitiesAndGroupsExist(TopologyTemplate topologyTemplate, Component component) { + return MapUtils.isNotEmpty(topologyTemplate.getCalculatedCapabilities()) && CollectionUtils.isNotEmpty(component.getGroups()); + } + + private static void findSetCapabilitiesToComponentAndGroup(Map calculatedCapProperties, Component component, Map groupsMap, Map.Entry entry) { + + String uniqueId = entry.getKey(); + if(groupsMap.containsKey(uniqueId)){ + setCapabilitiesToComponentAndGroup(calculatedCapProperties, component, entry, groupsMap.get(uniqueId)); + } else { + log.warn("The group with uniqueId {} was not found", uniqueId); + } + } + + private static void setCapabilitiesToComponentAndGroup(Map calculatedCapProperties, Component component, Map.Entry entry, GroupDefinition group) { + + for (Entry entryTypeList : entry.getValue().getMapToscaDataDefinition().entrySet()) { + String capabilityType = entryTypeList.getKey(); + List caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(cap -> mergeInstCapabiltyWithProperty(cap, group.getUniqueId(), calculatedCapProperties)).collect(Collectors.toList()); + if (component.getCapabilities().containsKey(capabilityType)) { + component.getCapabilities().get(capabilityType).addAll(caps); + } else { + component.getCapabilities().put(capabilityType, caps); + } + group.getCapabilities().put(capabilityType, Lists.newArrayList(caps)); + } + } + + private static CapabilityDefinition mergeInstCapabiltyWithProperty(CapabilityDataDefinition cap, String ownerId, Map calculatedCapProperties) { + CapabilityDefinition capability = new CapabilityDefinition(cap); + if (calculatedCapProperties != null) { + MapCapabilityProperty mapOfMapPropertiesDataDefinition = calculatedCapProperties.get(ownerId); + if (mapOfMapPropertiesDataDefinition != null && mapOfMapPropertiesDataDefinition.getMapToscaDataDefinition() != null) { + Map toscaCapPropMap = mapOfMapPropertiesDataDefinition.getMapToscaDataDefinition(); + toscaCapPropMap.forEach(( keyPath, capProp)-> findConvertSetProperties(cap, ownerId, capability, keyPath, capProp)); + } + } + return capability; + } + + private static void findConvertSetProperties(CapabilityDataDefinition cap, String primaryPathKey, CapabilityDefinition capability, String path, MapPropertiesDataDefinition capProp) { + // format key of capability properties : + // VF instance in service : instanceId#ownerId#type#capName + // VFC instance in VF : instanceId#type#capName -> instanceId=ownerId + // Group in service : groupName#ownerId#type#capName + // Group in VF : groupName#type#capName -> groupName=ownerId + String[] result = path.split(CAP_PROP_DELIM); + if (result.length < 4) { + log.debug("wrong key format for capabilty, key {}", capProp); + return; + } + if (relatedPropertiesExist(cap, primaryPathKey, capProp, result)) { + capability.setProperties(capProp.getMapToscaDataDefinition().values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList())); + } + } + + private static boolean relatedPropertiesExist(CapabilityDataDefinition cap, String primaryPathKey, MapPropertiesDataDefinition capProp, String[] result) { + return capProp != null && MapUtils.isNotEmpty(capProp.getMapToscaDataDefinition()) && areRelatedProperties(cap, primaryPathKey, result); + } + + private static boolean areRelatedProperties(CapabilityDataDefinition cap, String primaryPathKey, String[] result) { + int primaryKeyIndex = 0; + int ownerIndex = 1; + int typeIndex = result.length - 2; + int nameIndex = result.length - 1; + return result[typeIndex].equals(cap.getType()) && result[nameIndex].equals(cap.getName()) && cap.getOwnerId().equals(result[ownerIndex]) && primaryPathKey.equals(result[primaryKeyIndex]); + } + + private static void setComponentInstancesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { + + Map componentInstances = new HashMap<>(); + ComponentInstanceDataDefinition convertedInstance; + if (component.getComponentInstances() != null) { + for (ComponentInstance instance : component.getComponentInstances()) { + convertedInstance = new ComponentInstanceDataDefinition(instance); + if (instance.getGroupInstances() != null) { + MapGroupsDataDefinition groupsMap = new MapGroupsDataDefinition(); + + groupsMap.setMapToscaDataDefinition(instance.getGroupInstances().stream().map(GroupInstanceDataDefinition::new).collect(Collectors.toMap(GroupInstanceDataDefinition::getName, Function.identity()))); + if (topologyTemplate.getInstGroups() == null) { + topologyTemplate.setInstGroups(new HashMap<>()); + } + topologyTemplate.getInstGroups().put(instance.getUniqueId(), groupsMap); + } + componentInstances.put(instance.getUniqueId(), convertedInstance); + } + } + topologyTemplate.setComponentInstances(componentInstances); + + } + + private static void setComponentInstancesInputsToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { + + if (component.getComponentInstancesInputs() != null) { + topologyTemplate.setInstInputs(new HashMap<>()); + MapPropertiesDataDefinition inputsMap; + for (Entry> entry : component.getComponentInstancesInputs().entrySet()) { + inputsMap = new MapPropertiesDataDefinition(); + + inputsMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity()))); + + topologyTemplate.getInstInputs().put(entry.getKey(), inputsMap); + } + } + } + + private static void setComponentInstancesPropertiesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { + + if (component.getComponentInstancesProperties() != null) { + topologyTemplate.setInstProperties(new HashMap<>()); + MapPropertiesDataDefinition propertiesMap; + for (Entry> entry : component.getComponentInstancesProperties().entrySet()) { + propertiesMap = new MapPropertiesDataDefinition(); + + propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity()))); + + topologyTemplate.getInstProperties().put(entry.getKey(), propertiesMap); + } + } + } + + private static void setComponentInstancesArtifactsToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { + + List componentInstances = component.getComponentInstances(); + if (componentInstances != null) { + topologyTemplate.setInstanceArtifacts(new HashMap<>()); + topologyTemplate.setInstDeploymentArtifacts(new HashMap<>()); + + for (ComponentInstance ci : componentInstances) { + Map artifacts = ci.getArtifacts(); + if (artifacts != null) { + Map mapToscaDataDefinitionArtifact = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + MapArtifactDataDefinition insArtifact = new MapArtifactDataDefinition(mapToscaDataDefinitionArtifact); + topologyTemplate.getInstanceArtifacts().put(ci.getUniqueId(), insArtifact); + } + + Map deplArtifacts = ci.getDeploymentArtifacts(); + if (deplArtifacts != null) { + Map mapToscaDataDefinitionDepArtifact = deplArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + MapArtifactDataDefinition insDepArtifact = new MapArtifactDataDefinition(mapToscaDataDefinitionDepArtifact); + topologyTemplate.getInstDeploymentArtifacts().put(ci.getUniqueId(), insDepArtifact); + } + } + } + } + + private static void setComponentInstancesAttributesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { + + if (component.getComponentInstancesAttributes() != null) { + topologyTemplate.setInstAttributes(new HashMap<>()); + MapPropertiesDataDefinition attributesMap; + for (Entry> entry : component.getComponentInstancesAttributes().entrySet()) { + attributesMap = new MapPropertiesDataDefinition(); + + attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity()))); + + topologyTemplate.getInstAttributes().put(entry.getKey(), attributesMap); + } + } + } + + public static ComponentMetadataData convertToComponentMetadata(GraphVertex vertex) { + ComponentMetadataData metadata = null; + switch (vertex.getType()) { + case SERVICE: + metadata = new ServiceMetadataData(vertex.getMetadataJson()); + break; + case RESOURCE: + metadata = new ResourceMetadataData(vertex.getMetadataJson()); + break; + case PRODUCT: + metadata = new ProductMetadataData(vertex.getMetadataJson()); + break; + default: + break; + } + if (metadata != null) { + metadata.getMetadataDataDefinition().setUniqueId(vertex.getUniqueId()); + metadata.getMetadataDataDefinition().setLastUpdateDate((Long) vertex.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE)); + metadata.getMetadataDataDefinition().setUUID((String) vertex.getJsonMetadataField(JsonPresentationFields.UUID)); + metadata.getMetadataDataDefinition().setState((String) vertex.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)); + } + return metadata; + } + + public static List convertToGroupDefinitions(Map groups) { + + List groupDefinitions = null; + if (MapUtils.isNotEmpty(groups)) { + groupDefinitions = groups.values().stream().map(GroupDefinition::new).collect(Collectors.toList()); + } + return groupDefinitions; + } + + public static Map extractCapabilityProperteisFromInstances(List instances, boolean fromCsar) { + return instances + .stream() + .collect(Collectors.toMap(ComponentInstanceDataDefinition::getUniqueId, + ci -> convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), ci.getUniqueId(), fromCsar))); + } + + public static Map extractCapabilityPropertiesFromGroups(List groups, boolean fromCsar) { + if(CollectionUtils.isNotEmpty(groups)) + return groups + .stream() + .collect(Collectors.toMap(GroupDefinition::getUniqueId, + g -> convertToMapOfMapCapabiltyProperties(g.getCapabilities(), g.getUniqueId(), fromCsar))); + return Maps.newHashMap(); + } + + public static Map extractCapabilitiesFromGroups(final List groupDefinitions) { + Map calculatedCapabilities = Maps.newHashMap(); + for(GroupDefinition groupDefinition :groupDefinitions){ + calculatedCapabilities.put(groupDefinition.getUniqueId(), new MapListCapabilityDataDefinition(buildMapOfListsOfCapabilities(groupDefinition))); + } + return calculatedCapabilities; + } + + public static Map buildMapOfListsOfCapabilities(GroupDefinition groupDefinition) { + return groupDefinition.getCapabilities().entrySet() + .stream() + .collect(Collectors.toMap(Map.Entry::getKey, e-> new ListCapabilityDataDefinition(e.getValue() + .stream() + .map(CapabilityDataDefinition::new) + .collect(Collectors.toList())))); + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java deleted file mode 100644 index 4babd5d4a8..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.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.jsontitan.datamodel; - -import org.openecomp.sdc.be.datatypes.elements.*; - -import java.util.List; -import java.util.Map; - -public class NodeType extends ToscaElement{ - - public NodeType() { - super(ToscaElementTypeEnum.NODE_TYPE); - } - - private List derivedFrom; - private List derivedList; - private Map attributes; - private Map interfaceArtifacts; - - public List getDerivedList() { - return derivedList; - } - - public void setDerivedList(List derivedList) { - this.derivedList = derivedList; - } - - public List getDerivedFrom() { - return derivedFrom; - } - - public void setDerivedFrom(List derivedFrom) { - this.derivedFrom = derivedFrom; - } - - public Map getAttributes() { - return attributes; - } - - public void setAttributes(Map attributes) { - this.attributes = attributes; - } - - public Map getInterfaceArtifacts() { - return interfaceArtifacts; - } - - public void setInterfaceArtifacts(Map interfaceArtifacts) { - this.interfaceArtifacts = interfaceArtifacts; - } - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java deleted file mode 100644 index 8c0253a148..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java +++ /dev/null @@ -1,311 +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.jsontitan.datamodel; - -import org.apache.commons.collections.MapUtils; -import org.openecomp.sdc.be.datatypes.elements.*; -import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; -import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.MapInterfaceInstanceDataDefinition; -import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; - -import java.util.HashMap; -import java.util.Map; - -public class TopologyTemplate extends ToscaElement{ - - public TopologyTemplate() { - super(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE); - } - private Map inputs; - private Map instInputs; - private Map heatParameters; - private Map instAttributes; - private Map instProperties; - private Map groups; - private Map policies; - private Map instGroups; - private Map serviceApiArtifacts; - private Map forwardingPaths; - private Map compositions; - private Map calculatedCapabilities; - private Map calculatedRequirements; - private Map fullfilledCapabilities; - private Map fullfilledRequirements; - private Map calculatedCapabilitiesProperties; - private Map instDeploymentArtifacts; - private Map instanceArtifacts; - private Map interfaces; - private Map instInterfaces; - private Map componentInstInterfaces; - private Map dataTypes; - - private Map nodeFilterComponents; - //Component Instances External References (instanceId -> ExternalRefsMap) - //----------------------------------------------------------------------- - private Map mapComponentInstancesExternalRefs; - - public Map getMapComponentInstancesExternalRefs() { - return this.mapComponentInstancesExternalRefs; - } - - public void setComponentInstancesExternalRefs(Map mapComponentInstancesExternalRefs) { - this.mapComponentInstancesExternalRefs = mapComponentInstancesExternalRefs; - } - //----------------------------------------------------------------------- - - public Map getInterfaces() { - return interfaces; - } - - public void setInterfaces(Map interfaces) { - this.interfaces = interfaces; - } - - public Map getInstInterfaces() { - return instInterfaces; - } - - public void setInstInterfaces( - Map instInterfaces) { - this.instInterfaces = instInterfaces; - } - - public void addInstInterface(String compId, MapInterfaceInstanceDataDefinition - mapInterfaceInstanceDataDefinition) { - if(MapUtils.isEmpty(this.instInterfaces)) { - this.instInterfaces = new HashMap<>(); - } - - this.instInterfaces.put(compId, mapInterfaceInstanceDataDefinition); - } - - public Map getComponentInstInterfaces() { - return componentInstInterfaces; - } - - public void setComponentInstInterfaces( - Map componentInstInterfaces) { - this.componentInstInterfaces = componentInstInterfaces; - } - - public void addComponentInstanceInterfaceMap(String componentInstanceId, MapInterfaceDataDefinition - mapInterfaceDataDefinition) { - if(MapUtils.isEmpty(this.componentInstInterfaces)) { - this.componentInstInterfaces = new HashMap<>(); - } - - this.componentInstInterfaces.put(componentInstanceId, mapInterfaceDataDefinition); - } - - - public Map getInputs() { - return inputs; - } - public void setInputs(Map inputs) { - this.inputs = inputs; - } - public Map getInstInputs() { - return instInputs; - } - public void setInstInputs(Map instInputs) { - this.instInputs = instInputs; - } - public Map getHeatParameters() { - return heatParameters; - } - public void setHeatParameters(Map heatParameters) { - this.heatParameters = heatParameters; - } - public Map getInstAttributes() { - return instAttributes; - } - public void setInstAttributes(Map instAttributes) { - this.instAttributes = instAttributes; - } - public Map getInstProperties() { - return instProperties; - } - public void setInstProperties(Map instProperties) { - this.instProperties = instProperties; - } - public Map getGroups() { - return groups; - } - public void setGroups(Map groups) { - this.groups = groups; - } - public Map getPolicies() { - return policies; - } - public void setPolicies(Map policies) { - this.policies = policies; - } - public Map getInstGroups() { - return instGroups; - } - public void setInstGroups(Map instGroups) { - this.instGroups = instGroups; - } - public Map getServiceApiArtifacts() { - return serviceApiArtifacts; - } - public void setServiceApiArtifacts(Map serviceApiArtifacts) { - this.serviceApiArtifacts = serviceApiArtifacts; - } - public Map getCompositions() { - return compositions; - } - public void setCompositions(Map compositions) { - this.compositions = compositions; - } - public Map getCalculatedCapabilities() { - return calculatedCapabilities; - } - public void setCalculatedCapabilities(Map calculatedCapabilities) { - this.calculatedCapabilities = calculatedCapabilities; - } - public Map getCalculatedRequirements() { - return calculatedRequirements; - } - public void setCalculatedRequirements(Map calculatedRequirements) { - this.calculatedRequirements = calculatedRequirements; - } - public Map getFullfilledCapabilities() { - return fullfilledCapabilities; - } - public void setFullfilledCapabilities(Map fullfilledCapabilities) { - this.fullfilledCapabilities = fullfilledCapabilities; - } - public Map getFullfilledRequirements() { - return fullfilledRequirements; - } - public void setFullfilledRequirements(Map fullfilledRequirements) { - this.fullfilledRequirements = fullfilledRequirements; - } - - public Map getInstDeploymentArtifacts() { - return instDeploymentArtifacts; - } - public void setInstDeploymentArtifacts(Map instDeploymentArtifacts) { - this.instDeploymentArtifacts = instDeploymentArtifacts; - } - - public Map getCalculatedCapabilitiesProperties() { - return calculatedCapabilitiesProperties; - } - public void setCalculatedCapabilitiesProperties(Map calculatedCapabilitiesProperties) { - this.calculatedCapabilitiesProperties = calculatedCapabilitiesProperties; - } - - public Map getInstanceArtifacts() { - return instanceArtifacts; - } - public void setInstanceArtifacts(Map instanceArtifacts) { - this.instanceArtifacts = instanceArtifacts; - } - - public Map getForwardingPaths() { - return forwardingPaths; - } - - public void setForwardingPaths(Map forwardingPaths) { - this.forwardingPaths = forwardingPaths; - } - - public Map getNodeFilterComponents() { - return nodeFilterComponents; - } - - public void setNodeFilterComponents(Map nodeFilters) { - this.nodeFilterComponents = nodeFilters; - } - - /** - * Gets data types. - * @return Current data types. - */ - public Map getDataTypes() { - return dataTypes; - } - - /** - * Sets data types. - * @param dataTypes New data types. - */ - public void setDataTypes(Map dataTypes) { - this.dataTypes = dataTypes; - } - - /** - * Adds component instance to composition of topology template - * Note that component instance will be overrided in case if the topology template already contains a component instance with the same name - * @param componentInstance - */ - public void addComponentInstance(ComponentInstanceDataDefinition componentInstance){ - if(getCompositions() == null){ - compositions = new HashMap<>(); - } - if(MapUtils.isEmpty(getCompositions())){ - compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), new CompositionDataDefinition()); - } - if(MapUtils.isEmpty(getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances())){ - getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).setComponentInstances(new HashMap<>()); - } - getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances().put(componentInstance.getUniqueId(), componentInstance); - } - /** - * Returns map of component instances from composition - * @return - */ - public Map getComponentInstances() { - Map instances = null; - if(getCompositions() != null && getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()) != null ){ - instances = getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances(); - } - return instances; - } - - - /** - * Sets map of component instances to composition of topology template - * Note that component instances will be overrided in case if the topology template already contains a component instances - * @param instances - */ - public void setComponentInstances(Map instances) { - if(getCompositions() == null){ - compositions = new HashMap<>(); - } - if(MapUtils.isEmpty(getCompositions())){ - compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), new CompositionDataDefinition()); - } - getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).setComponentInstances(instances); - } - public Map getRelations() { - Map relations = null; - if( getCompositions() != null && getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()) != null ){ - relations = getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getRelations(); - } - return relations; - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElement.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElement.java deleted file mode 100644 index a18c75bca7..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElement.java +++ /dev/null @@ -1,344 +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.jsontitan.datamodel; - -import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation; -import org.slf4j.MDC; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -public abstract class ToscaElement { - - protected Map metadata; - protected List categories; - protected Map toscaArtifacts; - private Map artifacts; - private Map deploymentArtifacts; - private Map additionalInformation; - private Map properties; - private Map capabilities; - private Map capabiltiesProperties; - private Map requirements; - - protected ToscaElementTypeEnum toscaType; - // User - private String creatorUserId; - private String creatorFullName; - private String lastUpdaterUserId; - private String lastUpdaterFullName; - - private Map allVersions; - - public ToscaElement(ToscaElementTypeEnum toscaType){ - this.toscaType = toscaType; - } - - public Map getMetadata() { - return metadata; - } - - public void setMetadata(Map metadata) { - this.metadata = metadata; - } - - public List getCategories() { - return categories; - } - - public void setCategories(List categories) { - this.categories = categories; - } - public Map getToscaArtifacts() { - return toscaArtifacts; - } - - public void setToscaArtifacts(Map toscaArtifacts) { - this.toscaArtifacts = toscaArtifacts; - } - - public ToscaElementTypeEnum getToscaType() { - return toscaType; - } - - public void setToscaType(ToscaElementTypeEnum toscaType) { - this.toscaType = toscaType; - } - public Map getArtifacts() { - return artifacts; - } - - public void setArtifacts(Map artifacts) { - this.artifacts = artifacts; - } - - public Map getDeploymentArtifacts() { - return deploymentArtifacts; - } - - public void setDeploymentArtifacts(Map deploymentArtifacts) { - this.deploymentArtifacts = deploymentArtifacts; - } - public Map getAdditionalInformation() { - return additionalInformation; - } - public void setAdditionalInformation(Map additionalInformation) { - this.additionalInformation = additionalInformation; - } - public Map getProperties() { - return properties; - } - public void setProperties(Map properties) { - this.properties = properties; - } - - public Map getAllVersions() { - return allVersions; - } - - public void setAllVersions(Map allVersions) { - this.allVersions = allVersions; - } - - public Map getCapabilities() { - return capabilities; - } - - public void setCapabilities(Map capabilities) { - this.capabilities = capabilities; - } - - public Map getRequirements() { - return requirements; - } - - public void setRequirements(Map requirements) { - this.requirements = requirements; - } - - public Map getCapabilitiesProperties() { - return capabiltiesProperties; - } - - public void setCapabilitiesProperties(Map capabiltiesProperties) { - this.capabiltiesProperties = capabiltiesProperties; - } - - // metadata properties - // ---------------------------- - public Object getMetadataValue(JsonPresentationFields name) { - return getMetadataValueOrDefault(name, null); - } - - public Object getMetadataValueOrDefault(JsonPresentationFields name, Object defaultVal) { - if (metadata != null) { - return metadata.getOrDefault(name.getPresentation(), defaultVal); - } - return null; - } - - public void setMetadataValue(JsonPresentationFields name, Object value) { - if (metadata == null) { - metadata = new HashMap<>(); - } - metadata.put(name.getPresentation(), value); - - } - // -------------------- - public String getUUID() { - return (String) getMetadataValue(JsonPresentationFields.UUID); - } - - public void setUUID(String uuid) { - setMetadataValue(JsonPresentationFields.UUID, uuid); - } - - public String getVersion() { - return (String) getMetadataValue(JsonPresentationFields.VERSION); - } - - public String getNormalizedName() { - return (String) getMetadataValue(JsonPresentationFields.NORMALIZED_NAME); - } - - public void setNormalizedName(String normaliseComponentName) { - setMetadataValue(JsonPresentationFields.NORMALIZED_NAME, normaliseComponentName); - } - - public String getName() { - return (String) getMetadataValue(JsonPresentationFields.NAME); - } - - public String getSystemName() { - return (String) getMetadataValue(JsonPresentationFields.SYSTEM_NAME); - } - public void setSystemName(String systemName) { - setMetadataValue(JsonPresentationFields.SYSTEM_NAME, systemName); - } - - public void setLifecycleState(LifecycleStateEnum state) { - if(state != null) - setMetadataValue(JsonPresentationFields.LIFECYCLE_STATE, state.name()); - } - - public LifecycleStateEnum getLifecycleState() { - return LifecycleStateEnum.findState( (String) getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); - } - - public Long getCreationDate() { - return (Long) getMetadataValue(JsonPresentationFields.CREATION_DATE); - } - - public void setCreationDate(Long currentDate) { - setMetadataValue(JsonPresentationFields.CREATION_DATE, currentDate); - } - - public void setLastUpdateDate(Long currentDate) { - setMetadataValue(JsonPresentationFields.LAST_UPDATE_DATE, currentDate); - } - public Long getLastUpdateDate() { - return (Long) getMetadataValue(JsonPresentationFields.LAST_UPDATE_DATE); - } - - public String getUniqueId() { - return (String) getMetadataValue(JsonPresentationFields.UNIQUE_ID); - } - public void setUniqueId(String uniqueId) { - setMetadataValue(JsonPresentationFields.UNIQUE_ID, uniqueId); - } - - public void setHighestVersion(Boolean isHighest) { - setMetadataValue(JsonPresentationFields.HIGHEST_VERSION, isHighest); - - } - public Boolean isHighestVersion() { - return (Boolean) getMetadataValue(JsonPresentationFields.HIGHEST_VERSION); - - } - public ResourceTypeEnum getResourceType() { - String resourceType = (String) getMetadataValue(JsonPresentationFields.RESOURCE_TYPE); - return resourceType != null ? ResourceTypeEnum.valueOf(resourceType) : null; - } - - public void setResourceType(ResourceTypeEnum resourceType) { - if(resourceType != null) - setMetadataValue(JsonPresentationFields.RESOURCE_TYPE, resourceType.name()); - } - - public ComponentTypeEnum getComponentType() { - return ComponentTypeEnum.valueOf((String) getMetadataValue(JsonPresentationFields.COMPONENT_TYPE)); - } - - public void setComponentType(ComponentTypeEnum componentType) { - if(componentType != null) - setMetadataValue(JsonPresentationFields.COMPONENT_TYPE, componentType.name()); - } - - public String getDerivedFromGenericType(){ - return (String) getMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_TYPE); - } - - public void setDerivedFromGenericType(String derivedFromGenericType){ - setMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_TYPE, derivedFromGenericType); - } - - public String getDerivedFromGenericVersion(){ - return (String) getMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_VERSION); - } - - public void setDerivedFromGenericVersion(String derivedFromGenericVersion){ - setMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_VERSION, derivedFromGenericVersion); - } - - public Boolean isArchived() { return (Boolean) getMetadataValue(JsonPresentationFields.IS_ARCHIVED); } - - public void setArchived(Boolean archived) { setMetadataValue(JsonPresentationFields.IS_ARCHIVED, archived); } - - public Long getArchiveTime() { - Object archiveTime = getMetadataValue(JsonPresentationFields.ARCHIVE_TIME); - if (archiveTime instanceof Integer){ - return new Long((Integer)getMetadataValue(JsonPresentationFields.ARCHIVE_TIME)); - } - return (Long)archiveTime; - } - - public void setArchiveTime(Long archiveTime) { setMetadataValue(JsonPresentationFields.ARCHIVE_TIME, archiveTime); } - - public Boolean isVspArchived() { return (Boolean) getMetadataValue(JsonPresentationFields.IS_VSP_ARCHIVED); } - - public void setVspArchived(Boolean vspArchived) { setMetadataValue(JsonPresentationFields.IS_VSP_ARCHIVED, vspArchived); } - - public String getCreatorUserId() { - return creatorUserId; - } - - public void setCreatorUserId(String creatorUserId) { - this.creatorUserId = creatorUserId; - } - - public String getCreatorFullName() { - return creatorFullName; - } - - public void setCreatorFullName(String creatorFullName) { - this.creatorFullName = creatorFullName; - } - - public String getLastUpdaterUserId() { - return lastUpdaterUserId; - } - - public void setLastUpdaterUserId(String lastUpdaterUserId) { - this.lastUpdaterUserId = lastUpdaterUserId; - } - - public String getLastUpdaterFullName() { - return lastUpdaterFullName; - } - - public void setLastUpdaterFullName(String lastUpdaterFullName) { - this.lastUpdaterFullName = lastUpdaterFullName; - } - - public void generateUUID() { - String prevUUID = getUUID(); - String version = getVersion(); - if ((prevUUID == null && NodeTypeOperation.uuidNormativeNewVersion.matcher(version).matches()) || NodeTypeOperation.uuidNewVersion.matcher(version).matches()) { - UUID uuid = UUID.randomUUID(); - setUUID(uuid.toString()); - MDC.put("serviceInstanceID", uuid.toString()); - } - } - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnum.java deleted file mode 100644 index 3ee492b9bb..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnum.java +++ /dev/null @@ -1,49 +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.jsontitan.datamodel; - -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; - -public enum ToscaElementTypeEnum { - NODE_TYPE("node_type"), - TOPOLOGY_TEMPLATE("topology_template"); - - String value; - private ToscaElementTypeEnum(String value){ - this.value = value; - } - - public static VertexTypeEnum getVertexTypeByToscaType(ToscaElementTypeEnum toscaType ){ - switch ( toscaType ){ - case NODE_TYPE : - return VertexTypeEnum.NODE_TYPE; - case TOPOLOGY_TEMPLATE : - return VertexTypeEnum.TOPOLOGY_TEMPLATE; - default : - return null; - } - } - - public String getValue() { - return value; - } - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnum.java deleted file mode 100644 index 2a4496e793..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnum.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.jsontitan.enums; - -public enum JsonConstantKeysEnum { - - COMPOSITION("composition"), - CAPABILITIES("capabilities"), - REQUIREMENTS("requirements"), - PROPERTIES("properties"), - INPUTS("inputs"), - GROUPS("groups"), - INSTANCE_PROPERIES("instanceProperties"); - - private String value; - - private JsonConstantKeysEnum(String value) { - this.value = value; - } - - public String getValue() { - return value; - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArchiveOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArchiveOperation.java deleted file mode 100644 index f4033a2ffb..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArchiveOperation.java +++ /dev/null @@ -1,284 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; -import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.util.*; -import java.util.stream.Collectors; - -import static org.openecomp.sdc.be.model.jsontitan.operations.ArchiveOperation.Action.ARCHIVE; -import static org.openecomp.sdc.be.model.jsontitan.operations.ArchiveOperation.Action.RESTORE; - -/** - * Created by yavivi on 25/03/2018. - */ -@Component -public class ArchiveOperation extends BaseOperation { - - private static final Logger log = Logger.getLogger(ArchiveOperation.class.getName()); - - @Autowired - private IGraphLockOperation graphLockOperation; - - public enum Action { - ARCHIVE, RESTORE; - } - - public ArchiveOperation(TitanDao titanDao, IGraphLockOperation graphLockOperation){ - this.titanDao = titanDao; - this.graphLockOperation = graphLockOperation; - } - - public Either, ActionStatus> archiveComponent(String componentId) { - final Either vertexResult = this.titanDao.getVertexById(componentId); - if (vertexResult.isLeft()){ - return doAction(ARCHIVE, vertexResult.left().value()); - } else { - return Either.right(onError(ARCHIVE.name(), componentId, vertexResult.right().value())); - } - } - - public Either, ActionStatus> restoreComponent(String componentId) { - final Either vertexResult = this.titanDao.getVertexById(componentId); - if (vertexResult.isLeft()){ - return doAction(RESTORE, vertexResult.left().value()); - } else { - return Either.right(onError(RESTORE.name(), componentId, vertexResult.right().value())); - } - } - - public ActionStatus onVspRestored(String csarId){ - return onVspStateChanged(RESTORE, csarId); - } - - public ActionStatus onVspArchived(String csarId){ - return onVspStateChanged(ARCHIVE, csarId); - } - - private ActionStatus onVspStateChanged(Action action, String csarId) { - Map props = new HashMap<>(); - props.put(GraphPropertyEnum.CSAR_UUID, csarId); - Either, TitanOperationStatus> vfsE = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props); - return vfsE.either(vList -> setVspArchived(action, vList), s -> onError("VSP_"+action.name(), csarId, s)); - } - - private ActionStatus setVspArchived(Action action, List vList) { - if (!vList.isEmpty()) { - //Find & Lock the highest version component - GraphVertex highestVersion = this.getHighestVersionFrom(vList.get(0)); - StorageOperationStatus lockStatus = this.graphLockOperation.lockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType()); - if (lockStatus != StorageOperationStatus.OK){ - return onError(action.name(), highestVersion.getUniqueId(), TitanOperationStatus.ALREADY_LOCKED); - } - - try { - //Set isVspArchived flag - for (GraphVertex v : vList) { - boolean val = action == ARCHIVE ? true : false; - v.setJsonMetadataField(JsonPresentationFields.IS_VSP_ARCHIVED, val); - v.addMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED, val); - titanDao.updateVertex(v); - } - return commitAndCheck("VSP_"+action.name(), vList.toString()); - } finally { - this.graphLockOperation.unlockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType()); - } - - } - return ActionStatus.OK; - } - - public List setArchivedOriginsFlagInComponentInstances(GraphVertex compositionService) { - List ciUidsWithArchivedOrigins = new LinkedList(); - Either, TitanOperationStatus> instanceOfVerticesE = titanDao.getChildrenVertecies(compositionService, EdgeLabelEnum.INSTANCE_OF, JsonParseFlagEnum.NoParse); - Either, TitanOperationStatus> proxyOfVerticesE = titanDao.getChildrenVertecies(compositionService, EdgeLabelEnum.PROXY_OF, JsonParseFlagEnum.NoParse); - - List all = new LinkedList<>(); - if (instanceOfVerticesE.isLeft()){ - all.addAll(instanceOfVerticesE.left().value()); - } - if (proxyOfVerticesE.isLeft()){ - all.addAll(proxyOfVerticesE.left().value()); - } - - List archivedOrigins = all.stream().filter(v -> Boolean.TRUE.equals(v.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED))).collect(Collectors.toList()); - List archivedOriginsUids = archivedOrigins.stream().map(GraphVertex::getUniqueId).collect(Collectors.toList()); - - Map compositionsJson = (Map) compositionService.getJson(); - - if (compositionsJson != null) { - CompositionDataDefinition composition = compositionsJson.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - if (composition != null) { - - //Get all component instances from composition - Map componentInstances = composition.getComponentInstances(); - - //Extract component instances uids that has archived origins - ciUidsWithArchivedOrigins = componentInstances. - values(). - stream(). - //filter CIs whose origins are marked as archived (componentUid is in archivedOriginsUids) the second condition handles the PROXY_OF case) - filter(ci -> archivedOriginsUids.contains(ci.getComponentUid()) || archivedOriginsUids.contains(ci.getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID))). - map(ComponentInstanceDataDefinition::getUniqueId).collect(Collectors.toList()); - - //set archived origins flag - componentInstances. - values(). - stream(). - filter(ci -> archivedOriginsUids.contains(ci.getComponentUid()) || archivedOriginsUids.contains(ci.getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID))). - forEach( ci -> ci.setOriginArchived(true)); - - } - } - - return ciUidsWithArchivedOrigins; - } - - private Either, ActionStatus> doAction(Action action, GraphVertex componentVertex){ - - GraphVertex highestVersion = this.getHighestVersionFrom(componentVertex); - - if (action.equals(ARCHIVE) && isInCheckoutState(highestVersion)) { - return Either.right(ActionStatus.INVALID_SERVICE_STATE); - } - - //Lock the Highest Version - StorageOperationStatus lockStatus = this.graphLockOperation.lockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType()); - if (lockStatus != StorageOperationStatus.OK){ - return Either.right(onError(action.name(), componentVertex.getUniqueId(), TitanOperationStatus.ALREADY_LOCKED)); - } - - //Refetch latest version with full parsing - highestVersion = this.titanDao.getVertexById(highestVersion.getUniqueId(), JsonParseFlagEnum.ParseAll).left().value(); - - try { - //Get Catalog and Archive Roots - GraphVertex catalogRoot = titanDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT).left().value(); - GraphVertex archiveRoot = titanDao.getVertexByLabel(VertexTypeEnum.ARCHIVE_ROOT).left().value(); - - if (action == ARCHIVE) { - archiveEdges(catalogRoot, archiveRoot, highestVersion); - } else if (action == RESTORE) { - restoreEdges(catalogRoot, archiveRoot, highestVersion); - } - setPropertiesByAction(highestVersion, action); - titanDao.updateVertex(highestVersion); - - List affectedComponentIds = handleParents(highestVersion, catalogRoot, archiveRoot, action); - ActionStatus sc = commitAndCheck(action.name(), highestVersion.getUniqueId()); - return sc == ActionStatus.OK ? Either.left(affectedComponentIds) : Either.right(sc); - } finally { - this.graphLockOperation.unlockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType()); - } - } - - private ActionStatus commitAndCheck(String action, String componentId) { - TitanOperationStatus status = titanDao.commit(); - if (!status.equals(TitanOperationStatus.OK)){ - return onError(action, componentId, status); - } - return ActionStatus.OK; - } - - private boolean isInCheckoutState(GraphVertex v) { - if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name().equals(v.getMetadataProperty(GraphPropertyEnum.STATE))){ - return true; - } - return false; - } - - /** - * Walks on children until highest version is reached - * @param v - * @return - */ - private GraphVertex getHighestVersionFrom(GraphVertex v) { - Either childVertexE = titanDao.getChildVertex(v, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); - GraphVertex highestVersionVertex = v; - - while (childVertexE.isLeft()) { - highestVersionVertex = childVertexE.left().value(); - childVertexE = titanDao.getChildVertex(highestVersionVertex, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); - } - return highestVersionVertex; - } - - private boolean isHighestVersion(GraphVertex v){ - Boolean highest = (Boolean) v.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); - return highest != null && highest; - } - - private List handleParents(GraphVertex v, GraphVertex catalogRoot, GraphVertex archiveRoot, Action action) { - Either parentVertexE = titanDao.getParentVertex(v, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll); - List affectedCompIds = new ArrayList(); - affectedCompIds.add(v.getUniqueId()); - - while (parentVertexE.isLeft()){ - GraphVertex cv = parentVertexE.left().value(); - affectedCompIds.add(cv.getUniqueId()); - boolean isHighestVersion = isHighestVersion(cv); - if (isHighestVersion){ - if (action == ARCHIVE) { - archiveEdges(catalogRoot, archiveRoot, cv); - } else { - restoreEdges(catalogRoot, archiveRoot, cv); - } - } - setPropertiesByAction(cv, action); - titanDao.updateVertex(cv); - parentVertexE = titanDao.getParentVertex(cv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll); - } - return affectedCompIds; - } - - private void archiveEdges(GraphVertex catalogRoot, GraphVertex archiveRoot, GraphVertex v) { - titanDao.deleteAllEdges(catalogRoot, v, EdgeLabelEnum.CATALOG_ELEMENT); - titanDao.createEdge(archiveRoot, v, EdgeLabelEnum.ARCHIVE_ELEMENT, null); - setPropertiesByAction(v, ARCHIVE); - } - - private void restoreEdges(GraphVertex catalogRoot, GraphVertex archiveRoot, GraphVertex v) { - titanDao.deleteAllEdges(archiveRoot, v, EdgeLabelEnum.ARCHIVE_ELEMENT); - titanDao.createEdge(catalogRoot, v, EdgeLabelEnum.CATALOG_ELEMENT, null); - setPropertiesByAction(v, RESTORE); - } - - private void setPropertiesByAction(GraphVertex v, Action action) { - long now = System.currentTimeMillis(); - - boolean isArchived = action == ARCHIVE ? true : false; - v.addMetadataProperty(GraphPropertyEnum.IS_ARCHIVED, isArchived); - v.addMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME, now); - v.setJsonMetadataField(JsonPresentationFields.IS_ARCHIVED, isArchived); - v.setJsonMetadataField(JsonPresentationFields.ARCHIVE_TIME, now); - } - - private ActionStatus onError(String action, String componentId, TitanOperationStatus s) { - ActionStatus ret = ActionStatus.GENERAL_ERROR; - if (s == TitanOperationStatus.NOT_FOUND){ - ret = ActionStatus.RESOURCE_NOT_FOUND; - } else if (s == TitanOperationStatus.ALREADY_LOCKED) { - ret = ActionStatus.COMPONENT_IN_USE; - } - String retCodeVal = ret.name(); - log.error("error occurred when trying to {} {}. Return code is: {}", action, componentId, retCodeVal); - return ret; - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java deleted file mode 100644 index 3eb6a5211c..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java +++ /dev/null @@ -1,758 +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.jsontitan.operations; - -import fj.data.Either; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.tuple.ImmutableTriple; -import org.apache.commons.lang3.tuple.Triple; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.HeatParameterDefinition; -import org.openecomp.sdc.be.model.InterfaceDefinition; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; -import org.openecomp.sdc.common.api.ArtifactTypeEnum; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.slf4j.MDC; - -import java.util.*; -import java.util.Map.Entry; -import java.util.stream.Collectors; - -@org.springframework.stereotype.Component("artifacts-operations") - -public class ArtifactsOperations extends BaseOperation { - private static final String FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR = "failed to fetch {} for tosca element with id {}, error {}"; - private static final Logger log = Logger.getLogger(ArtifactsOperations.class.getName()); - - public Either addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, String instanceId) { - - String artifactId = artifactInfo.getUniqueId(); - if (artifactId == null && artifactInfo.getEsId() != null) { - artifactId = artifactInfo.getEsId(); - } - Either status = updateArtifactOnGraph(parentId, artifactInfo, type, artifactId, instanceId, false, false); - if (status.isRight()) { - - log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), parentId, status.right().value()); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value())); - return Either.right(status.right().value()); - } else { - - ArtifactDataDefinition artifactData = status.left().value(); - - ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactInfo, artifactData); - log.debug("The returned ArtifactDefintion is {}", artifactDefResult); - return Either.left(artifactDefResult); - } - - } - - public Either updateArtifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId, NodeTypeEnum type, String instanceId) { - - Either status = updateArtifactOnGraph(id, artifactInfo, type, artifactId, instanceId, true, false); - if (status.isRight()) { - - log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), id, status.right().value()); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value())); - return Either.right(status.right().value()); - } else { - - ArtifactDataDefinition artifactData = status.left().value(); - - ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactInfo, artifactData); - log.debug("The returned ArtifactDefintion is {}", artifactDefResult); - return Either.left(artifactDefResult); - } - } - - public Either isCloneNeeded(String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum type) { - ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); - - Triple triple = getEdgeLabelEnumFromArtifactGroupType(groupType, type); - EdgeLabelEnum edgeLabelEnum = triple.getLeft(); - return super.isCloneNeeded(parentId, edgeLabelEnum); - } - - public Either getArtifactById(String parentId, String id) { - return getArtifactById(parentId, id, null, null); - } - - public Either getArtifactById(String parentId, String id, ComponentTypeEnum componentType, String containerId) { - Either result = null; - ArtifactDataDefinition foundArtifact = null; - if (componentType != null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { - foundArtifact = getInstanceArtifactByLabelAndId(parentId, id, containerId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); - if (foundArtifact == null) { - foundArtifact = getInstanceArtifactByLabelAndId(parentId, id, containerId, EdgeLabelEnum.INSTANCE_ARTIFACTS); - } - } - if (foundArtifact == null) { - foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); - } - if (foundArtifact == null) { - foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.TOSCA_ARTIFACTS); - } - - if (foundArtifact == null) { - foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.ARTIFACTS); - } - - if (foundArtifact == null) { - foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.SERVICE_API_ARTIFACTS); - } - if (foundArtifact == null) { - foundArtifact = findInterfaceArtifact(parentId, id); - - } - - if (foundArtifact == null) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - return result; - } - - ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(null, foundArtifact); - return Either.left(artifactDefResult); - - } - private ArtifactDataDefinition findInterfaceArtifact(String parentId, String id) { - Either, TitanOperationStatus> dataFromGraph = getDataFromGraph(parentId, EdgeLabelEnum.INTERFACE); - if (dataFromGraph.isRight()){ - log.debug("failed to fetch interfaces {} for tosca element with id {}, error {}", id, parentId ,dataFromGraph.right().value()); - return null; - } - - Map interfaceDefinitionMap = dataFromGraph.left().value(); - if(interfaceDefinitionMap == null) { - return null; - } - Collection interfaces = interfaceDefinitionMap.values(); - if (interfaces == null){ - return null; - } - for (InterfaceDataDefinition interfaceDataDefinition : interfaces){ - Map operationsMap = interfaceDataDefinition.getOperations(); - if (operationsMap == null) { - return null; - } - ArtifactDataDefinition implementationArtifact = getArtifactDataDefinition(id, operationsMap); - if (implementationArtifact != null) - return implementationArtifact; - } - return null; - } - - private ArtifactDataDefinition getArtifactDataDefinition(String id, - Map operationsMap) { - for(OperationDataDefinition operationDataDefinition : operationsMap.values()){ - ArtifactDataDefinition implementationArtifact = operationDataDefinition.getImplementation(); - if(implementationArtifact != null){ - String uniqueId = implementationArtifact.getUniqueId(); - if (id.equals(uniqueId)) { - return implementationArtifact; - } - } - } - return null; - } - - - public Either removeArifactFromResource(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { - Either status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact); - - if (status.isRight()) { - - log.debug("Failed to delete artifact {} of resource {}", artifactId, id); - - BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete Artifact", artifactId, String.valueOf(status.right().value())); - return Either.right(status.right().value()); - } else { - - return Either.left(status.left().value()); - } - } - - public Either, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) { - - Triple triple = getEdgeLabelEnumFromArtifactGroupType(groupType, parentType); - EdgeLabelEnum edgeLabelEnum = triple.getLeft(); - - Either, TitanOperationStatus> foundArtifact = null; - Map resMap = new HashMap<>(); - foundArtifact = getArtifactByLabel(parentId, instanceId, edgeLabelEnum); - if (foundArtifact.isRight()) { - log.debug("Failed to find artifact in component {} with label {} ", parentId, edgeLabelEnum); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(foundArtifact.right().value())); - } - - resMap.putAll(foundArtifact.left().value()); - - return Either.left(resMap); - } - - /** - * @param parentId the id of the instance container - * @param instanceId the id of the instance of which to return its artifacts - * @return instance and instance deployment artifacts mapped by artifact label name - */ - public Either, StorageOperationStatus> getAllInstanceArtifacts(String parentId, String instanceId) { - Map resMap = new HashMap<>(); - Either, TitanOperationStatus> instArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INSTANCE_ARTIFACTS); - if (instArtifacts.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(instArtifacts.right().value())); - } - Either, TitanOperationStatus> deployInstArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); - if (deployInstArtifacts.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deployInstArtifacts.right().value())); - } - resMap.putAll(instArtifacts.left().value()); - resMap.putAll(deployInstArtifacts.left().value()); - return Either.left(convertArtifactMapToArtifactDefinitionMap(resMap)); - } - - public Either, StorageOperationStatus> getArtifacts(String parentId) { - - Either, TitanOperationStatus> foundArtifact = null; - Map resMap = new HashMap<>(); - foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.ARTIFACTS); - if (foundArtifact.isLeft()) { - resMap.putAll(foundArtifact.left().value()); - - } - foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); - if (foundArtifact.isLeft()) { - resMap.putAll(foundArtifact.left().value()); - - } - foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.TOSCA_ARTIFACTS); - if (foundArtifact.isLeft()) { - resMap.putAll(foundArtifact.left().value()); - - } - - return Either.left(resMap); - - } - - public Either removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { - - Either artifactData = this.getArtifactById(id, artifactId); - if (artifactData.isRight()) { - log.debug("Failed to find artifact in component {} with id {} ", id, artifactId); - return Either.right(artifactData.right().value()); - } - ArtifactDataDefinition artifactDefinition = artifactData.left().value(); - boolean isMandatory = false; - if ((artifactDefinition.getMandatory() || artifactDefinition.getServiceApi()) && !deleteMandatoryArtifact) { - // return Either.left(artifactData.left().value()); - isMandatory = true; - } - - Triple triple = getEdgeLabelEnumFromArtifactGroupType(artifactDefinition.getArtifactGroupType(), type); - EdgeLabelEnum edgeLabelEnum = triple.getLeft(); - VertexTypeEnum vertexTypeEnum = triple.getRight(); - - if (!isMandatory) { - StorageOperationStatus status = deleteToscaDataElement(id, edgeLabelEnum, vertexTypeEnum, artifactDefinition.getArtifactLabel(), JsonPresentationFields.ARTIFACT_LABEL); - if (status != StorageOperationStatus.OK) - return Either.right(status); - } - - return Either.left(artifactData.left().value()); - - } - - public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion, boolean isUpdate, EdgeLabelEnum edgeLabel) { - if (oldVesrion == null || oldVesrion.isEmpty()) - oldVesrion = "0"; - - String currentChecksum = artifactData.getArtifactChecksum(); - - if (isUpdate) { - ArtifactTypeEnum type = ArtifactTypeEnum.findType(artifactData.getArtifactType()); - switch (type) { - case HEAT_ENV: - if (edgeLabel == EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS) { - generateUUID(artifactData, oldVesrion); - } else { - updateVersionAndDate(artifactData, oldVesrion); - } - break; - case HEAT: - case HEAT_NET: - case HEAT_VOL: - generateUUID(artifactData, oldVesrion); - break; - default: - if (oldChecksum == null || oldChecksum.isEmpty()) { - if (currentChecksum != null) { - generateUUID(artifactData, oldVesrion); - } - } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) { - generateUUID(artifactData, oldVesrion); - } - break; - } - } else { - if (oldChecksum == null || oldChecksum.isEmpty()) { - if (currentChecksum != null) { - generateUUID(artifactData, oldVesrion); - } - } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) { - generateUUID(artifactData, oldVesrion); - } - } - } - - // @TODO add implementation - - public Either, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType) { - return null; - } - - public Either addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String componentId, NodeTypeEnum parentType, boolean failIfExist, String instanceId) { - artifactHeatEnv.setGeneratedFromId(artifactHeat.getUniqueId()); - return addArifactToComponent(artifactHeatEnv, componentId, parentType, failIfExist, instanceId); - } - - public Either getHeatArtifactByHeatEnvId(String parentId, ArtifactDefinition heatEnv, NodeTypeEnum parentType, String containerId, ComponentTypeEnum componentType) { - String id = heatEnv.getGeneratedFromId(); - ComponentTypeEnum compType; - switch (parentType) { - case ResourceInstance: - compType = ComponentTypeEnum.RESOURCE_INSTANCE; - break; - default: - compType = componentType; - } - return getArtifactById(parentId, id, compType, containerId); - } - - public Either updateHeatEnvArtifact(String id, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, String instanceId) { - - Either, TitanOperationStatus> artifactsEither = getArtifactByLabel(id, instanceId, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); - if (artifactsEither.isRight()) { - log.debug("Failed to find artifacts in component {} with id {} ", id, artifactsEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(artifactsEither.right().value())); - } - - Map artifacts = artifactsEither.left().value(); - List envList = artifacts.values().stream().filter(a -> a.getGeneratedFromId() != null && a.getGeneratedFromId().equals(artifactId)).collect(Collectors.toList()); - if (envList != null && !envList.isEmpty()) { - envList.forEach(a -> { - a.setGeneratedFromId(newArtifactId); - updateArtifactOnResource(a, id, a.getUniqueId(), type, instanceId); - - }); - - } - return Either.left(artifactEnvInfo); - } - - public Either updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type) { - return updateArtifactOnResource(artifactInfo, parentId, artifactInfo.getUniqueId(), type, null); - } - - - ///////////////////////////////////////////// private methods //////////////////////////////////////////////////// - - protected ArtifactDefinition convertArtifactDataToArtifactDefinition(ArtifactDefinition artifactInfo, ArtifactDataDefinition artifactDefResult) { - log.debug("The object returned after create property is {}", artifactDefResult); - - ArtifactDefinition propertyDefResult = new ArtifactDefinition(artifactDefResult); - if (artifactInfo != null) - propertyDefResult.setPayload(artifactInfo.getPayloadData()); - - List parameters = new ArrayList<>(); - /* - * StorageOperationStatus heatParametersOfNode = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefResult.getUniqueId().toString(), parameters); if ((heatParametersOfNode.equals(StorageOperationStatus.OK)) - * && !parameters.isEmpty()) { propertyDefResult.setHeatParameters(parameters); } - */ - return propertyDefResult; - } - - private ArtifactDataDefinition getInstanceArtifactByLabelAndId(String parentId, String id, String containerId, EdgeLabelEnum edgeLabelEnum) { - ArtifactDataDefinition foundArtifact = null; - Either, TitanOperationStatus> artifactsEither = getDataFromGraph(containerId, edgeLabelEnum); - if (artifactsEither.isRight()) { - log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, containerId, artifactsEither.right().value()); - return null; - } - - Map artifacts = artifactsEither.left().value(); - - MapArtifactDataDefinition artifactsPerInstance = artifacts.get(parentId); - if (artifactsPerInstance == null) { - log.debug("failed to fetch artifacts for instance {} in tosca element with id {}, error {}", parentId, containerId, artifactsEither.right().value()); - return null; - } - Optional op = artifactsPerInstance.getMapToscaDataDefinition().values().stream().filter(p -> p.getUniqueId().equals(id)).findAny(); - if (op.isPresent()) { - foundArtifact = op.get(); - } - return foundArtifact; - } - - private ArtifactDataDefinition getArtifactByLabelAndId(String parentId, String id, EdgeLabelEnum edgeLabelEnum) { - ArtifactDataDefinition foundArtifact = null; - Either, TitanOperationStatus> artifactsEither = getDataFromGraph(parentId, edgeLabelEnum); - if (artifactsEither.isRight()) { - log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, parentId, artifactsEither.right().value()); - return null; - } - - Map artifacts = artifactsEither.left().value(); - Optional op = artifacts.values().stream().filter(p -> p.getUniqueId().equals(id)).findAny(); - if (op.isPresent()) { - foundArtifact = op.get(); - } - return foundArtifact; - } - - private Either, TitanOperationStatus> getArtifactByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { - Either, TitanOperationStatus> artifactsEither = getArtifactsDataByLabel(parentId, instanceId, edgeLabelEnum); - if (artifactsEither.isRight()) { - log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, parentId, artifactsEither.right().value()); - return Either.right(artifactsEither.right().value()); - } - Map artifactDataMap = artifactsEither.left().value(); - return Either.left(convertArtifactMapToArtifactDefinitionMap(artifactDataMap)); - } - - private Either, TitanOperationStatus> getArtifactsDataByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { - return edgeLabelEnum.isInstanceArtifactsLabel() ? getInstanceArtifactsByLabel(parentId, instanceId, edgeLabelEnum) : getDataFromGraph(parentId, edgeLabelEnum); - } - - private Map convertArtifactMapToArtifactDefinitionMap(Map artifactDataMap) { - Map artMap = new HashMap<>(); - if (artifactDataMap != null && !artifactDataMap.isEmpty()) { - artMap = artifactDataMap.entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> convertArtifactDataToArtifactDefinition(null, e.getValue()))); - } - return artMap; - } - - private Either, TitanOperationStatus> getInstanceArtifactsByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { - Either, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum); - if (resultEither.isRight()) { - log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, parentId, resultEither.right().value()); - return Either.right(resultEither.right().value()); - } - Map mapArtifacts = resultEither.left().value(); - MapArtifactDataDefinition artifactPerInstance = mapArtifacts.get(instanceId); - return artifactPerInstance != null ? Either.left(artifactPerInstance.getMapToscaDataDefinition()) : Either.left(new HashMap<>()); - } - - private Triple getEdgeLabelEnumFromArtifactGroupType(ArtifactGroupTypeEnum groupType, NodeTypeEnum nodeType) { - EdgeLabelEnum edgeLabelEnum; - VertexTypeEnum vertexTypeEnum; - Boolean isDeepElement = false; - /* - * if (nodeType == NodeTypeEnum.ResourceInstance) { edgeLabelEnum = EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS; vertexTypeEnum = VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS; isDeepElement = true; } else { - */ - switch (groupType) { - case TOSCA: - edgeLabelEnum = EdgeLabelEnum.TOSCA_ARTIFACTS; - vertexTypeEnum = VertexTypeEnum.TOSCA_ARTIFACTS; - break; - case DEPLOYMENT: - if (nodeType == NodeTypeEnum.ResourceInstance) { - edgeLabelEnum = EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS; - vertexTypeEnum = VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS; - isDeepElement = true; - } else { - edgeLabelEnum = EdgeLabelEnum.DEPLOYMENT_ARTIFACTS; - vertexTypeEnum = VertexTypeEnum.DEPLOYMENT_ARTIFACTS; - } - break; - case SERVICE_API: - edgeLabelEnum = EdgeLabelEnum.SERVICE_API_ARTIFACTS; - vertexTypeEnum = VertexTypeEnum.SERVICE_API_ARTIFACTS; - break; - default: - if (nodeType == NodeTypeEnum.ResourceInstance) { - edgeLabelEnum = EdgeLabelEnum.INSTANCE_ARTIFACTS; - vertexTypeEnum = VertexTypeEnum.INSTANCE_ARTIFACTS; - isDeepElement = true; - } else { - edgeLabelEnum = EdgeLabelEnum.ARTIFACTS; - vertexTypeEnum = VertexTypeEnum.ARTIFACTS; - } - break; - } - // } - return new ImmutableTriple<>(edgeLabelEnum, isDeepElement, vertexTypeEnum); - - } - - public Either updateArtifactOnGraph(String componentId, ArtifactDefinition artifactInfo, NodeTypeEnum type, String artifactId, String instanceId, boolean isUpdate, boolean isDeletePlaceholder) { - Either res = null; - ArtifactDataDefinition artifactToUpdate = new ArtifactDataDefinition(artifactInfo); - ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); - - Triple triple = getEdgeLabelEnumFromArtifactGroupType(groupType, type); - EdgeLabelEnum edgeLabelEnum = triple.getLeft(); - VertexTypeEnum vertexTypeEnum = triple.getRight(); - - Either isNeedToCloneEither = isCloneNeeded(componentId, edgeLabelEnum); - if (isNeedToCloneEither.isRight()) { - log.debug("Failed check is clone needed {}", componentId); - return Either.right(isNeedToCloneEither.right().value()); - - } - boolean isNeedToClone = isNeedToCloneEither.left().value(); - - if (artifactId == null || isNeedToClone) { - String uniqueId; - if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { - uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, artifactToUpdate.getArtifactLabel()); - } else { - uniqueId = UniqueIdBuilder.buildInstanceArtifactUniqueId(componentId, instanceId, artifactToUpdate.getArtifactLabel()); - } - artifactToUpdate.setUniqueId(uniqueId); - if (!isDeletePlaceholder) - artifactToUpdate.setEsId(uniqueId); - } else - artifactToUpdate.setUniqueId(artifactId); - - Map artifacts = new HashMap<>(); - Map artifactInst = null; - if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { - - Either, TitanOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum); - - if (artifactsEither.isLeft() && artifactsEither.left().value() != null && !artifactsEither.left().value().isEmpty()) { - artifacts = artifactsEither.left().value(); - if (isNeedToClone && artifacts != null) { - artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE)); - } - } - } else { - - Either, TitanOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum); - if (artifactsEither.isLeft()) { - artifactInst = artifactsEither.left().value(); - if (isNeedToClone && artifactInst != null) { - artifactInst.values().forEach(ma -> ma.getMapToscaDataDefinition().values().forEach(a -> a.setDuplicated(Boolean.TRUE))); - } - MapArtifactDataDefinition artifatcsOnInstance = artifactInst.get(instanceId); - if (artifatcsOnInstance != null) { - artifacts = artifatcsOnInstance.getMapToscaDataDefinition(); - } - } - } - String oldChecksum = null; - String oldVersion = null; - if (artifacts != null && artifacts.containsKey(artifactInfo.getArtifactLabel())) { - ArtifactDataDefinition oldArtifactData = artifacts.get(artifactInfo.getArtifactLabel()); - oldChecksum = oldArtifactData.getArtifactChecksum(); - oldVersion = oldArtifactData.getArtifactVersion(); - //duplicated flag didn't receive from UI, take from DB - artifactToUpdate.setDuplicated(oldArtifactData.getDuplicated()); - - if (isNeedToClone) - artifactToUpdate.setDuplicated(Boolean.FALSE); - else { - if (artifactToUpdate.getDuplicated()) { - String uniqueId = ""; - if(type != NodeTypeEnum.ResourceInstance) - uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, artifactToUpdate.getArtifactLabel()); - else - uniqueId = UniqueIdBuilder.buildInstanceArtifactUniqueId(componentId, instanceId, artifactToUpdate.getArtifactLabel()); - - artifactToUpdate.setUniqueId(uniqueId); - if (!isDeletePlaceholder) - artifactToUpdate.setEsId(uniqueId); - artifactToUpdate.setDuplicated(Boolean.FALSE); - } - } - } - updateUUID(artifactToUpdate, oldChecksum, oldVersion, isUpdate, edgeLabelEnum); - - if (artifactInfo.getPayloadData() == null) { - if (!artifactToUpdate.getMandatory() || artifactToUpdate.getEsId() != null) { - artifactToUpdate.setEsId(artifactToUpdate.getUniqueId()); - } - } else { - if (artifactToUpdate.getEsId() == null) { - artifactToUpdate.setEsId(artifactToUpdate.getUniqueId()); - } - } - - StorageOperationStatus status = StorageOperationStatus.OK; - if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { - List toscaDataList = new ArrayList<>(); - toscaDataList.add(artifactToUpdate); - - if (isNeedToClone && artifacts != null) { - artifacts.values().stream().filter(a -> !a.getArtifactLabel().equals(artifactToUpdate.getArtifactLabel())).forEach(toscaDataList::add); - } - status = updateToscaDataOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataList, JsonPresentationFields.ARTIFACT_LABEL); - } else { - List toscaDataList = new ArrayList<>(); - toscaDataList.add(artifactToUpdate); - List pathKeys = new ArrayList<>(); - pathKeys.add(instanceId); - if (isNeedToClone) { - MapArtifactDataDefinition artifatcsOnInstance = artifactInst.get(instanceId); - if (artifatcsOnInstance != null) { - artifacts = artifatcsOnInstance.getMapToscaDataDefinition(); - artifacts.put(artifactToUpdate.getArtifactLabel(), artifactToUpdate); - } - - for (Entry e : artifactInst.entrySet()) { - List toscaDataListPerInst = e.getValue().getMapToscaDataDefinition().values().stream().collect(Collectors.toList()); - List pathKeysPerInst = new ArrayList<>(); - pathKeysPerInst.add(e.getKey()); - status = updateToscaDataDeepElementsOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.ARTIFACT_LABEL); - if (status != StorageOperationStatus.OK) { - log.debug("Failed to update atifacts group for instance {} in component {} edge type {} error {}", instanceId, componentId, edgeLabelEnum, status); - res = Either.right(status); - break; - } - } - } else { - status = updateToscaDataDeepElementsOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataList, pathKeys, JsonPresentationFields.ARTIFACT_LABEL); - } - } - if (status == StorageOperationStatus.OK) - res = Either.left(artifactToUpdate); - else - res = Either.right(status); - return res; - } - - public void generateUUID(ArtifactDataDefinition artifactData, String oldVesrion) { - - UUID uuid = UUID.randomUUID(); - artifactData.setArtifactUUID(uuid.toString()); - MDC.put("serviceInstanceID", uuid.toString()); - updateVersionAndDate(artifactData, oldVesrion); - } - - private void updateVersionAndDate(ArtifactDataDefinition artifactData, String oldVesrion) { - if (artifactData.getArtifactChecksum() != null) { - long time = System.currentTimeMillis(); - artifactData.setPayloadUpdateDate(time); - } - int newVersion = new Integer(oldVesrion).intValue(); - newVersion++; - artifactData.setArtifactVersion(String.valueOf(newVersion)); - } - - public Either removeArtifactOnGraph(ArtifactDefinition artifactFromGraph, String componentId, String instanceId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { - - Triple triple = getEdgeLabelEnumFromArtifactGroupType(artifactFromGraph.getArtifactGroupType(), type); - EdgeLabelEnum edgeLabelEnum = triple.getLeft(); - VertexTypeEnum vertexTypeEnum = triple.getRight(); - - if (deleteMandatoryArtifact || !(artifactFromGraph.getMandatory() || artifactFromGraph.getServiceApi())) { - StorageOperationStatus status; - if (triple.getMiddle()) { - List pathKeys = new ArrayList<>(); - pathKeys.add(instanceId); - status = deleteToscaDataDeepElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(), pathKeys, JsonPresentationFields.ARTIFACT_LABEL); - } else { - status = deleteToscaDataElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(), JsonPresentationFields.ARTIFACT_LABEL); - } - if (status != StorageOperationStatus.OK) - return Either.right(status); - } - return Either.left(artifactFromGraph); - - } - - public Either deleteArtifactWithCloningOnGraph(String componentId, ArtifactDefinition artifactToDelete, NodeTypeEnum type, String instanceId, boolean deleteMandatoryArtifact) { - - Either result = null; - Triple triple = getEdgeLabelEnumFromArtifactGroupType(artifactToDelete.getArtifactGroupType(), type); - EdgeLabelEnum edgeLabel = triple.getLeft(); - VertexTypeEnum vertexLabel = triple.getRight(); - - Boolean deleteElement = deleteMandatoryArtifact || !(artifactToDelete.getMandatory() || artifactToDelete.getServiceApi()); - Map artifacts = null; - GraphVertex parentVertex = null; - Either, TitanOperationStatus> getArtifactsRes = null; - - Either getToscaElementRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon getting tosca data from graph. Status is {}. ", componentId, getToscaElementRes.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value())); - } - if (result == null) { - parentVertex = getToscaElementRes.left().value(); - getArtifactsRes = this.getDataFromGraph(parentVertex, edgeLabel); - if (getArtifactsRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getArtifactsRes.right().value())); - } - } - if (result == null) { - artifacts = getArtifactsRes.left().value(); - if (triple.getMiddle()) { - artifacts.values().forEach(ma -> ((MapArtifactDataDefinition) ma).getMapToscaDataDefinition().values().forEach(a -> a.setDuplicated(Boolean.TRUE))); - MapArtifactDataDefinition artifatcsOnInstance = (MapArtifactDataDefinition) artifacts.get(instanceId); - if (artifatcsOnInstance != null && deleteElement) { - artifatcsOnInstance.getMapToscaDataDefinition().remove(artifactToDelete.getArtifactLabel()); - } - } else { - if (deleteElement) { - artifacts.remove(artifactToDelete.getArtifactLabel()); - } - artifacts.values().stream().forEach(a -> ((ArtifactDataDefinition) a).setDuplicated(Boolean.TRUE)); - } - artifactToDelete.setDuplicated(Boolean.TRUE); - } - if (artifacts != null) { - TitanOperationStatus status = titanDao.deleteEdgeByDirection(parentVertex, Direction.OUT, edgeLabel); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } else if (MapUtils.isNotEmpty(artifacts)) { - Either associateResult = associateElementToData(parentVertex, vertexLabel, edgeLabel, artifacts); - if (associateResult.isRight()) { - result = Either.right(associateResult.right().value()); - } - } - } - if (result == null) { - result = Either.left(artifactToDelete); - } - return result; - } - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java deleted file mode 100644 index d44865c399..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java +++ /dev/null @@ -1,1495 +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.jsontitan.operations; - -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.ObjectUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Property; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.*; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; -import org.openecomp.sdc.be.model.operations.StorageException; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.common.util.ValidationUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.openecomp.sdc.be.dao.impl.HealingPipelineDao; - -import java.util.*; -import java.util.EnumMap; -import java.util.stream.Collectors; - -/** - * public abstract class BaseOperation provides base operation functionality and common fields - * - */ -public abstract class BaseOperation { - - private static final String FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS = "Failed remove tosca data vertex of the tosca element {} by label {}. Status is {}. "; - private static final String FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS = "Failed to get child vertex of the tosca element {} by label {}. Status is {}. "; - private static final String FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS = "Failed to get tosca element {} upon adding the properties. Status is {}. "; - private static final Logger log = Logger.getLogger(BaseOperation.class.getName()); - public static final String VF_MODULE = "org.openecomp.groups.VfModule"; - - @Autowired - protected TitanDao titanDao; - - @Autowired - protected NodeTypeOperation nodeTypeOperation; - - @Autowired - protected TopologyTemplateOperation topologyTemplateOperation; - -// @Autowired - protected HealingPipelineDao healingPipelineDao; - - public void setTitanDao(TitanDao titanDao) { - this.titanDao = titanDao; - } - /** - * Returns reference to appropriate toscaTemplateOperation - * - * @param componentType - * @return - */ - public ToscaElementOperation getToscaElementOperation(ComponentTypeEnum componentType) { - ToscaElementOperation operation; - switch (componentType) { - case SERVICE: - case RESOURCE: - operation = topologyTemplateOperation; - break; - default: - operation = nodeTypeOperation; - break; - } - return operation; - } - - /** - * Returns reference to appropriate toscaTemplateOperation - * - * @param toscaElementType - * @return - */ - public ToscaElementOperation getToscaElementOperation(ToscaElementTypeEnum toscaElementType) { - ToscaElementOperation operation; - switch (toscaElementType) { - case TOPOLOGY_TEMPLATE: - operation = topologyTemplateOperation; - break; - case NODE_TYPE: - operation = nodeTypeOperation; - break; - default: - operation = null; - break; - } - return operation; - } - - /** - * Returns reference to appropriate toscaTemplateOperation - * - * @param toscaElementType - * @return - */ - public ToscaElementOperation getToscaElementOperation(VertexTypeEnum toscaElementType) { - ToscaElementOperation operation; - switch (toscaElementType) { - case TOPOLOGY_TEMPLATE: - operation = topologyTemplateOperation; - break; - case NODE_TYPE: - operation = nodeTypeOperation; - break; - default: - operation = null; - break; - } - return operation; - } - /** - * Converts received vertex to User object - * - * @param ownerV - * @return - */ - public User convertToUser(Vertex ownerV) { - User owner = new User(); - owner.setUserId((String) ownerV.property(GraphPropertyEnum.USERID.getProperty()).value()); - VertexProperty property = ownerV.property(GraphPropertyEnum.ROLE.getProperty()); - if(property != null && property.isPresent() ){ - owner.setRole((String) property.value()); - } - - property = ownerV.property(GraphPropertyEnum.FIRST_NAME.getProperty()); - if(property != null && property.isPresent() ){ - owner.setFirstName((String) ownerV.property(GraphPropertyEnum.FIRST_NAME.getProperty()).value()); - } - - property = ownerV.property(GraphPropertyEnum.LAST_NAME.getProperty()); - if( property != null && property.isPresent() ){ - owner.setLastName((String) ownerV.property(GraphPropertyEnum.LAST_NAME.getProperty()).value()); - } - - property = ownerV.property(GraphPropertyEnum.EMAIL.getProperty()); - if( property != null && property.isPresent() ){ - owner.setEmail((String) ownerV.property(GraphPropertyEnum.EMAIL.getProperty()).value()); - } - - property = ownerV.property(GraphPropertyEnum.LAST_LOGIN_TIME.getProperty()); - if( property != null && property.isPresent() ){ - owner.setLastLoginTime((Long) ownerV.property(GraphPropertyEnum.LAST_LOGIN_TIME.getProperty()).value()); - } - return owner; - } - - protected Either, TitanOperationStatus> getDataFromGraph(GraphVertex componentV, EdgeLabelEnum edgelabel) { - Either>, TitanOperationStatus> dataVertex = getDataAndVertexFromGraph(componentV, edgelabel); - if (dataVertex.isRight()) { - return Either.right(dataVertex.right().value()); - } - Map properties = dataVertex.left().value().getRight(); - return Either.left(properties); - } - - @SuppressWarnings("unchecked") - protected Either>, TitanOperationStatus> getDataAndVertexFromGraph(GraphVertex componentV, EdgeLabelEnum edgelabel) { - Either dataVertex = getDataVertex(componentV, edgelabel); - if (dataVertex.isRight()) { - return Either.right(dataVertex.right().value()); - } - GraphVertex propV = dataVertex.left().value(); - Map properties = (Map) propV.getJson(); - Pair> pair = new ImmutablePair<>(propV, properties); - return Either.left(pair); - } - - protected Either getDataVertex(GraphVertex componentV, EdgeLabelEnum edgelabel) { - Either childVertex = titanDao.getChildVertex(componentV, edgelabel, JsonParseFlagEnum.ParseJson); - if (childVertex.isRight()) { - if (childVertex.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("failed to fetch {} for tosca element with id {}, error {}", edgelabel, componentV.getUniqueId(), childVertex.right().value()); - } - return Either.right(childVertex.right().value()); - } - GraphVertex propV = childVertex.left().value(); - return Either.left(propV); - } - - /** - * Returns tosca data belonging to tosca element specified by uid according received label - * - * @param toscaElementUid - * @param edgelabel - * @return - */ - public Either, TitanOperationStatus> getDataFromGraph(String toscaElementUid, EdgeLabelEnum edgelabel) { - - Either, TitanOperationStatus> result = null; - Either getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon getting tosca data from graph. Status is {}. ", toscaElementUid, status); - result = Either.right(status); - } - if (result == null) { - result = getDataFromGraph(getToscaElementRes.left().value(), edgelabel); - } - return result; - } - - public Either findUserVertex(String userId) { - return titanDao.getVertexByPropertyAndLabel(GraphPropertyEnum.USERID, userId, VertexTypeEnum.USER, JsonParseFlagEnum.NoParse); - } - - /** - * - * @param elemementId - * @param label - * @return - */ - public Either isCloneNeeded(String elemementId, EdgeLabelEnum label) { - Either vertexById = titanDao.getVertexById(elemementId); - if (vertexById.isRight()) { - log.debug("Failed to fetch element by id {} error {}", elemementId, vertexById.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexById.right().value())); - } - GraphVertex toscaElementVertex = vertexById.left().value(); - Either childVertex = titanDao.getChildVertex(toscaElementVertex, label, JsonParseFlagEnum.NoParse); - if (childVertex.isRight()) { - if (childVertex.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("failed to fetch {} for tosca element with id {}, error {}", label, toscaElementVertex.getUniqueId(), childVertex.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value())); - } - return Either.left(Boolean.FALSE); - } - GraphVertex dataVertex = childVertex.left().value(); - Iterator edges = dataVertex.getVertex().edges(Direction.IN, label.name()); - int edgeCount = 0; - while (edges.hasNext()) { - edges.next(); - ++edgeCount; - } - if (edgeCount > 1) { - return Either.left(Boolean.TRUE); - } else { - return Either.left(Boolean.FALSE); - } - } - - protected Either updateOrCopyOnUpdate(GraphVertex dataVertex, GraphVertex toscaElementVertex, EdgeLabelEnum label) { -// healingPipelineDao.setHealingVersion(dataVertex); - Iterator edges = dataVertex.getVertex().edges(Direction.IN, label.name()); - int edgeCount = 0; - Edge edgeToRemove = null; - while (edges.hasNext()) { - Edge edge = edges.next(); - ++edgeCount; - Vertex outVertex = edge.outVertex(); - String outId = (String) titanDao.getProperty((TitanVertex) outVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()); - if (toscaElementVertex.getUniqueId().equals(outId)) { - edgeToRemove = edge; - } - } - if (edgeToRemove == null) { - log.debug("No edges {} from vertex {} to vertex {}", label, toscaElementVertex.getUniqueId(), dataVertex.getUniqueId()); - return Either.right(TitanOperationStatus.GENERAL_ERROR); - } - switch (edgeCount) { - case 0: - // error - log.debug("No edges {} to vertex {}", label, dataVertex.getUniqueId()); - return Either.right(TitanOperationStatus.GENERAL_ERROR); - case 1: - // update - log.trace("Only one edge {} to vertex {}. Update vertex", label, dataVertex.getUniqueId()); - return titanDao.updateVertex(dataVertex); - default: - // copy on update - log.trace("More than one edge {} to vertex {}. Need to clone vertex", label, dataVertex.getUniqueId()); - return cloneDataVertex(dataVertex, toscaElementVertex, label, edgeToRemove); - } - } - - private Either cloneDataVertex(GraphVertex dataVertex, GraphVertex toscaElementVertex, EdgeLabelEnum label, Edge edgeToRemove) { - GraphVertex newDataVertex = new GraphVertex(dataVertex.getLabel()); - String id = IdBuilderUtils.generateChildId(toscaElementVertex.getUniqueId(), dataVertex.getLabel()); - newDataVertex.cloneData(dataVertex); - newDataVertex.setUniqueId(id); - - Either createVertex = titanDao.createVertex(newDataVertex); - if (createVertex.isRight()) { - log.debug("Failed to clone data vertex for {} error {}", dataVertex.getUniqueId(), createVertex.right().value()); - return createVertex; - } - newDataVertex = createVertex.left().value(); - TitanOperationStatus createEdge = titanDao.createEdge(toscaElementVertex, newDataVertex, label, titanDao.getEdgeProperties(edgeToRemove)); - if (createEdge != TitanOperationStatus.OK) { - log.debug("Failed to associate vertex {} to vertex {}, error {}", toscaElementVertex.getUniqueId(), newDataVertex.getUniqueId(), createEdge); - return Either.right(createEdge); - } - edgeToRemove.remove(); - return Either.left(newDataVertex); - } - - public Either associateElementToData(GraphVertex element, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, Map data) { - GraphVertex dataV = new GraphVertex(vertexLabel); - String id = IdBuilderUtils.generateChildId(element.getUniqueId(), vertexLabel); - dataV.setUniqueId(id); - dataV.setJson(data); - Either createVertex = titanDao.createVertex(dataV); - if (createVertex.isRight()) { - log.trace("Failed to create {} vertex for type node {}", vertexLabel, element.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createVertex.right().value())); - } - dataV = createVertex.left().value(); - TitanOperationStatus createEdgeStatus = titanDao.createEdge(element.getVertex(), dataV.getVertex(), edgeLabel, new HashMap<>()); - if (createEdgeStatus != TitanOperationStatus.OK) { - log.trace("Failed to create {} vertex for type node {}", vertexLabel, element.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeStatus)); - } - return Either.left(dataV); - } - - /** - * Adds tosca data element to tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaData - * @param mapKeyField - * @return - */ - public StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { - - List toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return addToscaDataToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField); - } - - /** - * Adds tosca data deep element to tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaData - * @param pathKeys - * @param mapKeyField - * @return - */ - public StorageOperationStatus addToscaDataDeepElementToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List pathKeys, - JsonPresentationFields mapKeyField) { - - List toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return addToscaDataDeepElementsToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); - } - - /** - * Converts recieved map of tosca data deep elements to list and adds it to tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaDataMap - * @param pathKeys - * @param mapKeyField - * @return - */ - public StorageOperationStatus addToscaDataDeepElementsToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map toscaDataMap, List pathKeys, - JsonPresentationFields mapKeyField) { - - if (toscaDataMap != null) { - return addToscaDataDeepElementsToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataMap.values().stream().collect(Collectors.toList()), pathKeys, mapKeyField); - } - return StorageOperationStatus.OK; - } - - /** - * Adds list of tosca data deep elements to tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaDataList - * @param pathKeys - * @param mapKeyField - * @return - */ - public StorageOperationStatus addToscaDataDeepElementsToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, List pathKeys, - JsonPresentationFields mapKeyField) { - - return updateOrAddToscaDataDeepElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField, false); - } - - /** - * Updates list of tosca data elements of tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaData - * @param mapKeyField - * @return - */ - public StorageOperationStatus updateToscaDataOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { - List toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return updateToscaDataOfToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField); - } - - /** - * Updates tosca data deep element of tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaData - * @param pathKeys - * @param mapKeyField - * @return - */ - public StorageOperationStatus updateToscaDataDeepElementOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List pathKeys, - JsonPresentationFields mapKeyField) { - List toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return updateToscaDataDeepElementsOfToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); - } - - /** - * Updates tosca data deep elements of tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaDataList - * @param pathKeys - * @param mapKeyField - * @return - */ - public StorageOperationStatus updateToscaDataDeepElementsOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, List pathKeys, - JsonPresentationFields mapKeyField) { - - return updateOrAddToscaDataDeepElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField, true); - } - - /** - * Adds tosca data element to tosca element with specified uid according received labels - * - * @param toscaElementUid - * @param toscaData - * @param edgeLabel - * @param vertexLabel - * @param mapKeyField - * @return - */ - public StorageOperationStatus addToscaDataToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { - - List toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return addToscaDataToToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, mapKeyField); - } - - /** - * Adds tosca data deep element to tosca element with specified uid according received labels - * - * @param toscaElementUid - * @param edgeLabel - * @param vertexLabel - * @param toscaData - * @param pathKeys - * @param mapKeyField - * @return - */ - public StorageOperationStatus addToscaDataDeepElementToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List pathKeys, - JsonPresentationFields mapKeyField) { - - List toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return addToscaDataDeepElementsToToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); - } - - public StorageOperationStatus updateToscaDataDeepElementOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List pathKeys, - JsonPresentationFields mapKeyField) { - - List toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return updateToscaDataDeepElementsOfToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); - } - - public StorageOperationStatus updateToscaDataDeepElementsOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, List pathKeys, - JsonPresentationFields mapKeyField) { - - StorageOperationStatus statusRes = null; - Either getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { - statusRes = updateToscaDataDeepElementsOfToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); - } - if (statusRes == null) { - statusRes = StorageOperationStatus.OK; - } - return statusRes; - } - - StorageOperationStatus overrideToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, Map toscaData) { - return titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse) - .left() - .bind(graphVertex -> overrideToscaElementData(graphVertex, toscaData, edgeLabel)) - .either(graphVertex -> StorageOperationStatus.OK, - DaoStatusConverter::convertTitanStatusToStorageStatus); - } - - private Either overrideToscaElementData(GraphVertex toscaElement, Map toscaData, EdgeLabelEnum edgeLabelEnum) { - return titanDao.getChildVertex(toscaElement, edgeLabelEnum, JsonParseFlagEnum.ParseJson) - .left() - .bind(dataVertex -> overrideToscaElementData(dataVertex, toscaElement, toscaData, edgeLabelEnum)) - .right() - .map(err -> logAndReturn(err, "failed to override tosca data for element {} of type {}. status: {}", toscaElement.getUniqueId(), edgeLabelEnum, err)); - } - - private Either overrideToscaElementData(GraphVertex dataElement, GraphVertex toscaElement, Map toscaData, EdgeLabelEnum edgeLabelEnum) { - dataElement.setJson(toscaData); - return updateOrCopyOnUpdate(dataElement, toscaElement, edgeLabelEnum); - } - - /** - * Adds list of tosca data deep elements to tosca element with specified uid according received labels - * - * @param toscaElementUid - * @param edgeLabel - * @param vertexLabel - * @param toscaDataList - * @param pathKeys - * @param mapKeyField - * @return - */ - public StorageOperationStatus addToscaDataDeepElementsToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, List pathKeys, - JsonPresentationFields mapKeyField) { - - StorageOperationStatus statusRes = null; - Either getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { - statusRes = addToscaDataDeepElementsToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); - } - if (statusRes == null) { - statusRes = StorageOperationStatus.OK; - } - return statusRes; - } - - public StorageOperationStatus deleteToscaDataDeepElementsBlockOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String key) { - - StorageOperationStatus statusRes = null; - Either getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == null) { - statusRes = deleteToscaDataDeepElementsBlockToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, key); - } - if (statusRes == null) { - statusRes = StorageOperationStatus.OK; - } - return statusRes; - } - - public StorageOperationStatus deleteToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String key) { - - StorageOperationStatus result = null; - GraphVertex toscaDataVertex = null; - Either toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight()) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null) { - toscaDataVertex = toscaDataVertexRes.left().value(); - result = deleteDeepElementsBlock(toscaDataVertex, key); - } - if (result == null) { - Either updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); - if (updateOrCopyRes.isRight()) { - TitanOperationStatus status = updateOrCopyRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete tosca data block {} from the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - @SuppressWarnings("rawtypes") - public StorageOperationStatus addToscaDataDeepElementsBlockToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, MapDataDefinition toscaDataMap, String key) { - - StorageOperationStatus statusRes = null; - Either getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == null && toscaDataMap != null) { - statusRes = addToscaDataDeepElementsBlockToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataMap, key); - } - if (statusRes == null) { - statusRes = StorageOperationStatus.OK; - } - return statusRes; - } - - @SuppressWarnings("rawtypes") - public StorageOperationStatus addToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, MapDataDefinition toscaDataMap, String key) { - - StorageOperationStatus result = null; - GraphVertex toscaDataVertex = null; - Either toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null && toscaDataVertexRes.isLeft()) { - toscaDataVertex = toscaDataVertexRes.left().value(); - result = addDeepElementsBlock(toscaDataVertex, toscaDataMap, key); - - } - if (result == null) { - if (toscaDataVertex != null) { - Either updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); - if (updateOrCopyRes.isRight()) { - TitanOperationStatus status = updateOrCopyRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data {} to the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } else { - Map data = new HashMap<>(); - data.put(key, toscaDataMap); - Either createRes = associateElementToData(toscaElement, vertexLabel, edgeLabel, data); - if (createRes.isRight()) { - StorageOperationStatus status = createRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to assosiate tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); - result = status; - } - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - /** - * - * @param toscaElementId the id of the tosca element data container - * @param edgeLabel the edge label of the data type to update - * @param toscaDataMap the data to update - * @param key the key in the json object where the map object block resides - * @return the status of the update operation - */ - public StorageOperationStatus updateToscaDataDeepElementsBlockToToscaElement(String toscaElementId, EdgeLabelEnum edgeLabel, MapDataDefinition toscaDataMap, String key) { - return titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse) - .either(toscaElement -> updateToscaDataDeepElementsBlockToToscaElement(toscaElement, edgeLabel, toscaDataMap, key), - DaoStatusConverter::convertTitanStatusToStorageStatus); - } - - private StorageOperationStatus updateToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, MapDataDefinition toscaDataMap, String key) { - return titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson) - .left() - .bind(dataVertex -> updateToscaDataDeepElementsBlockToToscaElement(toscaElement, dataVertex, edgeLabel, toscaDataMap, key)) - .either(updatedVertex -> StorageOperationStatus.OK, - DaoStatusConverter::convertTitanStatusToStorageStatus); - } - - private Either updateToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, GraphVertex dataElement, EdgeLabelEnum edgeLabel, MapDataDefinition toscaDataMap, String key) { - Map mapToscaDataDefinition = toscaDataMap.getMapToscaDataDefinition(); - updateDeepElements(dataElement, mapToscaDataDefinition, Collections.singletonList(key)); - return updateOrCopyOnUpdate(dataElement, toscaElement, edgeLabel) - .right() - .map(err -> logAndReturn(err, "failed while trying to update data vertex from tosca element {}, of type {} . status {}", toscaElement.getUniqueId(), edgeLabel, err)); - } - - /** - * Updates tosca data element of tosca element by specified uid according received labels - * - * @param toscaElementUid - * @param edgeLabel - * @param vertexLabel - * @param toscaData - * @param mapKeyField - * @return - */ - public StorageOperationStatus updateToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { - - List toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return updateToscaDataOfToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, mapKeyField); - } - - /** - * Updates list of tosca data elements belonging to tosca element with specified uid according received labels - * - * @param toscaElementUid - * @param edgeLabel - * @param vertexLabel - * @param toscaDataList - * @param mapKeyField - * @return - */ - public StorageOperationStatus updateToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, JsonPresentationFields mapKeyField) { - - StorageOperationStatus statusRes = null; - Either getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { - statusRes = updateToscaDataOfToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, mapKeyField); - } - if (statusRes == null) { - statusRes = StorageOperationStatus.OK; - } - return statusRes; - } - - /** - * Adds list of tosca data elements to tosca element with specified uid according received labels - * - * @param toscaElementUid - * @param edgeLabel - * @param vertexLabel - * @param toscaDataList - * @param mapKeyField - * @return - */ - public StorageOperationStatus addToscaDataToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, JsonPresentationFields mapKeyField) { - - StorageOperationStatus statusRes = null; - Either getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { - statusRes = addToscaDataToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, mapKeyField); - } - if (statusRes == null) { - statusRes = StorageOperationStatus.OK; - } - return statusRes; - } - - /** - * Converts recieved map of tosca data elements to list and adds it to tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaDataMap - * @param mapKeyField - * @return - */ - public StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map toscaDataMap, JsonPresentationFields mapKeyField) { - - return addToscaDataToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataMap.values().stream().collect(Collectors.toList()), mapKeyField); - } - - /** - * Adds list of tosca data elements to tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaDataList - * @param mapKeyField - * @return - */ - public StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, JsonPresentationFields mapKeyField) { - - return updateOrAddToscaData(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField, false); - } - - /** - * Updates list of tosca data elements belonging to tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaDataList - * @param mapKeyField - * @return - */ - public StorageOperationStatus updateToscaDataOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, JsonPresentationFields mapKeyField) { - - return updateOrAddToscaData(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField, true); - } - - public boolean hasEdgeOfType(GraphVertex toscaElement, EdgeLabelEnum edgeLabel) { - Either vertex = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - return vertex.isLeft(); - } - - @SuppressWarnings("unchecked") - private StorageOperationStatus updateOrAddToscaData(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, JsonPresentationFields mapKeyField, boolean isUpdate) { - StorageOperationStatus result = null; - GraphVertex toscaDataVertex = null; - Map existingToscaDataMap = null; - Either, StorageOperationStatus> validateRes = null; - Map mergedToscaDataMap; - Either toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null) { - if (toscaDataVertexRes.isLeft()) { - toscaDataVertex = toscaDataVertexRes.left().value(); - existingToscaDataMap = (Map) toscaDataVertex.getJson(); - } - - validateRes = validateMergeToscaData(toscaElement, toscaDataList, mapKeyField, existingToscaDataMap, isUpdate); - if (validateRes.isRight()) { - result = validateRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed validate tosca data upon adding to tosca element {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result); - } - } - if (result == null) { - mergedToscaDataMap = validateRes.left().value(); - result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, mergedToscaDataMap); - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - - } - - @SuppressWarnings("unchecked") - public StorageOperationStatus updateFullToscaData(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map toscaData) { - StorageOperationStatus result = null; - GraphVertex toscaDataVertex = null; - Map existingToscaDataMap = null; - - Either toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null) { - if (toscaDataVertexRes.isLeft()) { - toscaDataVertex = toscaDataVertexRes.left().value(); - existingToscaDataMap = (Map) toscaDataVertex.getJson(); - } - - - } - if (result == null) { - - result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, toscaData); - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private StorageOperationStatus updateOrAddToscaDataDeepElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List toscaDataList, List pathKeys, - JsonPresentationFields mapKeyField, boolean isUpdate) { - - StorageOperationStatus result = null; - GraphVertex toscaDataVertex = null; - Map existingDeepElementsMap = null; - Either, StorageOperationStatus> validateRes = null; - Either toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null) { - if (toscaDataVertexRes.isLeft()) { - toscaDataVertex = toscaDataVertexRes.left().value(); - existingDeepElementsMap = getDeepElements(toscaDataVertex, pathKeys); - } - validateRes = validateMergeToscaData(toscaElement, toscaDataList, mapKeyField, existingDeepElementsMap, isUpdate); - if (validateRes.isRight()) { - result = validateRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed validate tosca data upon adding to tosca element {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result); - } - } - if (result == null) { - updateDeepElements(toscaDataVertex, validateRes.left().value(), pathKeys); - Map toscaDataToHandle; - if(toscaDataVertex == null){ - toscaDataToHandle = new HashMap<>(); - Map currMap = toscaDataToHandle; - for (int i = 1; i < pathKeys.size()-1; ++i) { - currMap.put(pathKeys.get(i), (K) new MapDataDefinition()); - currMap = (Map) ((MapDataDefinition) currMap).getMapToscaDataDefinition().get(pathKeys.get(i)); - } - toscaDataToHandle.put(pathKeys.get(pathKeys.size()-1), (K) new MapDataDefinition(validateRes.left().value())); - - } else { - toscaDataToHandle = (Map) toscaDataVertex.getJson(); - } - result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, toscaDataToHandle); - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private void updateDeepElements(GraphVertex toscaDataVertex, Map mergedDeepElementMap, List pathKeys) { - - if (toscaDataVertex != null && MapUtils.isNotEmpty(mergedDeepElementMap)) { - Map currMap = (Map) toscaDataVertex.getJson(); - if(!currMap.containsKey(pathKeys.get(0))){ - currMap.put(pathKeys.get(0), new MapDataDefinition<>()); - } - MapDataDefinition currDeepElement = currMap.get(pathKeys.get(0)); - - for (int i = 1; i < pathKeys.size(); ++i) { - if(currDeepElement.findByKey(pathKeys.get(i)) == null){ - currDeepElement.put(pathKeys.get(i), new MapDataDefinition<>()); - } - currDeepElement = (MapDataDefinition) currDeepElement.findByKey(pathKeys.get(i)); - } - if(currDeepElement != null){ - for (Map.Entry elementEntry : mergedDeepElementMap.entrySet()) { - currDeepElement.put(elementEntry.getKey(), elementEntry.getValue()); - } - } - } - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private Map getDeepElements(GraphVertex toscaDataVertex, List pathKeys) { - Map result = null; - Map currMap = (Map) toscaDataVertex.getJson(); - MapDataDefinition currDeepElement = (MapDataDefinition) currMap.get(pathKeys.get(0)); - for (int i = 1; i < pathKeys.size(); ++i) { - currDeepElement = (MapDataDefinition) currDeepElement.findByKey(pathKeys.get(i)); - } - if(currDeepElement != null){ - result = (Map) currDeepElement.getMapToscaDataDefinition(); - } - return result; - } - - @SuppressWarnings("unchecked") - private StorageOperationStatus addDeepElementsBlock(GraphVertex toscaDataVertex, T toscaDataBlock, String key) { - - StorageOperationStatus result = null; - Map currMap = (Map) toscaDataVertex.getJson(); - if (currMap.containsKey(key)) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add block of deep tosca data elements by label {}." + " The block element with the same key {} already exists. ", toscaDataVertex.getLabel(), key); - result = StorageOperationStatus.ENTITY_ALREADY_EXISTS; - } - if (result == null) { - currMap.put(key, toscaDataBlock); - } - return result; - } - - @SuppressWarnings("unchecked") - private StorageOperationStatus deleteDeepElementsBlock(GraphVertex toscaDataVertex, String key) { - - StorageOperationStatus result = null; - Map currMap = (Map) toscaDataVertex.getJson(); - if (!currMap.containsKey(key)) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete block of deep tosca data elements by label {}." + " The block element with the same key {} doesn't exist. ", toscaDataVertex.getLabel(), key); - result = StorageOperationStatus.NOT_FOUND; - } - if (result == null) { - currMap.remove(key); - } - return null; - } - - /** - * Removes tosca data vertex belonging to tosca element specified by uid according label - * - * @param toscaElementUid - * @param edgeLabel - * @param vertexLabel - * @return - */ - public StorageOperationStatus removeToscaData(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) { - - StorageOperationStatus statusRes = StorageOperationStatus.OK; - Either getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == StorageOperationStatus.OK) { - statusRes = removeToscaDataVertex(getToscaElementRes.left().value(), edgeLabel, vertexLabel); - } - return statusRes; - } - - /** - * Removes tosca data vertex belonging to tosca element according label - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @return - */ - public StorageOperationStatus removeToscaDataVertex(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) { - StorageOperationStatus result = null; - GraphVertex toscaDataVertex = null; - Iterator edges = null; - int edgeCounter = 0; - Edge edge = null; - Edge edgeToDelete = null; - Either toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight()) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null) { - toscaDataVertex = toscaDataVertexRes.left().value(); - edges = toscaDataVertex.getVertex().edges(Direction.IN); - if (edges == null || !edges.hasNext()) { - result = StorageOperationStatus.NOT_FOUND; - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, result); - } - } - if (result == null) { - if (edges!=null) { - while (edges.hasNext()) { - ++edgeCounter; - edge = edges.next(); - if (edge.outVertex().id().equals(toscaElement.getVertex().id())) { - edgeToDelete = edge; - break; - } - } - } - if (edgeToDelete == null) { - result = StorageOperationStatus.NOT_FOUND; - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, result); - } - } - if (result == null) { - if (edgeCounter > 1 && edgeToDelete!=null) { - edgeToDelete.remove(); - } else { - toscaDataVertex.getVertex().remove(); - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - /** - * Deletes tosca data elements belonging to tosca element specified by uid according label - * - * @param toscaElementUid - * @param edgeLabel - * @param uniqueKeys - * @return - */ - public StorageOperationStatus deleteToscaDataElements(String toscaElementUid, EdgeLabelEnum edgeLabel, List uniqueKeys) { - - StorageOperationStatus statusRes = StorageOperationStatus.OK; - Either getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == StorageOperationStatus.OK) { - statusRes = deleteToscaDataElements(getToscaElementRes.left().value(), edgeLabel, uniqueKeys); - } - return statusRes; - } - - /** - * Deletes tosca data element belonging to tosca element specified by uid according label - * - * @param toscaElementUid - * @param edgeLabel - * @param vertexLabel - * @param uniqueKey - * @param mapKeyField - * @return - */ - public StorageOperationStatus deleteToscaDataElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, JsonPresentationFields mapKeyField) { - - StorageOperationStatus statusRes = StorageOperationStatus.OK; - Either getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == StorageOperationStatus.OK) { - statusRes = deleteToscaDataElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKey, mapKeyField); - } - return statusRes; - - } - - /** - * Deletes tosca data deep element belonging to tosca element specified by uid according label - * - * @param toscaElementUid - * @param edgeLabel - * @param vertexLabel - * @param uniqueKey - * @param pathKeys - * @param mapKeyField - * @return - */ - public StorageOperationStatus deleteToscaDataDeepElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, List pathKeys, JsonPresentationFields mapKeyField) { - - StorageOperationStatus statusRes = StorageOperationStatus.OK; - Either getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == StorageOperationStatus.OK) { - statusRes = deleteToscaDataDeepElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKey, pathKeys, mapKeyField); - } - return statusRes; - - } - - /** - * Deletes tosca data deep element belonging to tosca element according label - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param uniqueKey - * @param pathKeys - * @param mapKeyField - * @return - */ - public StorageOperationStatus deleteToscaDataDeepElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, List pathKeys, JsonPresentationFields mapKeyField) { - - List uniqueKeys = new ArrayList<>(); - uniqueKeys.add(uniqueKey); - return deleteToscaDataDeepElements(toscaElement, edgeLabel, vertexLabel, uniqueKeys, pathKeys, mapKeyField); - } - - public StorageOperationStatus deleteToscaDataDeepElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List uniqueKeys, List pathKeys, JsonPresentationFields mapKeyField) { - - StorageOperationStatus result = null; - GraphVertex toscaDataVertex; - Map existingToscaDataMap = null; - Either toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight()) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null) { - toscaDataVertex = toscaDataVertexRes.left().value(); - existingToscaDataMap = getDeepElements(toscaDataVertexRes.left().value(), pathKeys); - result = deleteElementsFromDataVertex(toscaElement, edgeLabel, uniqueKeys, toscaDataVertex, existingToscaDataMap); - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private StorageOperationStatus deleteElementsFromDataVertex(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, List uniqueKeys, GraphVertex toscaDataVertex, Map existingToscaDataMap) { - StorageOperationStatus result; - for (String uniqueKey : uniqueKeys) { - result = removeKeyFromDataVertex(uniqueKey, existingToscaDataMap); - if (result != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete tosca data element of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result); - break; - } - } - result = updateToscaDataElement(toscaElement, edgeLabel, toscaDataVertex); - return result; - } - - /** - * Deletes tosca data element belonging to tosca element according label - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param uniqueKey - * @param mapKeyField - * @return - */ - public StorageOperationStatus deleteToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, JsonPresentationFields mapKeyField) { - - List uniqueKeys = new ArrayList<>(); - uniqueKeys.add(uniqueKey); - return deleteToscaDataElements(toscaElement, edgeLabel, uniqueKeys); - } - - @SuppressWarnings("unchecked") -/** - * Deletes tosca data elements belonging to tosca element according label - * @param toscaElement - * @param edgeLabel - * @param uniqueKeys - * @return - */ - public StorageOperationStatus deleteToscaDataElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, List uniqueKeys) { - StorageOperationStatus result = null; - GraphVertex toscaDataVertex; - Map existingToscaDataMap; - Either toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight()) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null) { - toscaDataVertex = toscaDataVertexRes.left().value(); - existingToscaDataMap = (Map) toscaDataVertex.getJson(); - result = deleteElementsFromDataVertex(toscaElement, edgeLabel, uniqueKeys, toscaDataVertex, existingToscaDataMap); - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - /** - * Adds the map data entry to the graph vertex of the specified type, related with the specified edge to the component specified by ID - * @param componentId The uniqueId of the component - * @param vertexTypeEnum The type of the vertex - * @param edgeLabelEnum The type of the edge - * @param mapDataEntry The map data entry - * @param - * @return The status of the operation result - */ - public StorageOperationStatus addElementToComponent(String componentId, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map.Entry mapDataEntry){ - if(MapUtils.isNotEmpty(mapDataEntry.getValue().getMapToscaDataDefinition())) - return addToscaDataDeepElementsBlockToToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, mapDataEntry.getValue(), mapDataEntry.getKey()); - return StorageOperationStatus.OK; - } - - private StorageOperationStatus updateToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex) { - StorageOperationStatus result = StorageOperationStatus.OK; - Either updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); - if (updateOrCopyRes.isRight()) { - result = DaoStatusConverter.convertTitanStatusToStorageStatus(updateOrCopyRes.right().value()); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), result); - } - return result; - } - - private StorageOperationStatus removeKeyFromDataVertex(String uniqueKey, Map existingToscaDataMap) { - if (!existingToscaDataMap.containsKey(uniqueKey)) { - return StorageOperationStatus.NOT_FOUND; - } - existingToscaDataMap.remove(uniqueKey); - return StorageOperationStatus.OK; - } - - protected StorageOperationStatus handleToscaData(GraphVertex toscaElement, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex, Map mergedToscaDataMap) { - - StorageOperationStatus result = StorageOperationStatus.OK; - if (toscaDataVertex == null) { - - Either createRes = associateElementToData(toscaElement, vertexLabel, edgeLabel, mergedToscaDataMap); - if (createRes.isRight()) { - StorageOperationStatus status = createRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to assosiate tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); - result = status; - } - } else { - toscaDataVertex.setJson(mergedToscaDataMap); - Either updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); - if (updateOrCopyRes.isRight()) { - TitanOperationStatus status = updateOrCopyRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data {} to the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } - return result; - } - - private Either, StorageOperationStatus> validateMergeToscaData(GraphVertex toscaElement, List toscaDataList, JsonPresentationFields mapKeyField, Map existingToscaDataMap, - boolean isUpdate) { - - Map mergedToscaDataMap = new HashMap<>(); - StorageOperationStatus status; - Either, StorageOperationStatus> result = Either.left(mergedToscaDataMap); - if (MapUtils.isNotEmpty(existingToscaDataMap)) { - mergedToscaDataMap.putAll(existingToscaDataMap); - } - for (T toscaDataElement : toscaDataList) { - status = handleToscaDataElement(toscaElement, mapKeyField, mergedToscaDataMap, toscaDataElement, isUpdate); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - break; - } - } - return result; - } - - private StorageOperationStatus handleToscaDataElement(GraphVertex toscaElement, JsonPresentationFields mapKeyField, Map mergedToscaDataMap, T toscaDataElement, boolean isUpdate) { - - StorageOperationStatus status = StorageOperationStatus.OK; - String currKey = (String) toscaDataElement.getToscaPresentationValue(mapKeyField); - - if(StringUtils.isEmpty(currKey) && toscaDataElement instanceof ListDataDefinition) { - ToscaDataDefinition toscaDataDefinition = ((ListDataDefinition) toscaDataElement) - .getListToscaDataDefinition().get(0); - if(toscaDataDefinition != null) { - currKey = (String) toscaDataDefinition.getToscaPresentationValue(mapKeyField); - } - } - - if (StringUtils.isEmpty(currKey)) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data to tosca element {}. The key is empty. "); - status = StorageOperationStatus.BAD_REQUEST; - } else if (!isUpdate && mergedToscaDataMap.containsKey(currKey)) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data to tosca element {}. The element with the same key {} already exists. ", toscaElement.getUniqueId(), currKey); - status = StorageOperationStatus.BAD_REQUEST; - } - mergedToscaDataMap.put(currKey, toscaDataElement); - return status; - } - -// public StorageOperationStatus updateDataOnGraph(GraphVertex dataVertex) { -// Either updateVertex = titanDao.updateVertex(dataVertex); -// if (updateVertex.isRight()) { -// return DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertex.right().value()); -// } -// return StorageOperationStatus.OK; -// } - - protected GroupInstanceDataDefinition buildGroupInstanceDataDefinition(GroupDataDefinition group, ComponentInstanceDataDefinition componentInstance, Map instDeplArtifMap) { - - String componentInstanceName = componentInstance.getName(); - Long creationDate = System.currentTimeMillis(); - GroupInstanceDataDefinition groupInstance = new GroupInstanceDataDefinition(); - String groupUid = group.getUniqueId(); - - groupInstance.setGroupUid(groupUid); - groupInstance.setType(group.getType()); - groupInstance.setCustomizationUUID(generateCustomizationUUID()); - groupInstance.setCreationTime(creationDate); - groupInstance.setModificationTime(creationDate); - groupInstance.setName(buildGroupInstanceName(componentInstanceName, group.getName())); - groupInstance.setGroupName(group.getName()); - groupInstance.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(groupInstance.getName())); - groupInstance.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(componentInstance.getUniqueId(), groupUid, groupInstance.getNormalizedName())); - groupInstance.setArtifacts(group.getArtifacts()); - -// List fixedArtifactsUuid; -// List artifactsUuid = group.getArtifactsUuid(); -// if (instDeplArtifMap != null) { -// fixedArtifactsUuid = new ArrayList<>(); -// artifactsUuid.forEach(u -> { -// Optional findFirst = instDeplArtifMap.values().stream().filter(a -> u.equals(a.getUniqueId())).findFirst(); -// if (findFirst.isPresent()) { -// fixedArtifactsUuid.add(findFirst.get().getArtifactUUID()); -// } else { -// fixedArtifactsUuid.add(u); -// } -// }); -// } else { -// fixedArtifactsUuid = artifactsUuid; -// } - groupInstance.setArtifactsUuid(group.getArtifactsUuid()); - groupInstance.setProperties(group.getProperties()); - convertPropertiesToInstanceProperties(groupInstance.getProperties()); - groupInstance.setInvariantUUID(group.getInvariantUUID()); - groupInstance.setGroupUUID(group.getGroupUUID()); - groupInstance.setVersion(group.getVersion()); - - return groupInstance; - } - - - protected String buildGroupInstanceName(String instanceName, String groupName) { - return ValidationUtils.normalizeComponentInstanceName(instanceName) + ".." + groupName; - } - - protected String generateCustomizationUUID() { - return UUID.randomUUID().toString(); - } - - protected void convertPropertiesToInstanceProperties(List properties){ - properties.forEach(PropertyDataDefinition::convertPropertyDataToInstancePropertyData); - } - - private TitanOperationStatus logAndReturn(TitanOperationStatus titanOperationStatus, String logMsg, Object ... logParams) { - log.debug(logMsg, logParams); - return titanOperationStatus; - } - - protected GraphVertex throwStorageException(TitanOperationStatus status) { - throw new StorageException(status); - } - - public void setHealingPipelineDao(HealingPipelineDao healingPipelineDao) { - this.healingPipelineDao = healingPipelineDao; - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ByToscaNameDerivedNodeTypeResolver.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ByToscaNameDerivedNodeTypeResolver.java deleted file mode 100644 index 5748629584..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ByToscaNameDerivedNodeTypeResolver.java +++ /dev/null @@ -1,55 +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.jsontitan.operations; - -import fj.data.Either; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.model.DerivedNodeTypeResolver; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Component("derived-resource-resolver") -public class ByToscaNameDerivedNodeTypeResolver implements DerivedNodeTypeResolver { - - @Autowired - private TitanDao titanDao; - - @Override - public Either, TitanOperationStatus> findDerivedResources(String parentResource) { - Map propertiesToMatch = new HashMap<>(); - propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - - propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, parentResource); - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - return titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, JsonParseFlagEnum.NoParse); - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CapabilitiesOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CapabilitiesOperation.java deleted file mode 100644 index 9d7f64c24a..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CapabilitiesOperation.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright © 2016-2018 European Support Limited - * - * 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. - */ - -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -import org.apache.commons.collections.MapUtils; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.operations.StorageException; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -@org.springframework.stereotype.Component("capabilities-operation") -public class CapabilitiesOperation extends BaseOperation { - private static final Logger LOGGER = LoggerFactory.getLogger(CapabilitiesOperation.class); - - public Either, StorageOperationStatus> addCapabilities(String componentId, - List capabilityDefinitions) { - return addOrUpdateCapabilities(componentId, capabilityDefinitions, false); - } - - public Either, StorageOperationStatus> updateCapabilities(String componentId, - List capabilityDefinitions) { - return addOrUpdateCapabilities(componentId, capabilityDefinitions, true); - } - - private Either, StorageOperationStatus> addOrUpdateCapabilities(String componentId, - List capabilityDefinitions, - boolean isUpdateAction) { - StorageOperationStatus statusRes = performUpdateToscaAction(isUpdateAction, - componentId, Collections.singletonList(convertToListCapabilityDataDefinition(capabilityDefinitions))); - if (!statusRes.equals(StorageOperationStatus.OK)) { - LOGGER.error("Failed to find the parent capability of capability type {}." + " status is {}", componentId, - statusRes); - return Either.right(statusRes); - } - return Either.left(capabilityDefinitions); - } - - public StorageOperationStatus deleteCapabilities(Component component, String capabilityIdToDelete) { - return deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.CAPABILITIES, - Collections.singletonList(capabilityIdToDelete)); - } - - public StorageOperationStatus deleteCapabilityProperties(Component component, String capabilityPropIdToDelete) { - return deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.CAPABILITIES_PROPERTIES, - Collections.singletonList(capabilityPropIdToDelete)); - } - - private static ListCapabilityDataDefinition convertToListCapabilityDataDefinition(List capabilities) { - List capabilityDefinitions = new ArrayList<>(capabilities); - return new ListCapabilityDataDefinition(capabilityDefinitions); - } - - private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, String componentId, - List toscaDataList) { - if (isUpdate) { - return updateToscaDataOfToscaElement(componentId, EdgeLabelEnum.CAPABILITIES, - VertexTypeEnum.CAPABILITIES, toscaDataList, JsonPresentationFields.TYPE); - } else { - return addToscaDataToToscaElement(componentId, EdgeLabelEnum.CAPABILITIES, - VertexTypeEnum.CAPABILITIES, toscaDataList, JsonPresentationFields.TYPE); - } - } - - private StorageOperationStatus createOrUpdateCapabilityProperties(String componentId, TopologyTemplate toscaElement, - Map propertiesMap) { - GraphVertex toscaElementV = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse) - .left().on(this::throwStorageException); - Map capabilitiesProperties = toscaElement.getCapabilitiesProperties(); - if(MapUtils.isNotEmpty(capabilitiesProperties)) { - - capabilitiesProperties.forEach((key, val) -> { - Map mapToscaDataDefinition = val.getMapToscaDataDefinition(); - mapToscaDataDefinition.forEach((key1, val1) -> { - - propertiesMap.forEach((propKey, propVal) -> { - Map propValMapToscaDataDefinition = propVal.getMapToscaDataDefinition(); - propValMapToscaDataDefinition.forEach((propKey1, propVal1) -> { - if(propKey1.equals(key1) && val1.getUniqueId().equals(propVal1.getUniqueId())) { - ToscaDataDefinition.mergeDataMaps(mapToscaDataDefinition, propValMapToscaDataDefinition); - } - }); - }); - }); - }); - - ToscaDataDefinition.mergeDataMaps(propertiesMap, capabilitiesProperties); - } - - return topologyTemplateOperation.updateFullToscaData(toscaElementV, - EdgeLabelEnum.CAPABILITIES_PROPERTIES, VertexTypeEnum.CAPABILITIES_PROPERTIES, propertiesMap); - } - - public StorageOperationStatus createOrUpdateCapabilityProperties(String componentId, - Map propertiesMap) { - StorageOperationStatus propertiesStatusRes = null; - if(MapUtils.isNotEmpty(propertiesMap)) { - propertiesStatusRes = createOrUpdateCapabilityProperties(componentId, getTopologyTemplate(componentId), - propertiesMap); - } - - return propertiesStatusRes; - } - - private TopologyTemplate getTopologyTemplate(String componentId) { - return (TopologyTemplate)topologyTemplateOperation - .getToscaElement(componentId, getFilterComponentWithCapProperties()) - .left() - .on(this::throwStorageException); - } - private ComponentParametersView getFilterComponentWithCapProperties() { - ComponentParametersView filter = new ComponentParametersView(); - filter.setIgnoreCapabiltyProperties(false); - return filter; - } - - private ToscaElement throwStorageException(StorageOperationStatus status) { - throw new StorageException(status); - } - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CategoryOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CategoryOperation.java deleted file mode 100644 index 88f0ea3fd7..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CategoryOperation.java +++ /dev/null @@ -1,91 +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.jsontitan.operations; - -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; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.common.util.ValidationUtils; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@org.springframework.stereotype.Component("category-operation") -public class CategoryOperation extends BaseOperation{ - - private static final Logger log = Logger.getLogger(CategoryOperation.class.getName()); - - /** - * - * @param name - * @param type - * @return - */ - public Either getCategory(String name, VertexTypeEnum type) { - if (name != null) { - String categoryUid = UniqueIdBuilder.buildComponentCategoryUid(name, type); - Map props = new HashMap<>(); - props.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(name)); - Either, TitanOperationStatus> either = titanDao.getByCriteria(type, props); - - if (either.isRight()) { - TitanOperationStatus titanOperationStatus = either.right().value(); - log.debug("Problem while geting category with id {}. reason - {}", categoryUid, titanOperationStatus.name()); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { - return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); - } else { - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - } - return Either.left(either.left().value().get(0)); - } else { - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - } - /** - * - * @param categoryV - * @param name - * @return - */ - public Either getSubCategoryForCategory(GraphVertex categoryV, String name ) { - Either, TitanOperationStatus> childrenVertecies = titanDao.getChildrenVertecies(categoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); - if ( childrenVertecies.isRight() ){ - log.debug("Failed to fetch children verticies for category {} error {}", categoryV.getUniqueId(), childrenVertecies.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value())); - } - for ( GraphVertex childV : childrenVertecies.left().value() ){ - if ( childV.getMetadataProperty(GraphPropertyEnum.NAME).equals(name) ){ - return Either.left(childV); - } - } - return Either.right(StorageOperationStatus.NOT_FOUND); - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperation.java deleted file mode 100644 index 70cfc5d238..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperation.java +++ /dev/null @@ -1,297 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - - -import fj.data.Either; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.MapComponentInstanceExternalRefs; -import org.openecomp.sdc.be.model.jsontitan.utils.IdMapper; -import org.openecomp.sdc.be.model.operations.impl.OperationUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.util.*; - -import static java.util.Collections.emptyMap; - -/** - * Created by yavivi on 26/01/2018. - */ -@Component -public class ExternalReferencesOperation extends BaseOperation { - - @Autowired - private IdMapper idMapper; - - @Autowired - private OperationUtils operationUtils; - - - /** - * Constructor - */ - public ExternalReferencesOperation(TitanDao titanDao, NodeTypeOperation nto, TopologyTemplateOperation tto, IdMapper idMapper){ - this.titanDao = titanDao; - this.topologyTemplateOperation = tto; - this.nodeTypeOperation = nto; - this.idMapper = idMapper; - } - - public Either addExternalReferenceWithCommit(String serviceUuid, String componentInstanceName, String objectType, String reference) { - Either addResult = addExternalReference(serviceUuid, componentInstanceName, objectType, reference); - titanDao.commit(); - return addResult; - } - - public Either deleteExternalReferenceWithCommit(String serviceUuid, String componentInstanceName, String objectType, String reference) { - Either result = deleteExternalReference(serviceUuid, componentInstanceName, objectType, reference); - titanDao.commit(); - return result; - } - - public Either updateExternalReferenceWithCommit(String serviceVertexUuid, String componentInstanceName, String objectType, String oldRef, String newRef) { - Either updateResult = updateExternalReference(serviceVertexUuid, componentInstanceName, objectType, oldRef, newRef); - titanDao.commit(); - return updateResult; - } - - public Either addExternalReference(String assetUuid, String componentInstanceName, String objectType, String reference) { - - //Get Container vertex - Either vertexById = titanDao.getVertexById(assetUuid); - if (vertexById.isRight()){ - return Either.right(ActionStatus.RESOURCE_NOT_FOUND); - } - - GraphVertex serviceVertex = vertexById.left().value(); - - final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex); - if (compInstanceUniqueId == null) { - return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); - } - - //Get the external references map vertex - final Either dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); - - //Check whether data vertex found - GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; - - //instanceId -> externalRefsMap - Map externalReferencesFullData; - if (externalRefsVertex == null) { - //External Refs vertex does not exist, create its map. - externalReferencesFullData = new HashMap<>(); - externalReferencesFullData.put(compInstanceUniqueId, new MapComponentInstanceExternalRefs()); - } else { - externalReferencesFullData = (Map) externalRefsVertex.getJson(); - externalReferencesFullData.computeIfAbsent(compInstanceUniqueId, k -> new MapComponentInstanceExternalRefs()); - } - - boolean isAdded = addExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, reference); - updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); - - return isAdded ? Either.left(reference) : Either.right(ActionStatus.EXT_REF_ALREADY_EXIST); - } - - public Either deleteExternalReference(String assetUuid, String componentInstanceName, String objectType, String reference){ - //Get Service vertex - Either vertexById = titanDao.getVertexById(assetUuid); - if (vertexById.isRight()){ - return Either.right(ActionStatus.RESOURCE_NOT_FOUND); - } - GraphVertex serviceVertex = vertexById.left().value(); - - final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex); - if (compInstanceUniqueId == null) { - return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); - } - - //Get the external references map vertex - final Either dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); - - //Check whether data vertex found - GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; - boolean refDeleted = false; - if (externalRefsVertex != null) { - Map externalReferencesFullData = (Map) externalRefsVertex.getJson(); - if (externalReferencesFullData != null) { - refDeleted = deleteExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, reference); - updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); - } - } - - if (refDeleted) { - return Either.left(reference); - } else { - return Either.right(ActionStatus.EXT_REF_NOT_FOUND); - } - } - - public Either updateExternalReference(String assetUuid, String componentInstanceName, String objectType, String oldRef, String newRef) { - //Get Service vertex - Either vertexById = titanDao.getVertexById(assetUuid); - if (vertexById.isRight()){ - return Either.right(ActionStatus.RESOURCE_NOT_FOUND); - } - - GraphVertex serviceVertex = vertexById.left().value(); - - //Map instance_name -> uuid - final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex); - if (compInstanceUniqueId == null) { - return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); - } - - //Get the external references map vertex - final Either dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); - - //Check whether data vertex found - GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; - boolean refReplaced = false; - if (externalRefsVertex != null) { - Map externalReferencesFullData = (Map) externalRefsVertex.getJson(); - if (externalReferencesFullData != null) { - refReplaced = updateExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, oldRef, newRef); - updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); - } - } - if (refReplaced) { - return Either.left(newRef); - } else { - return Either.right(ActionStatus.EXT_REF_NOT_FOUND); - } - } - - public Either>, ActionStatus> getExternalReferences(String assetUuid, String objectType) { - //Get Service vertex - Either vertexById = titanDao.getVertexById(assetUuid); - if (vertexById.isRight()){ - return Either.right(ActionStatus.RESOURCE_NOT_FOUND); - } - - GraphVertex serviceVertex = vertexById.left().value(); - - Map> result = new HashMap(); - - //Get the external references map vertex - final Either dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); - //Check whether data vertex found - GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; - if (externalRefsVertex != null) { - Map externalReferencesFullData = (Map) externalRefsVertex.getJson(); - if (externalReferencesFullData != null) { - externalReferencesFullData.entrySet().forEach( - s -> { - List externalRefsByObjectType = externalReferencesFullData.get(s.getKey()).getExternalRefsByObjectType(objectType); - List refList = externalRefsByObjectType == null ? new ArrayList<>() : externalRefsByObjectType; - String key = idMapper.mapUniqueIdToComponentNameTo(s.getKey(), serviceVertex); - result.put(key, refList); - } - ); - return Either.left(result); - } - } - //No external References Node found on this asset - return Either.left(new HashMap<>()); - } - - public void addAllExternalReferences(String containerUniqueId, - String compInstanceUniqueId, - Map> instanceExternalReferences) { - - GraphVertex serviceVertex = titanDao.getVertexById(containerUniqueId) - .left() - .on(operationUtils::onTitanOperationFailure); - Either dataVertex = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); - Map externalReferencesFullData; - if (dataVertex.isLeft()) { - externalReferencesFullData = (Map) dataVertex.left().value().getJson(); - } else { - externalReferencesFullData = new HashMap<>(); - } - externalReferencesFullData.put(compInstanceUniqueId, new MapComponentInstanceExternalRefs(instanceExternalReferences)); - updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); - } - - public Map> getAllExternalReferences(String containerUniqueId, - String compInstanceUniqueId) { - GraphVertex serviceVertex = titanDao.getVertexById(containerUniqueId) - .left() - .on(operationUtils::onTitanOperationFailure); - - Either dataVertex = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); - if (dataVertex.isRight()) { - return new HashMap<>(); - } - GraphVertex externalRefsVertex = dataVertex.left().value(); - Map externalReferencesFullData = externalRefsVertex == null ? null : (Map) externalRefsVertex.getJson(); - if (externalReferencesFullData != null) { - return externalReferencesFullData - .getOrDefault(compInstanceUniqueId, new MapComponentInstanceExternalRefs()) - .getComponentInstanceExternalRefs(); - } - return emptyMap(); - } - - public Either, ActionStatus> getExternalReferences(String assetUuid, String componentInstanceName, String objectType) { - //Get Service vertex - Either vertexById = titanDao.getVertexById(assetUuid); - if (vertexById.isRight()){ - return Either.right(ActionStatus.RESOURCE_NOT_FOUND); - } - - GraphVertex serviceVertex = vertexById.left().value(); - final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex); - if (compInstanceUniqueId == null) { - return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); - } - - //Get the external references map vertex - final Either dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); - - //Check whether data vertex found - GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; - if (externalRefsVertex != null) { - Map externalReferencesFullData = (Map) externalRefsVertex.getJson(); - if (externalReferencesFullData != null) { - return Either.left(getExternalReferencesByObjectId(externalReferencesFullData, compInstanceUniqueId, objectType)); - } - } - - //No external References Node found on this asset - return Either.left(new LinkedList()); - } - - public IdMapper getIdMapper() { - return idMapper; - } - - public void setIdMapper(IdMapper idMapper) { - this.idMapper = idMapper; - } - - private List getExternalReferencesByObjectId(Map externalReferencesFullData, String componentInstanceId, String objectType) { - MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId); - List externalRefsByObjectType = externalRefsMap.getExternalRefsByObjectType(objectType); - return externalRefsByObjectType != null ? externalRefsByObjectType : new LinkedList<>(); - } - - private boolean updateExternalRef(Map externalReferencesFullData, String componentInstanceId, String objectType, String oldRef, String newRef) { - MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId); - return externalRefsMap.replaceExternalRef(objectType, oldRef, newRef); - } - - private boolean deleteExternalRef(Map externalReferencesFullData, String componentInstanceId, String objectType, String reference) { - MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId); - return externalRefsMap.deleteExternalRef(objectType, reference); - } - - private boolean addExternalRef(Map externalReferencesFullData, String componentInstanceId, String objectType, String reference) { - MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId); - return externalRefsMap.addExternalRef(objectType, reference); - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ForwardingPathOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ForwardingPathOperation.java deleted file mode 100644 index 0d82b0f27d..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ForwardingPathOperation.java +++ /dev/null @@ -1,117 +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.jsontitan.operations; - -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; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility; -import org.openecomp.sdc.common.log.wrappers.Logger; - -import java.util.*; - -@org.springframework.stereotype.Component("forwarding-paths-operations") -public class ForwardingPathOperation extends BaseOperation { - private static final Logger log = Logger.getLogger(ForwardingPathOperation.class.getName()); - - - public Either, StorageOperationStatus> deleteForwardingPath(Service service, Set forwardingPathsToDelete) { - Either, StorageOperationStatus> result = null; - Either getComponentVertex; - StorageOperationStatus status = null; - - if (result == null) { - getComponentVertex = titanDao.getVertexById(service.getUniqueId(), JsonParseFlagEnum.NoParse); - if (getComponentVertex.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); - } - } - if (result == null) { - - status = deleteToscaDataElements(service.getUniqueId(), EdgeLabelEnum.FORWARDING_PATH,new ArrayList<>(forwardingPathsToDelete)); - - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - } - } - - if (result == null) { - result = Either.left(forwardingPathsToDelete); - } - return result; - } - - public Either addForwardingPath(String serviceId, ForwardingPathDataDefinition currentPath) { - return addOrUpdateForwardingPath(false, serviceId, currentPath); - } - - public Either updateForwardingPath(String serviceId, ForwardingPathDataDefinition currentPath) { - return addOrUpdateForwardingPath(true, serviceId, currentPath); - } - - private Either addOrUpdateForwardingPath(boolean isUpdateAction, String serviceId, ForwardingPathDataDefinition currentPath) { - - StorageOperationStatus statusRes; - Either getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(serviceId, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(log, CommonUtility.LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", serviceId, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - return Either.right(statusRes); - } - GraphVertex serviceVertex = getToscaElementRes.left().value(); - if (!isUpdateAction){ - currentPath.setUniqueId(UUID.randomUUID().toString()); - } - statusRes = performUpdateToscaAction(isUpdateAction, serviceVertex, Arrays.asList(currentPath), JsonPresentationFields.FORWARDING_PATH); - { - if (!statusRes.equals(StorageOperationStatus.OK)) { - log.error("Failed to find the parent capability of capability type {}. status is {}", serviceId, statusRes); - return Either.right(statusRes); - } - return Either.left(currentPath); - } - - } - - - private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, GraphVertex graphVertex, List toscaDataList, JsonPresentationFields mapKeyField) { - if (isUpdate) { - return updateToscaDataOfToscaElement(graphVertex, EdgeLabelEnum.FORWARDING_PATH, VertexTypeEnum.FORWARDING_PATH, toscaDataList, JsonPresentationFields.UNIQUE_ID); - } else { - return addToscaDataToToscaElement(graphVertex, EdgeLabelEnum.FORWARDING_PATH, VertexTypeEnum.FORWARDING_PATH, toscaDataList, JsonPresentationFields.UNIQUE_ID); - } - } - -} - - - 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 deleted file mode 100644 index b417f83b74..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java +++ /dev/null @@ -1,395 +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.jsontitan.operations; - -import fj.data.Either; -import org.apache.commons.collections.MapUtils; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.*; -import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; -import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; -import org.openecomp.sdc.be.model.operations.StorageException; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; -import org.openecomp.sdc.common.log.wrappers.Logger; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.stream.Collectors; - -@org.springframework.stereotype.Component("groups-operation") -public class GroupsOperation extends BaseOperation { - - private static final Logger log = Logger.getLogger(GroupsOperation.class.getName()); - - public StorageOperationStatus deleteCalculatedCapabilitiesWithProperties(String componentId, List groupDefinitions) { - Optional error = groupDefinitions.stream().map(g->removeCalculatedCapabilityFromComponent(componentId, g.getUniqueId())).filter(status-> status!=StorageOperationStatus.OK).findFirst(); - if(!error.isPresent()){ - Map extractCapabilityPropertiesFromGroups = ModelConverter.extractCapabilityPropertiesFromGroups(groupDefinitions, false); - error = extractCapabilityPropertiesFromGroups.keySet().stream().map(k->removeCalculatedCapabilityPropertiesFromComponent(componentId, k)).filter(status-> status!=StorageOperationStatus.OK).findFirst(); - } - if(error.isPresent()){ - return error.get(); - } - return StorageOperationStatus.OK; - } - - /** - * Adds the map of the calculated capabilities and the map of the calculated capabilities properties the the component on the graph - * @param componentId - * @param calculatedCapabilities - * @param calculatedCapabilitiesProperties - * @return status of the result the operation - */ - public StorageOperationStatus addCalculatedCapabilitiesWithProperties(String componentId, Map calculatedCapabilities, Map calculatedCapabilitiesProperties) { - - Optional error = calculatedCapabilities.entrySet().stream().map(e-> addElementToComponent(componentId, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst(); - if(!error.isPresent()){ - error = calculatedCapabilitiesProperties.entrySet().stream().map(e->addCalculatedCapabilityPropertiesToComponent(componentId, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst(); - } - if(error.isPresent()){ - return error.get(); - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus updateCalculatedCapabilitiesWithProperties(String componentId, Map calculatedCapabilities, Map calculatedCapabilitiesProperties) { - - Optional error = calculatedCapabilities.entrySet().stream().map(e->updateCalculatedCapabilityOfComponent(componentId, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst(); - if(!error.isPresent()){ - error = calculatedCapabilitiesProperties.entrySet().stream().map(e->updateCalculatedCapabilityPropertiesOnComponent(componentId, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst(); - } - if(error.isPresent()){ - return error.get(); - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus updateCalculatedCapabilityOfComponent(String componentId, Entry capabilities){ - if(MapUtils.isNotEmpty(capabilities.getValue().getMapToscaDataDefinition())) - return updateToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAPABILITIES, capabilities.getValue(), capabilities.getKey()); - return StorageOperationStatus.OK; - } - - private StorageOperationStatus addCalculatedCapabilityPropertiesToComponent(String componentId, Entry properties){ - if(MapUtils.isNotEmpty(properties.getValue().getMapToscaDataDefinition())) - return addToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, properties.getValue(), properties.getKey()); - return StorageOperationStatus.OK; - } - - private StorageOperationStatus updateCalculatedCapabilityPropertiesOnComponent(String componentId, Entry properties){ - if(MapUtils.isNotEmpty(properties.getValue().getMapToscaDataDefinition())) - return updateToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, properties.getValue(), properties.getKey()); - return StorageOperationStatus.OK; - } - - private StorageOperationStatus removeCalculatedCapabilityFromComponent(String componentId, String groupId){ - return deleteToscaDataDeepElementsBlockOfToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, groupId); - } - - private StorageOperationStatus removeCalculatedCapabilityPropertiesFromComponent(String componentId, String groupId){ - return deleteToscaDataDeepElementsBlockOfToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, groupId); - } - - - public Either, StorageOperationStatus> createGroups(Component component, Map groups) { - - Either, StorageOperationStatus> result = null; - Either getComponentVertex = null; - StorageOperationStatus status = null; - - getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); - if (getComponentVertex.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); - } - if (result == null) { - status = topologyTemplateOperation.associateGroupsToComponent(getComponentVertex.left().value(), groups); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - } - } - if (result == null) { - result = Either.left(ModelConverter.convertToGroupDefinitions(groups)); - } - return result; - } - - public Either, StorageOperationStatus> addGroups(Component component, List groups) { - Either, StorageOperationStatus> result = null; - Either getComponentVertex; - StorageOperationStatus status; - - getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); - if (getComponentVertex.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); - } - if (result == null) { - status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.NAME); - - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - } - } - - if (result == null) { - Map mapGroup = groups.stream().collect(Collectors.toMap(GroupDataDefinition::getName, x->x)); - result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup)); - } - return result; - } - - public Either, StorageOperationStatus> deleteGroups(Component component, List groups) { - Either, StorageOperationStatus> result = null; - Either getComponentVertex = null; - StorageOperationStatus status = null; - - getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); - if (getComponentVertex.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); - } - if (result == null) { - List groupName = groups.stream().map(GroupDataDefinition::getName).collect(Collectors.toList()); - status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.GROUPS, groupName); - - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - } - } - - if (result == null) { - Map mapGroup = groups.stream().collect(Collectors.toMap( GroupDataDefinition::getName, x->x)); - result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup)); - } - return result; - } - - public Either, StorageOperationStatus> updateGroups(Component component, List groups, boolean promoteVersion) { - Either, StorageOperationStatus> result = null; - Either getComponentVertex = null; - StorageOperationStatus status = null; - - getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); - if (getComponentVertex.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); - } - if (result == null) { - groups.forEach(gr -> { - updateVersion(promoteVersion, gr); - String groupUUID = UniqueIdBuilder.generateUUID(); - gr.setGroupUUID(groupUUID); - }); - - status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.NAME); - - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - } - } - - if (result == null) { - Map mapGroup = groups.stream().collect(Collectors.toMap( GroupDataDefinition::getName, x->x)); - result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup)); - } - return result; - } - - private void updateVersion(boolean promoteVersion, T group) { - if(promoteVersion) { - String version = group.getVersion(); - String newVersion = increaseMajorVersion(version); - group.setVersion(newVersion); - } - } - - public void updateGroupOnComponent(String componentId, GroupDefinition groupDefinition) { - GraphVertex componentVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata) - .left() - .on(this::onTitanError); - - StorageOperationStatus updateToscaResult = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition, - JsonPresentationFields.NAME); - - if (StorageOperationStatus.OK != updateToscaResult) { - throw new StorageException(updateToscaResult, groupDefinition.getUniqueId()); - } - - updateLastUpdateDate(componentVertex); - } - - private void updateLastUpdateDate(GraphVertex componentVertex) { - componentVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - titanDao.updateVertex(componentVertex) - .left() - .on(this::onTitanError); - } - - GraphVertex onTitanError(TitanOperationStatus titanOperationStatus) { - throw new StorageException( - DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); - } - - public Either, StorageOperationStatus> updateGroupPropertiesOnComponent(String componentId, GroupDefinition group, List newGroupProperties) { - - Either, StorageOperationStatus> result = null; - Either getComponentVertex = null; - GraphVertex componentVertex = null; - - getComponentVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); - if (getComponentVertex.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); - } - if (result == null) { - componentVertex = getComponentVertex.left().value(); - //update - List properties = group.getProperties(); - newGroupProperties.forEach(np -> { - Optional currentProp = properties.stream().filter(p -> p.getName().equals(np.getName())).findAny(); - if (currentProp.isPresent()) { - currentProp.get().setValue(np.getValue()); - } - }); - - StorageOperationStatus updateDataRes = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, group, JsonPresentationFields.NAME); - if (updateDataRes != StorageOperationStatus.OK) { - log.debug("Failed to update properties for group {} error {}", group.getName(), updateDataRes); - result = Either.right(updateDataRes); - } - } - if (result == null) { - componentVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - Either updateRes = titanDao.updateVertex(componentVertex); - if (updateRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the component {}. Status is {} ", componentId, updateRes.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value())); - } - } - if (result == null) { - result = Either.left(newGroupProperties); - } - return result; - } - - /** - * The version of the group is an integer. In order to support BC, we might get a version in a float format. - * - * @param version - * @return - */ - private String increaseMajorVersion(String version) { - - String[] versionParts = version.split(ToscaElementLifecycleOperation.VERSION_DELIMITER_REGEXP); - Integer majorVersion = Integer.parseInt(versionParts[0]); - - majorVersion++; - - return String.valueOf(majorVersion); - - } - - public Either, StorageOperationStatus> updateGroupInstances(Component component, String instanceId, List updatedGroupInstances) { - - Either, StorageOperationStatus> result = null; - StorageOperationStatus status = null; - - Either getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); - if (getComponentVertex.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); - } - if (result == null) { - List pathKeys = new ArrayList<>(); - pathKeys.add(instanceId); - status = updateToscaDataDeepElementsOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, updatedGroupInstances, pathKeys, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - } - } - if (result == null) { - result = Either.left(updatedGroupInstances); - } - return result; - } - - public Either updateGroup(Component component, GroupDefinition currentGroup) { - StorageOperationStatus status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroup, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status); - return Either.right(status); - } - return Either.left(currentGroup); - } - - public StorageOperationStatus deleteGroup(Component component, String currentGroupName) { - StorageOperationStatus status = deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroupName, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group {} of component {}. The status is}. ", currentGroupName, component.getName(), status); - } - return status; - } - - public Either addGroup(Component component, GroupDefinition currentGroup) { - StorageOperationStatus status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroup, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status); - return Either.right(status); - } - return Either.left(currentGroup); - } - - public Either updateGroupInstancePropertyValuesOnGraph(String componentId, String instanceId, GroupInstance oldGroupInstance, List newProperties) { - - Either getComponentVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); - if (getComponentVertex.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); - } - - List propertiesOld = oldGroupInstance.getProperties(); - newProperties.forEach(np -> { - Optional prop = propertiesOld.stream().filter(p -> p.getName().equals(np.getName())).findFirst(); - if (prop.isPresent()) { - prop.get().setValue(np.getValue()); - } - }); - GroupInstanceDataDefinition groupInstanceDataDefinition = new GroupInstanceDataDefinition(oldGroupInstance); - List pathKeys = new ArrayList<>(); - pathKeys.add(instanceId); - StorageOperationStatus updateDataRes = updateToscaDataDeepElementOfToscaElement(componentId, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, groupInstanceDataDefinition, pathKeys, JsonPresentationFields.NAME); - if (updateDataRes != StorageOperationStatus.OK) { - log.debug("Failed to update properties for group instance {} error {}", oldGroupInstance.getName(), updateDataRes); - return Either.right(updateDataRes); - } - return Either.left(oldGroupInstance); - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InstancesOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InstancesOperation.java deleted file mode 100644 index 84814e4863..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InstancesOperation.java +++ /dev/null @@ -1,25 +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.jsontitan.operations; - -public class InstancesOperation extends BaseOperation { - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperation.java deleted file mode 100644 index b4433d1be0..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperation.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright © 2016-2018 European Support Limited - * - * 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. - */ - -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import org.apache.commons.collections.MapUtils; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.InterfaceDefinition; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; - -@org.springframework.stereotype.Component("interfaces-operation") -public class InterfaceOperation extends BaseOperation { - - public Either, StorageOperationStatus> addInterfaces(String componentId, - List interfaceDefinitions) { - return addOrUpdateInterfaces(false, componentId, interfaceDefinitions); - } - - private Either, StorageOperationStatus> addOrUpdateInterfaces(boolean isUpdateAction, - String componentId, List interfaceDefinitions) { - - List interfaceDataDefinitions = - interfaceDefinitions.stream().map(InterfaceDataDefinition::new).collect(Collectors.toList()); - StorageOperationStatus statusRes = - performUpdateToscaAction(isUpdateAction, componentId, interfaceDataDefinitions, EdgeLabelEnum.INTERFACE, - VertexTypeEnum.INTERFACE); - if (!statusRes.equals(StorageOperationStatus.OK)) { - return Either.right(statusRes); - } - return Either.left(interfaceDefinitions); - } - - private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, String componentId, - List toscaDataList, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) { - if (isUpdate) { - return updateToscaDataOfToscaElement(componentId, edgeLabel, vertexLabel, toscaDataList, - JsonPresentationFields.UNIQUE_ID); - } else { - return addToscaDataToToscaElement(componentId, edgeLabel, vertexLabel, toscaDataList, - JsonPresentationFields.UNIQUE_ID); - } - } - - public Either, StorageOperationStatus> updateInterfaces(String componentId, - List interfaceDefinitions) { - return addOrUpdateInterfaces(true, componentId, interfaceDefinitions); - } - - public Either deleteInterface(String componentId, String interfacesToDelete) { - - StorageOperationStatus statusRes = deleteToscaDataElements(componentId, EdgeLabelEnum.INTERFACE, - Collections.singletonList(interfacesToDelete)); - if (!statusRes.equals(StorageOperationStatus.OK)) { - return Either.right(statusRes); - } - - Either, TitanOperationStatus> componentEither = - getDataFromGraph(componentId, EdgeLabelEnum.INTERFACE); - if (componentEither.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentEither.right().value())); - } - - Map interfaceDataDefinitionMap = componentEither.left().value(); - if (MapUtils.isEmpty(interfaceDataDefinitionMap)) { - statusRes = removeToscaData(componentId, EdgeLabelEnum.INTERFACE, VertexTypeEnum.INTERFACE); - if (!statusRes.equals(StorageOperationStatus.OK)) { - return Either.right(statusRes); - } - } - - return Either.left(interfacesToDelete); - } - -} \ No newline at end of file diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeFilterOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeFilterOperation.java deleted file mode 100644 index 7b3076ae8b..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeFilterOperation.java +++ /dev/null @@ -1,175 +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.jsontitan.operations; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import fj.data.Either; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterPropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility; -import org.openecomp.sdc.common.log.wrappers.Logger; - -@org.springframework.stereotype.Component("service-filter-operations") -public class NodeFilterOperation extends BaseOperation { - - private static Logger logger = Logger.getLogger(NodeFilterOperation.class); - - public Either, StorageOperationStatus> deleteNodeFilters(Service service, - Set componentInstanceIds) { - Either getComponentVertex; - Either getNodeFilterVertex; - StorageOperationStatus status; - - getComponentVertex = titanDao.getVertexById(service.getUniqueId(), JsonParseFlagEnum.NoParse); - if (getComponentVertex.isRight()) { - return Either.right( - DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); - } - - getNodeFilterVertex = - titanDao.getChildVertex(getComponentVertex.left().value(), EdgeLabelEnum.NODE_FILTER_TEMPLATE, - JsonParseFlagEnum.NoParse); - if (getNodeFilterVertex.isLeft()) { - status = deleteToscaDataElements(service.getUniqueId(), EdgeLabelEnum.NODE_FILTER_TEMPLATE, - new ArrayList<>(componentInstanceIds)); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - } - - return Either.left(componentInstanceIds); - } - - - public Either deleteNodeFilter(Service service, String componentInstanceId) { - final Either, StorageOperationStatus> listStorageOperationStatusEither = - deleteNodeFilters(service, ImmutableSet.of(componentInstanceId)); - if (listStorageOperationStatusEither.isRight()) { - return Either.right(listStorageOperationStatusEither.right().value()); - } - return Either.left(componentInstanceId); - } - - - public Either createNodeFilter(String serviceId, - String componentInstanceId) { - CINodeFilterDataDefinition nodeFilterDataDefinition = new CINodeFilterDataDefinition(); - return addOrUpdateNodeFilter(false, serviceId, componentInstanceId, nodeFilterDataDefinition); - } - - public Either deleteConstraint(String serviceId, - String componentInstanceId, CINodeFilterDataDefinition nodeFilterDataDefinition, int propertyIndex) { - ListDataDefinition properties = - nodeFilterDataDefinition.getProperties(); - properties.getListToscaDataDefinition().remove(propertyIndex); - nodeFilterDataDefinition.setProperties(properties); - return addOrUpdateNodeFilter(true, serviceId, componentInstanceId, nodeFilterDataDefinition); - } - - public Either addNewProperty(String serviceId, - String componentInstanceId, CINodeFilterDataDefinition nodeFilterDataDefinition, - RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition) { - ListDataDefinition properties = - nodeFilterDataDefinition.getProperties(); - if (properties == null) { - properties = new ListDataDefinition<>(); - nodeFilterDataDefinition.setProperties(properties); - } - properties.getListToscaDataDefinition().add(requirementNodeFilterPropertyDataDefinition); - nodeFilterDataDefinition.setProperties(properties); - return addOrUpdateNodeFilter(true, serviceId, componentInstanceId, nodeFilterDataDefinition); - } - - public Either updateProperties(String serviceId, - String componentInstanceId, CINodeFilterDataDefinition nodeFilterDataDefinition, - List requirementNodeFilterPropertyDataDefinition) { - ListDataDefinition properties = - nodeFilterDataDefinition.getProperties(); - properties.getListToscaDataDefinition().clear(); - properties.getListToscaDataDefinition().addAll(requirementNodeFilterPropertyDataDefinition); - nodeFilterDataDefinition.setProperties(properties); - return addOrUpdateNodeFilter(true, serviceId, componentInstanceId, nodeFilterDataDefinition); - } - - public Either updateNodeFilter(String serviceId, - String componentInstanceId, CINodeFilterDataDefinition ciNodeFilterDataDefinition) { - return addOrUpdateNodeFilter(true, serviceId, componentInstanceId, ciNodeFilterDataDefinition); - } - - private Either addOrUpdateNodeFilter(boolean isUpdateAction, - String serviceId, String componentInstanceId, CINodeFilterDataDefinition ciNodeFilterDataDefinition) { - - StorageOperationStatus statusRes; - Either getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(serviceId, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(logger, CommonUtility.LogLevelEnum.DEBUG, - "Failed to get tosca element {} upon adding the properties. Status is {}. ", serviceId, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - return Either.right(statusRes); - } - GraphVertex serviceVertex = getToscaElementRes.left().value(); - ciNodeFilterDataDefinition.setID(componentInstanceId); - statusRes = performUpdateToscaAction(isUpdateAction, serviceVertex, ImmutableList.of(ciNodeFilterDataDefinition)); - if (!statusRes.equals(StorageOperationStatus.OK)) { - titanDao.rollback(); - logger.error( - " Failed to perform tosca update for node filter in service {} , component instance {}. status is {}", - serviceId, componentInstanceId, statusRes); - return Either.right(statusRes); - } - titanDao.commit(); - return Either.left(ciNodeFilterDataDefinition); - - } - - - private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, GraphVertex graphVertex, - List toscaDataList) { - if (isUpdate) { - return updateToscaDataOfToscaElement(graphVertex, EdgeLabelEnum.NODE_FILTER_TEMPLATE, - VertexTypeEnum.NODE_FILTER_TEMPLATE, toscaDataList, JsonPresentationFields.UNIQUE_ID); - } else { - return addToscaDataToToscaElement(graphVertex, EdgeLabelEnum.NODE_FILTER_TEMPLATE, - VertexTypeEnum.NODE_FILTER_TEMPLATE, toscaDataList, JsonPresentationFields.UNIQUE_ID); - } - } - -} - - - diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java deleted file mode 100644 index de396b4c1a..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java +++ /dev/null @@ -1,2400 +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.jsontitan.operations; - -import com.thinkaurelius.titan.core.TitanVertex; -import fj.data.Either; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; -import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.GroupInstance; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RelationshipImpl; -import org.openecomp.sdc.be.model.RelationshipInfo; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; -import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; -import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; -import org.openecomp.sdc.common.api.ArtifactTypeEnum; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.common.util.ValidationUtils; - -import java.io.IOException; -import java.util.*; -import java.util.Map.Entry; -import java.util.function.BiConsumer; -import java.util.function.BiPredicate; -import java.util.stream.Collectors; - -@org.springframework.stereotype.Component("node-template-operation") -public class NodeTemplateOperation extends BaseOperation { - private static final String FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR = "Failed to fetch container vertex {} error {}"; - private static final String FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE = "Failed to update topology template {} with new component instance {}. "; - private static final String ARTIFACT_PLACEHOLDER_TYPE = "type"; - private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName"; - private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description"; - public static final String HEAT_ENV_NAME = "heatEnv"; - public static final String HEAT_VF_ENV_NAME = "VfHeatEnv"; - public static final String HEAT_ENV_SUFFIX = "env"; - private static Integer defaultHeatTimeout; - public static final Integer NON_HEAT_TIMEOUT = 0; - - private static final Logger log = Logger.getLogger(NodeTemplateOperation.class.getName()); - - public NodeTemplateOperation() { - defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); - if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) { - defaultHeatTimeout = 60; - } - } - - public static Integer getDefaultHeatTimeout() { - return defaultHeatTimeout; - } - - public Either, StorageOperationStatus> addComponentInstanceToTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, String instanceNumberSuffix, ComponentInstance componentInstance, - boolean allowDeleted, User user) { - - Either, StorageOperationStatus> result = null; - Either addComponentInstanceRes = null; - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to create component instance {} in component {}", componentInstance, container.getUniqueId()); - ComponentInstanceDataDefinition componentInstanceData = null; - Either newInstanceNameRes = null; - - Either metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseJson); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - if (result == null) { - - newInstanceNameRes = buildValidateInstanceName(container, originToscaElement, componentInstance, instanceNumberSuffix); - if (newInstanceNameRes.isRight()) { - result = Either.right(newInstanceNameRes.right().value()); - } - } - if (result == null) { - componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(), newInstanceNameRes.left().value(), true, originToscaElement); - - addComponentInstanceRes = addComponentInstanceToTopologyTemplate(container, originToscaElement, componentInstanceData, metadataVertex.left().value(), allowDeleted, user); - - if (addComponentInstanceRes.isRight()) { - StorageOperationStatus status = addComponentInstanceRes.right().value(); - if (status == StorageOperationStatus.NOT_FOUND) { - status = StorageOperationStatus.INVALID_ID; - } - result = Either.right(status); - } - if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { - TopologyTemplate updatedContainer = addComponentInstanceRes.left().value(); - result = addServerCapAndReqToProxyServerInstance(updatedContainer, componentInstance, componentInstanceData); - if(result.isRight()) { - return result; - } - - result = addServiceInstancePropertiesToProxyServiceInstance(updatedContainer, componentInstance); - if(result.isRight()) { - return result; - } - - result = addServiceInstanceInputsToProxyServiceInstance(updatedContainer, componentInstance); - if(result.isRight()) { - return result; - } - - result = addServiceInstanceInterfacesToProxyServiceInstance(updatedContainer, componentInstance); - if(result.isRight()) { - return result; - } - - } - } - if (result == null) { - result = Either.left(new ImmutablePair<>(addComponentInstanceRes.left().value(), componentInstanceData.getUniqueId())); - } - return result; - } - - private Either, StorageOperationStatus> addServerCapAndReqToProxyServerInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance, - - ComponentInstanceDataDefinition componentInstanceData) { - - Either, StorageOperationStatus> result; - - Map calcCap = updatedContainer.getCalculatedCapabilities(); - Map calcReg = updatedContainer.getCalculatedRequirements(); - Map calcCapProp = updatedContainer.getCalculatedCapabilitiesProperties(); - - Map> additionalCap = componentInstance.getCapabilities(); - Map> additionalReq = componentInstance.getRequirements(); - - MapListCapabilityDataDefinition allCalculatedCap = calcCap == null || !calcCap.containsKey(componentInstanceData.getUniqueId()) ? new MapListCapabilityDataDefinition() : calcCap.get(componentInstanceData.getUniqueId()); - /******** capability ****************************/ - StorageOperationStatus status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, componentInstanceData.getUniqueId()); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status); - return Either.right(status); - } - - if (additionalCap != null && !additionalCap.isEmpty()) { - - Map serverCap = additionalCap.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, en -> new ListCapabilityDataDefinition(en.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())))); - - serverCap.entrySet().forEach(entryPerType -> - entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> { - cap.addToPath(componentInstance.getUniqueId()); - allCalculatedCap.add(entryPerType.getKey(), cap); - })); - - - addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, componentInstance.getUniqueId()); - - /******** capability property ****************************/ - status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, componentInstanceData.getUniqueId()); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty properties for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status); - return Either.right(status); - } - - MapCapabilityProperty allCalculatedCapProp = calcCapProp == null || !calcCapProp.containsKey(componentInstanceData.getUniqueId()) ? new MapCapabilityProperty() : calcCapProp.get(componentInstanceData.getUniqueId()); - - additionalCap.forEach(new BiConsumer>() { - @Override - public void accept(String s, List caps) { - - if (caps != null && !caps.isEmpty()) { - - MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); - - for (CapabilityDefinition cap : caps) { - List capPrps = cap.getProperties(); - if (capPrps != null) { - - for (ComponentInstanceProperty cip : capPrps) { - dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip)); - } - - StringBuilder sb = new StringBuilder(componentInstance.getUniqueId()); - sb.append(ModelConverter.CAP_PROP_DELIM); - - sb.append(cap.getOwnerId()); - - sb.append(ModelConverter.CAP_PROP_DELIM).append(s).append(ModelConverter.CAP_PROP_DELIM).append(cap.getName()); - allCalculatedCapProp.put(sb.toString(), dataToCreate); - } - } - - } - - } - }); - - addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, allCalculatedCapProp, componentInstance.getUniqueId()); - } - - /******** Requirements property ****************************/ - if (additionalReq != null && !additionalReq.isEmpty()) { - - MapListRequirementDataDefinition allCalculatedReq = calcReg == null || !calcReg.containsKey(componentInstanceData.getUniqueId()) ? new MapListRequirementDataDefinition() : calcReg.get(componentInstanceData.getUniqueId()); - status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceData.getUniqueId()); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated Requirements for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status); - return Either.right(status); - } - - Map serverReq = additionalReq.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, en -> new ListRequirementDataDefinition(en.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())))); - - serverReq.entrySet().forEach(entryPerType -> - entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> { - cap.addToPath(componentInstance.getUniqueId()); - allCalculatedReq.add(entryPerType.getKey(), cap); - })); - - - addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, componentInstance.getUniqueId()); - - } - - Either updatedComponentInstanceRes = topologyTemplateOperation.getToscaElement(updatedContainer.getUniqueId()); - if (updatedComponentInstanceRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ", updatedContainer.getName(), componentInstance.getName()); - result = Either.right(updatedComponentInstanceRes.right().value()); - } - result = Either.left(new ImmutablePair<>((TopologyTemplate) updatedComponentInstanceRes.left().value(), componentInstanceData.getUniqueId())); - return result; - } - - private Either buildValidateInstanceName(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance, String instanceNumberSuffix) { - - Either result = null; - String instanceName = componentInstance.getName(); - if (StringUtils.isEmpty(instanceName) || instanceName.equalsIgnoreCase(originToscaElement.getName()) || componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { - instanceName = buildComponentInstanceName(instanceNumberSuffix, instanceName); - } else if (!isUniqueInstanceName(container, componentInstance.getName())) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create component instance with name {} on component container {}. The instance with the same name already exists. ", componentInstance.getName(), container.getName()); - result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS); - } - if (result == null) { - result = Either.left(instanceName); - } - return result; - } - - private Either, StorageOperationStatus> addServiceInstancePropertiesToProxyServiceInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance) { - - List propertiesList = componentInstance.getProperties(); - - if (propertiesList != null && !propertiesList.isEmpty()) { - Map propertiesMap = propertiesList.stream().map(PropertyDataDefinition::new) - .collect(Collectors.toMap( - PropertyDataDefinition::getName, i -> i)); - MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(propertiesMap); - Map instPropertiesMap = new HashMap<>(); - instPropertiesMap.put(componentInstance.getUniqueId(), instProperties); - updatedContainer.setInstProperties(instPropertiesMap); - Either getToscaElementRes = titanDao.getVertexById(updatedContainer.getUniqueId(), JsonParseFlagEnum.NoParse); - if(getToscaElementRes.isLeft()){ - deleteToscaDataDeepElementsBlockToToscaElement(getToscaElementRes.left().value(), EdgeLabelEnum.INST_PROPERTIES, - VertexTypeEnum.INST_PROPERTIES, componentInstance.getUniqueId()); - } - StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), - EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, instProperties, - componentInstance.getUniqueId()); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - - - } - return Either.left(new ImmutablePair<>(updatedContainer, componentInstance.getUniqueId())); - } - - private Either, StorageOperationStatus> addServiceInstanceInputsToProxyServiceInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance) { - - List inputsList = componentInstance.getInputs(); - - if (CollectionUtils.isNotEmpty(inputsList)) { - Map inputsMap = inputsList.stream().map( - PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, i -> i)); - MapPropertiesDataDefinition instInputs = new MapPropertiesDataDefinition(inputsMap); - Map instInputsMap = new HashMap<>(); - instInputsMap.put(componentInstance.getUniqueId(), instInputs); - updatedContainer.setInstInputs(instInputsMap); - - StorageOperationStatus status = - addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), - EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, instInputs, - componentInstance.getUniqueId()); - if(status != StorageOperationStatus.OK) { - return Either.right(status); - } - } - - return Either.left(new ImmutablePair<>(updatedContainer, componentInstance.getUniqueId())); - } - - private Either, StorageOperationStatus> addServiceInstanceInterfacesToProxyServiceInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance) { - Map interfaces = componentInstance.getInterfaces(); - - if(MapUtils.isNotEmpty(interfaces)){ - Map interfacesMap = interfaces.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> (InterfaceDataDefinition) e.getValue())); - MapInterfaceDataDefinition instInterfaces = new MapInterfaceDataDefinition(interfacesMap); - - Map instInterfacesMap = new HashMap<>(); - instInterfacesMap.put(componentInstance.getUniqueId(), instInterfaces); - updatedContainer.setComponentInstInterfaces(instInterfacesMap); - - StorageOperationStatus status = - addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), - EdgeLabelEnum.INST_INTERFACES, VertexTypeEnum.INST_INTERFACES, instInterfaces, - componentInstance.getUniqueId()); - - if(status != StorageOperationStatus.OK) { - return Either.right(status); - } - } - - return Either.left(new ImmutablePair<>(updatedContainer, componentInstance.getUniqueId())); - } - - public Either addComponentInstanceToTopologyTemplate( - TopologyTemplate container, ToscaElement originToscaElement, - ComponentInstanceDataDefinition componentInstance, GraphVertex metadataVertex, boolean allowDeleted, - User user) { - - Either result = null; - Either updateContainerComponentRes = null; - String containerComponentId = container.getUniqueId(); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to create component instance {} in component {}", componentInstance, containerComponentId); - String instOriginComponentId = componentInstance.getComponentUid(); - Either updateElement = null; - - Boolean isDeleted = (Boolean) originToscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED); - - if (!allowDeleted && (isDeleted != null) && isDeleted) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance", instOriginComponentId); - result = Either.right(StorageOperationStatus.INVALID_ID); - } - Boolean isArchived = originToscaElement.isArchived(); - if ( isArchived != null && isArchived ){ - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create instance {}. Origin {} component is archived . ", componentInstance.getName(), originToscaElement.getName()); - result = Either.right(StorageOperationStatus.COMPONENT_IS_ARCHIVED); - } - - if (result == null) { - container.addComponentInstance(componentInstance); - metadataVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - topologyTemplateOperation.fillToscaElementVertexData(metadataVertex, container, JsonParseFlagEnum.ParseAll); - updateElement = titanDao.updateVertex(metadataVertex); - if (updateElement.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(), componentInstance.getName()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); - } - } - if (result == null) { - Either addToscaDataRes = addComponentInstanceToscaDataToContainerComponent(originToscaElement, componentInstance, updateElement.left().value(), user); - if (addToscaDataRes.isRight()) { - result = Either.right(addToscaDataRes.right().value()); - } - } - if (result == null) { - StorageOperationStatus createInstanceEdge = createInstanceEdge(metadataVertex, componentInstance); - result = createInstanceEdge == StorageOperationStatus.OK ? null : Either.right(createInstanceEdge); - } - - if (result == null) { - updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId); - if (updateContainerComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ", container.getName(), componentInstance.getName()); - result = Either.right(updateContainerComponentRes.right().value()); - } - } - if (result == null) { - result = Either.left((TopologyTemplate) updateContainerComponentRes.left().value()); - } - return result; - } - - public Either, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance) { - - Either, StorageOperationStatus> result = null; - Either updateContainerComponentRes = null; - - String containerComponentId = container.getUniqueId(); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstance, containerComponentId); - ComponentInstanceDataDefinition componentInstanceData = null; - - Either metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(), componentInstance.getName(), false, originToscaElement); - container.addComponentInstance(componentInstanceData); - metadataVertex.left().value().setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - topologyTemplateOperation.fillToscaElementVertexData(metadataVertex.left().value(), container, JsonParseFlagEnum.ParseAll); - Either updateElement = titanDao.updateVertex(metadataVertex.left().value()); - if (updateElement.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(), componentInstance.getName()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); - } - } - if (result == null) { - updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId); - if (updateContainerComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", container.getName(), componentInstance.getName()); - result = Either.right(updateContainerComponentRes.right().value()); - } - } - if (result == null) { - result = Either.left(new ImmutablePair<>((TopologyTemplate) updateContainerComponentRes.left().value(), componentInstanceData.getUniqueId())); - } - return result; - } - - public Either updateComponentInstanceMetadataOfTopologyTemplate(TopologyTemplate container, ComponentParametersView filter) { - - Either result = null; - Either updateContainerComponentRes = null; - - String containerComponentId = container.getUniqueId(); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata of container component {}", containerComponentId); - - Either metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - metadataVertex.left().value().setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - topologyTemplateOperation.fillToscaElementVertexData(metadataVertex.left().value(), container, JsonParseFlagEnum.ParseAll); - Either updateElement = titanDao.updateVertex(metadataVertex.left().value()); - if (updateElement.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {}. ", container.getName()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); - } - } - if (result == null) { - updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId, filter); - if (updateContainerComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {}. ", container.getName()); - result = Either.right(updateContainerComponentRes.right().value()); - } - } - if (result == null) { - result = Either.left((TopologyTemplate) updateContainerComponentRes.left().value()); - } - return result; - } - - public Either, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(TopologyTemplate container, String componentInstanceId) { - - Either, StorageOperationStatus> result = null; - Either updateContainerComponentRes = null; - - String containerComponentId = container.getUniqueId(); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstanceId, containerComponentId); - - Either metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - GraphVertex containerV = null; - ComponentInstanceDataDefinition removedComponentInstance = null; - if (result == null) { - removedComponentInstance = container.getComponentInstances().remove(componentInstanceId); - containerV = metadataVertex.left().value(); - StorageOperationStatus status = removeRelationsOfInstance(container, componentInstanceId, containerV); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete relation for component instance {} in container. error {}", componentInstanceId, container.getUniqueId(), status); - result = Either.right(status); - } - - containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - topologyTemplateOperation.fillToscaElementVertexData(containerV, container, JsonParseFlagEnum.ParseAll); - Either updateElement = titanDao.updateVertex(containerV); - if (updateElement.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(), componentInstanceId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); - } - } - if (result == null) { - StorageOperationStatus status = deleteComponentInstanceToscaDataFromContainerComponent(containerV, componentInstanceId); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete data for instance {} in container {}. error {] ", componentInstanceId, container.getUniqueId(), status); - return Either.right(status); - } - ComponentInstance componentInstance = new ComponentInstance(removedComponentInstance); - StorageOperationStatus createInstanceEdge = removeInstanceEdge(containerV, componentInstance); - result = createInstanceEdge == StorageOperationStatus.OK ? null : Either.right(createInstanceEdge); - } - if (result == null) { - updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId); - if (updateContainerComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} after deleting the component instance {}. ", container.getName(), componentInstanceId); - result = Either.right(updateContainerComponentRes.right().value()); - } - } - if (result == null) { - result = Either.left(new ImmutablePair<>((TopologyTemplate) updateContainerComponentRes.left().value(), componentInstanceId)); - } - return result; - } - - private StorageOperationStatus removeRelationsOfInstance(TopologyTemplate container, String ciToRemove, GraphVertex containerV) { - CompositionDataDefinition composition = container.getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()); - if (composition != null) { - Map relations = composition.getRelations(); - if (MapUtils.isNotEmpty(relations)) { - Either>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); - if (capResult.isRight()) { - return capResult.right().value(); - - } - Map calculatedCapabilty = capResult.left().value().getRight(); - - Either>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); - if (capFullResult.isRight()) { - return capFullResult.right().value(); - - } - Map fullFilledCapabilty = capFullResult.left().value().getRight(); - - Either>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); - if (reqResult.isRight()) { - return reqResult.right().value(); - } - Map calculatedRequirement = reqResult.left().value().getRight(); - - Either>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); - if (reqResult.isRight()) { - return reqResult.right().value(); - } - Map fullfilledRequirement = reqFullResult.left().value().getRight(); - - Iterator> iterator = relations.entrySet().iterator(); - while (iterator.hasNext()) { - Entry relation = iterator.next(); - RelationshipInstDataDefinition relationToDelete = relation.getValue(); - if (relationToDelete.getFromId().equals(ciToRemove) || relationToDelete.getToId().equals(ciToRemove)) { - iterator.remove(); - if (relationToDelete.getFromId().equals(ciToRemove)) { - updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, ciToRemove, relationToDelete, null); - updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, relationToDelete.getToId(), relationToDelete, null); - } - if (relationToDelete.getToId().equals(ciToRemove)) { - updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, relationToDelete.getFromId(), relationToDelete, null); - updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, ciToRemove, relationToDelete, null); - } - } - } - return updateAllAndCalculatedCapReqOnGraph(container.getUniqueId(), containerV, capResult, capFullResult, reqResult, reqFullResult); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus deleteComponentInstanceToscaDataFromContainerComponent(GraphVertex containerV, String componentInstanceId) { - StorageOperationStatus status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty properties for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove fullfilled capabilities for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove attributes for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove properties for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance inputs for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance deployment artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INSTANCE_ARTIFACTS, VertexTypeEnum.INSTANCE_ARTIFACTS, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance external refs for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_INTERFACES, - VertexTypeEnum.INST_INTERFACES, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, - "Failed to remove service instance interfaces for instance {} in container {}. " + - "error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - return StorageOperationStatus.OK; - } - - protected Either addComponentInstanceToscaDataToContainerComponent(ToscaElement originToscaElement, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user) { - - Either result; - StorageOperationStatus status; - if (originToscaElement.getToscaType() == ToscaElementTypeEnum.NODE_TYPE) { - status = addComponentInstanceToscaDataToNodeTypeContainer((NodeType) originToscaElement, componentInstance, updatedContainerVertex); - } else { - status = addComponentInstanceToscaDataToTopologyTemplateContainer((TopologyTemplate) originToscaElement, componentInstance, updatedContainerVertex); - } - if (status == StorageOperationStatus.OK) { - result = Either.left(updatedContainerVertex); - } else { - result = Either.right(status); - } - return result; - } - - private StorageOperationStatus addComponentInstanceToscaDataToTopologyTemplateContainer(TopologyTemplate originTopologyTemplate, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) { - - StorageOperationStatus status; - - status = addCalculatedCapReqFromTopologyTemplate(originTopologyTemplate, componentInstance, updatedContainerVertex); - - if (status != StorageOperationStatus.OK) { - - return status; - } - - MapPropertiesDataDefinition instInputs = new MapPropertiesDataDefinition(originTopologyTemplate.getInputs()); - MapPropertiesDataDefinition instInputsAsProperties = turnInputsIntoProperties(instInputs); - - status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, instInputsAsProperties, componentInstance.getUniqueId()); - if (status != StorageOperationStatus.OK) { - return status; - } - - return status; - } - - private MapPropertiesDataDefinition turnInputsIntoProperties(MapPropertiesDataDefinition instInput){ - if (instInput.getMapToscaDataDefinition() != null) { - for (PropertyDataDefinition currProp : instInput.getMapToscaDataDefinition().values()){ - String temp = currProp.getValue(); - currProp.setValue(currProp.getDefaultValue()); - currProp.setDefaultValue(temp); - } - } - return instInput; - } - - private MapListCapabilityDataDefinition prepareCalculatedCapabiltyForTopologyTemplate( - Map capabilities, - ComponentInstanceDataDefinition componentInstance, - MapListCapabilityDataDefinition calculatedCap) { - MapListCapabilityDataDefinition allCalculatedCap = - new MapListCapabilityDataDefinition(calculatedCap); - populateCapability(capabilities, componentInstance, allCalculatedCap); - return allCalculatedCap; - } - - private void populateCapability(Map capabilities, - ComponentInstanceDataDefinition componentInstance, - MapListCapabilityDataDefinition allCalculatedCap) { - capabilities.forEach((key, value) -> { - List listCapabilities = value.getListToscaDataDefinition() - .stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()); - listCapabilities.forEach(cap -> { - cap.setSource(componentInstance.getComponentUid()); - cap.addToPath(componentInstance.getUniqueId()); - cap.setOwnerId(componentInstance.getUniqueId()); - cap.setOwnerName(componentInstance.getName()); - cap.setLeftOccurrences(cap.getMaxOccurrences()); - allCalculatedCap.add(key, cap); - }); - }); - } - - private MapListRequirementDataDefinition prepareCalculatedRequirementForTopologyTemplate( - Map requirements, - ComponentInstanceDataDefinition componentInstance, - MapListRequirementDataDefinition calculatedReqs) { - MapListRequirementDataDefinition allCalculatedReq = - new MapListRequirementDataDefinition(calculatedReqs); - - populateRequirement(requirements, componentInstance, allCalculatedReq); - return allCalculatedReq; - } - private void populateRequirement(Map requirements, - ComponentInstanceDataDefinition componentInstance, - MapListRequirementDataDefinition allCalculatedReq) { - requirements.forEach((key, value) -> { - List listRequirements = value.getListToscaDataDefinition() - .stream().map(RequirementDataDefinition::new).collect(Collectors.toList()); - listRequirements.forEach(req -> { - req.setSource(componentInstance.getComponentUid()); - req.addToPath(componentInstance.getUniqueId()); - req.setOwnerId(componentInstance.getUniqueId()); - req.setOwnerName(componentInstance.getName()); - req.setLeftOccurrences(req.getMaxOccurrences()); - allCalculatedReq.add(key, req); - }); - }); - } - - - - private StorageOperationStatus addCalculatedCapReqFromTopologyTemplate(TopologyTemplate originTopologyTemplate, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) { - Map calculatedCapabilities = originTopologyTemplate.getCalculatedCapabilities(); - - MapListCapabilityDataDefinition allCalculatedCap = new MapListCapabilityDataDefinition(); - if (calculatedCapabilities != null) { - calculatedCapabilities.forEach((key1, value1) -> { - Map mapByType = value1.getMapToscaDataDefinition(); - mapByType.forEach((key, value) -> value.getListToscaDataDefinition().forEach(cap -> { - cap.addToPath(componentInstance.getUniqueId()); - allCalculatedCap.add(key, cap); - })); - }); - } - MapListCapabilityDataDefinition allCaps; - Map capabilities = originTopologyTemplate.getCapabilities(); - if (MapUtils.isNotEmpty(capabilities)) { - allCaps = prepareCalculatedCapabiltyForTopologyTemplate(capabilities, componentInstance, - allCalculatedCap); - } else { - allCaps = new MapListCapabilityDataDefinition(allCalculatedCap); - } - if(!allCaps.isEmpty()) { - StorageOperationStatus calculatedCapabilitiesResult = - addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, - EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, - allCaps, componentInstance.getUniqueId()); - if (calculatedCapabilitiesResult != StorageOperationStatus.OK) { - return calculatedCapabilitiesResult; - } - MapListCapabilityDataDefinition fullCalculatedCap = new MapListCapabilityDataDefinition(); - calculatedCapabilitiesResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, - EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, - fullCalculatedCap, componentInstance.getUniqueId()); - if (calculatedCapabilitiesResult != StorageOperationStatus.OK) { - return calculatedCapabilitiesResult; - } - } - Map calculatedRequirements = - originTopologyTemplate.getCalculatedRequirements(); - MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition(); - if (calculatedRequirements != null) { - calculatedRequirements.forEach((key, value) -> { - Map mapByType = - value.getMapToscaDataDefinition(); - mapByType.forEach((key1, value1) -> value1.getListToscaDataDefinition().forEach(req -> { - req.addToPath(componentInstance.getUniqueId()); - allCalculatedReq.add(key1, req); - })); - }); - - } - - MapListRequirementDataDefinition allReqs; - Map requirements = originTopologyTemplate.getRequirements(); - if (MapUtils.isNotEmpty(requirements)) { - allReqs = prepareCalculatedRequirementForTopologyTemplate(requirements, - componentInstance, allCalculatedReq); - } else - allReqs = new MapListRequirementDataDefinition(allCalculatedReq); - - if(!allReqs.isEmpty()) { - StorageOperationStatus calculatedRequirementResult = - addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, - EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, - allReqs, componentInstance.getUniqueId()); - if (calculatedRequirementResult != StorageOperationStatus.OK) { - return calculatedRequirementResult; - } - MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition(); - calculatedRequirementResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, - EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, - fullCalculatedReq, - componentInstance.getUniqueId()); - if (calculatedRequirementResult != StorageOperationStatus.OK) { - return calculatedRequirementResult; - } - } - Map calculatedCapabilitiesProperties = originTopologyTemplate.getCalculatedCapabilitiesProperties(); - Map updateKeyMap = new HashMap<>(); - - if (calculatedCapabilitiesProperties != null && !calculatedCapabilitiesProperties.isEmpty()) { - for (MapCapabilityProperty map : calculatedCapabilitiesProperties.values()) { - for (Entry entry : map.getMapToscaDataDefinition().entrySet()) { - String newKey = (componentInstance.getUniqueId() + ModelConverter.CAP_PROP_DELIM + entry.getKey()); - updateKeyMap.put(newKey, entry.getValue()); - } - } - } - Map capabilitiesProperties = - originTopologyTemplate.getCapabilitiesProperties(); - Map updateKeyMapCapabilitiesProperties; - if (MapUtils.isNotEmpty(capabilitiesProperties)) { - updateKeyMapCapabilitiesProperties = capabilitiesProperties.entrySet().stream() - .collect(Collectors.toMap(e -> createCapPropertyKey(e.getKey(), - componentInstance.getUniqueId()), Entry::getValue)); - } - else { - updateKeyMapCapabilitiesProperties = new HashMap<>(); - } - updateKeyMap.putAll(updateKeyMapCapabilitiesProperties); - MapCapabilityProperty mapCapabilityProperty = new MapCapabilityProperty(updateKeyMap); - - if(MapUtils.isNotEmpty(capabilitiesProperties) || MapUtils.isNotEmpty(calculatedCapabilitiesProperties )) { - StorageOperationStatus calculatedResult = - addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, - EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, - VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabilityProperty, - componentInstance.getUniqueId()); - if (calculatedResult != StorageOperationStatus.OK) { - return calculatedResult; - } - } - return StorageOperationStatus.OK; - } - private StorageOperationStatus addComponentInstanceToscaDataToNodeTypeContainer(NodeType originNodeType, - ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) { - - StorageOperationStatus status; - - if(MapUtils.isNotEmpty(originNodeType.getProperties())){ - MapPropertiesDataDefinition instProperties = - new MapPropertiesDataDefinition(originNodeType.getProperties()); - status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_PROPERTIES, - VertexTypeEnum.INST_PROPERTIES, instProperties, componentInstance.getUniqueId()); - if (status != StorageOperationStatus.OK) { - return status; - } - } - - if(MapUtils.isNotEmpty(originNodeType.getAttributes())){ - MapPropertiesDataDefinition instAttributes = - new MapPropertiesDataDefinition(originNodeType.getAttributes()); - status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_ATTRIBUTES, - VertexTypeEnum.INST_ATTRIBUTES, instAttributes, componentInstance.getUniqueId()); - if (status != StorageOperationStatus.OK) { - return status; - } - } - - return addCalculatedCapReqFromNodeType(originNodeType, componentInstance, updatedContainerVertex); - } - - public MapArtifactDataDefinition prepareInstDeploymentArtifactPerInstance(Map deploymentArtifacts, String componentInstanceId, User user, String envType) { - if (deploymentArtifacts != null && envType.equals(HEAT_VF_ENV_NAME)) { - Map instDeploymentArtifacts = new HashMap<>(); - - deploymentArtifacts.entrySet().forEach(e -> { - ArtifactDataDefinition artifact = e.getValue(); - String type = artifact.getArtifactType(); - if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { - ArtifactDataDefinition artifactEnv = createArtifactPlaceHolderInfo(artifact, componentInstanceId, user, envType); - instDeploymentArtifacts.put(artifactEnv.getArtifactLabel(), artifactEnv); - } - }); - - deploymentArtifacts.putAll(instDeploymentArtifacts); - - return new MapArtifactDataDefinition(deploymentArtifacts); - - } - return null; - } - - @SuppressWarnings({ "unchecked" }) - private ArtifactDataDefinition createArtifactPlaceHolderInfo(ArtifactDataDefinition artifactHeat, String componentId, User user, String heatEnvType) { - Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); - if (deploymentResourceArtifacts == null) { - log.debug("no deployment artifacts are configured for generated artifacts"); - return null; - } - Map placeHolderData = (Map) deploymentResourceArtifacts.get(heatEnvType); - if (placeHolderData == null) { - log.debug("no env type {} are configured for generated artifacts", heatEnvType); - return null; - } - - String envLabel = (artifactHeat.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase(); - - ArtifactDataDefinition artifactInfo = new ArtifactDataDefinition(); - - String artifactName = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME); - String artifactType = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_TYPE); - String artifactDescription = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_DESCRIPTION); - - artifactInfo.setArtifactDisplayName(artifactName); - artifactInfo.setArtifactLabel(envLabel); - artifactInfo.setArtifactType(artifactType); - artifactInfo.setDescription(artifactDescription); - artifactInfo.setArtifactGroupType(artifactHeat.getArtifactGroupType()); - setDefaultArtifactTimeout(artifactHeat.getArtifactGroupType(), artifactInfo); - artifactInfo.setGeneratedFromId(artifactHeat.getUniqueId()); - // clone heat parameters in case of heat env only not VF heat env - if (heatEnvType.equals(HEAT_ENV_NAME)) { - artifactInfo.setHeatParameters(artifactHeat.getHeatParameters()); - } - setArtifactPlaceholderCommonFields(componentId, user, artifactInfo); - - return artifactInfo; - } - - public void setDefaultArtifactTimeout(ArtifactGroupTypeEnum groupType, ArtifactDataDefinition artifactInfo) { - if (groupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) { - artifactInfo.setTimeout(defaultHeatTimeout); - } else { - artifactInfo.setTimeout(NON_HEAT_TIMEOUT); - } - } - - private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDataDefinition artifactInfo) { - String uniqueId = null; - - if (resourceId != null) { - uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase()); - artifactInfo.setUniqueId(uniqueId); - } - artifactInfo.setUserIdCreator(user.getUserId()); - String fullName = user.getFullName(); - artifactInfo.setUpdaterFullName(fullName); - - long time = System.currentTimeMillis(); - - artifactInfo.setCreatorFullName(fullName); - artifactInfo.setCreationDate(time); - - artifactInfo.setLastUpdateDate(time); - artifactInfo.setUserIdLastUpdater(user.getUserId()); - - artifactInfo.setMandatory(true); - } - - /** - * - * @param originNodeType - * @param componentInstance - * @param updatedContainerVertex - * @return - */ - private StorageOperationStatus addCalculatedCapReqFromNodeType(NodeType originNodeType, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) { - - Map capabilities = originNodeType.getCapabilities(); - MapListCapabilityDataDefinition allCalculatedCap = prepareCalculatedCapabiltyForNodeType(capabilities, componentInstance); - StorageOperationStatus calculatedResult; - if (allCalculatedCap != null) { - calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, componentInstance.getUniqueId()); - - if (calculatedResult != StorageOperationStatus.OK) { - return calculatedResult; - } - } - Map capabiltiesProperties = originNodeType.getCapabilitiesProperties(); - if (capabiltiesProperties != null) { - Map updateKeyMap = capabiltiesProperties.entrySet().stream().collect(Collectors.toMap(e -> createCapPropertyKey(e.getKey(), componentInstance.getUniqueId()), Entry::getValue)); - MapCapabilityProperty mapCapabilityProperty = new MapCapabilityProperty(updateKeyMap); - calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabilityProperty, componentInstance.getUniqueId()); - if (calculatedResult != StorageOperationStatus.OK) { - return calculatedResult; - } - } - - MapListCapabilityDataDefinition fullCalculatedCap = new MapListCapabilityDataDefinition(); - calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, fullCalculatedCap, componentInstance.getUniqueId()); - - if (calculatedResult != StorageOperationStatus.OK) { - return calculatedResult; - } - - Map requirements = originNodeType.getRequirements(); - - MapListRequirementDataDefinition allCalculatedReq = prepareCalculatedRequirementForNodeType(requirements, componentInstance); - - StorageOperationStatus status; - if (allCalculatedReq != null) { - status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, componentInstance.getUniqueId()); - if (status != StorageOperationStatus.OK) { - return status; - } - } - MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition(); - addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, fullCalculatedReq, componentInstance.getUniqueId()); - return StorageOperationStatus.OK; - - } - - public static String createCapPropertyKey(String key, String instanceId) { - StringBuilder sb = new StringBuilder(instanceId); - sb.append(ModelConverter.CAP_PROP_DELIM).append(instanceId).append(ModelConverter.CAP_PROP_DELIM).append(key); - return sb.toString(); - } - - /** - * Prepares a map of capabilities lists Produces a deep copy of the received map of capabilities Sets values to the specific fields according to received component instance - * - * @param capabilities - * @param componentInstance - * @return - */ - public MapListCapabilityDataDefinition prepareCalculatedCapabiltyForNodeType(Map capabilities, ComponentInstanceDataDefinition componentInstance) { - if (capabilities != null) { - MapListCapabilityDataDefinition allCalculatedCap = new MapListCapabilityDataDefinition(); - - populateCapability(capabilities, componentInstance, allCalculatedCap); - return allCalculatedCap; - } - return null; - } - - /** - * Prepares a map of requirements lists Produces a deep copy of the received map of requirements Sets values to the specific fields according to received component instance - * - * @param requirements - * @param componentInstance - * @return - */ - public MapListRequirementDataDefinition prepareCalculatedRequirementForNodeType(Map requirements, ComponentInstanceDataDefinition componentInstance) { - if (requirements != null) { - MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition(); - - populateRequirement(requirements, componentInstance, allCalculatedReq); - return allCalculatedReq; - } - return null; - } - - public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstanceDataDefinition componentInstance, List groups, Map> groupInstancesArtifacts) { - - StorageOperationStatus result = null; - Map groupInstanceToCreate = new HashMap<>(); - if (groupInstancesArtifacts != null && CollectionUtils.isNotEmpty(groups)) { - for (Map.Entry> groupArtifacts : groupInstancesArtifacts.entrySet()) { - Optional groupOptional = groups.stream().filter(g -> g.getUniqueId().equals(groupArtifacts.getKey())).findFirst(); - if (groupOptional.isPresent()) { - GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition((GroupDataDefinition) groupOptional.get(), (ComponentInstanceDataDefinition) componentInstance, null); - groupInstance.setGroupInstanceArtifacts(groupArtifacts.getValue().stream().map(ArtifactDataDefinition::getUniqueId).collect(Collectors.toList())); - groupInstance.setGroupInstanceArtifactsUuid(groupArtifacts.getValue().stream().map(ArtifactDataDefinition::getArtifactUUID).collect(Collectors.toList())); - groupInstanceToCreate.put(groupInstance.getName(), groupInstance); - } - } - } - if (MapUtils.isNotEmpty(groupInstanceToCreate)) { - result = addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, new MapDataDefinition<>(groupInstanceToCreate), componentInstance.getUniqueId()); - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private ComponentInstanceDataDefinition buildComponentInstanceDataDefinition(ComponentInstance resourceInstance, String containerComponentId, String instanceNewName, boolean generateUid, ToscaElement originToscaElement) { - String ciOriginComponentUid = resourceInstance.getComponentUid(); - - if (!ValidationUtils.validateStringNotEmpty(resourceInstance.getCustomizationUUID())) { - resourceInstance.setCustomizationUUID(generateCustomizationUUID()); - } - ComponentInstanceDataDefinition dataDefinition = new ComponentInstanceDataDefinition(resourceInstance); - - Long creationDate = resourceInstance.getCreationTime(); - Long modificationTime; - if (creationDate == null) { - creationDate = System.currentTimeMillis(); - modificationTime = creationDate; - } else { - modificationTime = System.currentTimeMillis(); - } - dataDefinition.setComponentUid(ciOriginComponentUid); - dataDefinition.setCreationTime(creationDate); - dataDefinition.setModificationTime(modificationTime); - if (StringUtils.isNotEmpty(instanceNewName)) { - dataDefinition.setName(instanceNewName); - resourceInstance.setName(instanceNewName); - } - if (StringUtils.isNotEmpty(dataDefinition.getName())) - dataDefinition.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(dataDefinition.getName())); - dataDefinition.setIcon(resourceInstance.getIcon()); - if (generateUid) { - dataDefinition.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(containerComponentId, ciOriginComponentUid, dataDefinition.getNormalizedName())); - resourceInstance.setUniqueId(dataDefinition.getUniqueId()); - } - if (StringUtils.isEmpty(dataDefinition.getComponentVersion()) && originToscaElement != null) - dataDefinition.setComponentVersion((String) originToscaElement.getMetadataValue(JsonPresentationFields.VERSION)); - if (StringUtils.isEmpty(dataDefinition.getComponentName()) && originToscaElement != null) - dataDefinition.setComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.NAME)); - if (originToscaElement != null && dataDefinition.getToscaComponentName() == null) - dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); - if (dataDefinition.getOriginType() == null && originToscaElement != null) { - ResourceTypeEnum resourceType = originToscaElement.getResourceType(); - OriginTypeEnum originType = OriginTypeEnum.findByValue(resourceType.name()); - dataDefinition.setOriginType(originType); - } - if (dataDefinition.getOriginType() == OriginTypeEnum.ServiceProxy) - dataDefinition.setIsProxy(true); - - return dataDefinition; - } - - private Boolean isUniqueInstanceName(TopologyTemplate container, String instanceName) { - Boolean isUniqueName = true; - try { - isUniqueName = !container.getComponentInstances().values().stream().filter(ci -> ci.getName() != null && ci.getName().equals(instanceName)).findAny().isPresent(); - - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during fetching component instance with name {} from component container {}. {} ", instanceName, container.getName(), e.getMessage()); - } - return isUniqueName; - } - - private String buildComponentInstanceName(String instanceSuffixNumber, String instanceName) { - return instanceName + " " + (instanceSuffixNumber == null ? 0 : instanceSuffixNumber); - } - - public Either associateResourceInstances(String componentId, RequirementCapabilityRelDef relation) { - List relations = new ArrayList<>(); - relations.add(relation); - Either, StorageOperationStatus> associateResourceInstances = associateResourceInstances(componentId, relations); - if (associateResourceInstances.isRight()) { - return Either.right(associateResourceInstances.right().value()); - } - return Either.left(associateResourceInstances.left().value().get(0)); - } - - @SuppressWarnings({ "unchecked" }) - public Either, StorageOperationStatus> associateResourceInstances(String componentId, List relations) { - - Either containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (containerVEither.isRight()) { - TitanOperationStatus error = containerVEither.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - } - GraphVertex containerV = containerVEither.left().value(); - Either>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); - if (capResult.isRight()) { - return Either.right(capResult.right().value()); - - } - Map calculatedCapabilty = capResult.left().value().getRight(); - - Either>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); - if (capResult.isRight()) { - return Either.right(capResult.right().value()); - - } - Map fullFilledCapabilty = capFullResult.left().value().getRight(); - - Either>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); - if (reqResult.isRight()) { - return Either.right(reqResult.right().value()); - } - Map calculatedRequirement = reqResult.left().value().getRight(); - - Either>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); - if (reqResult.isRight()) { - return Either.right(reqResult.right().value()); - } - Map fullfilledRequirement = reqFullResult.left().value().getRight(); - - Map jsonComposition = (Map) containerV.getJson(); - CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - - StorageOperationStatus status; - List relationsList = new ArrayList<>(); - for (RequirementCapabilityRelDef relation : relations) { - List relationshipsResult = new ArrayList<>(); - String fromNode = relation.getFromNode(); - String toNode = relation.getToNode(); - List relationships = relation.getRelationships(); - if (relationships == null || relationships.isEmpty()) { - BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement definition sent in order to set the relation between {} to {}", fromNode, toNode); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - - for (CapabilityRequirementRelationship immutablePair : relationships) { - String requirement = immutablePair.getRelation().getRequirement(); - - Either, StorageOperationStatus> associateRes = connectInstancesInContainer(fromNode, toNode, immutablePair.getRelation(), relation.isOriginUI(), calculatedCapabilty, calculatedRequirement, - fullFilledCapabilty, fullfilledRequirement, compositionDataDefinition, containerV.getUniqueId()); - - if (associateRes.isRight()) { - status = associateRes.right().value(); - BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to associate resource instance {} to resource instance {}. status is {}", fromNode, toNode, status); - return Either.right(status); - } - - RelationshipInstDataDefinition relationshipInstData = (RelationshipInstDataDefinition) associateRes.left().value().get(JsonPresentationFields.RELATIONSHIP); - RelationshipImpl relationshipImplResult = new RelationshipImpl(); - relationshipImplResult.setType(relationshipInstData.getType()); - RelationshipInfo requirementAndRelationshipPair = new RelationshipInfo(requirement, relationshipImplResult); - requirementAndRelationshipPair.setCapability(immutablePair.getRelation().getCapability()); - requirementAndRelationshipPair.setRequirement(immutablePair.getRelation().getRequirement()); - requirementAndRelationshipPair.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId()); - requirementAndRelationshipPair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId()); - requirementAndRelationshipPair.setCapabilityUid(immutablePair.getRelation().getCapabilityUid()); - requirementAndRelationshipPair.setRequirementUid(immutablePair.getRelation().getRequirementUid()); - requirementAndRelationshipPair.setId(relationshipInstData.getUniqueId()); - CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); - capReqRel.setRelation(requirementAndRelationshipPair); - capReqRel.setCapability((CapabilityDataDefinition) associateRes.left().value().get(JsonPresentationFields.CAPABILITY)); - capReqRel.setRequirement((RequirementDataDefinition) associateRes.left().value().get(JsonPresentationFields.REQUIREMENT)); - relationshipsResult.add(capReqRel); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "update customization UUID for from CI {} and to CI {}", relation.getFromNode(), relation.getToNode()); - status = updateCustomizationUUID(relation.getFromNode(), compositionDataDefinition); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - status = updateCustomizationUUID(relation.getToNode(), compositionDataDefinition); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - } - RequirementCapabilityRelDef reqCapRelDef = new RequirementCapabilityRelDef(relation); - reqCapRelDef.setRelationships(relationshipsResult); - relationsList.add(reqCapRelDef); - } - // update metadata of container and composition json - status = updateAllAndCalculatedCapReqOnGraph(componentId, containerV, capResult, capFullResult, reqResult, reqFullResult); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - - return Either.left(relationsList); - } - - private StorageOperationStatus updateAllAndCalculatedCapReqOnGraph(String componentId, GraphVertex containerV, Either>, StorageOperationStatus> capResult, - Either>, StorageOperationStatus> capFullResult, Either>, StorageOperationStatus> reqResult, - Either>, StorageOperationStatus> reqFullResult) { - containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - Either updateElement = titanDao.updateVertex(containerV); - if (updateElement.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new relations error {}. ", componentId, updateElement.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()); - } - // update cap/req jsons, fulfilled cap/req jsons!!!!! - Either status; - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update calculated capabilty for container {}", containerV.getUniqueId()); - status = updateOrCopyOnUpdate(capResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); - if (status.isRight()) { - TitanOperationStatus error = status.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update calculated capabilty for container {} error {}", containerV.getUniqueId(), error); - return DaoStatusConverter.convertTitanStatusToStorageStatus(error); - } - - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update calculated requirement for container {}", containerV.getUniqueId()); - status = updateOrCopyOnUpdate(reqResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); - if (status.isRight()) { - TitanOperationStatus error = status.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update calculated requiremnt for container {} error {}", containerV.getUniqueId(), error); - return DaoStatusConverter.convertTitanStatusToStorageStatus(error); - } - - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update fullfilled capabilty for container {}", containerV.getUniqueId()); - status = updateOrCopyOnUpdate(capFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); - if (status.isRight()) { - TitanOperationStatus error = status.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update fullfilled capabilty for container {} error {}", containerV.getUniqueId(), error); - return DaoStatusConverter.convertTitanStatusToStorageStatus(error); - } - - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update fullfilled requirement for container {}", containerV.getUniqueId()); - status = updateOrCopyOnUpdate(reqFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); - if (status.isRight()) { - TitanOperationStatus error = status.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update fullfilled requirement for container {} error {}", containerV.getUniqueId(), error); - return DaoStatusConverter.convertTitanStatusToStorageStatus(error); - } - return StorageOperationStatus.OK; - } - - @SuppressWarnings({ "unchecked" }) - public Either dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { - if (requirementDef.getRelationships() == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No relation pair in request [ {} ]", requirementDef); - return Either.right(StorageOperationStatus.BAD_REQUEST); - } - - String fromResInstanceUid = requirementDef.getFromNode(); - String toResInstanceUid = requirementDef.getToNode(); - - Either containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (containerVEither.isRight()) { - TitanOperationStatus error = containerVEither.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - } - GraphVertex containerV = containerVEither.left().value(); - - // DE191707 - validations - Map jsonComposition = (Map) containerV.getJson(); - CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - Map componentInstances = compositionDataDefinition.getComponentInstances(); - ComponentInstanceDataDefinition ciFrom = componentInstances.get(fromResInstanceUid); - if (ciFrom == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "FROM instance {} isn't under container {}", fromResInstanceUid, componentId); - return Either.right(StorageOperationStatus.NOT_FOUND); - - } - ComponentInstanceDataDefinition ciTo = componentInstances.get(toResInstanceUid); - if (ciFrom == ciTo) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "TO instance {} isn't under container {}", toResInstanceUid, componentId); - return Either.right(StorageOperationStatus.NOT_FOUND); - - } - Map relations = compositionDataDefinition.getRelations(); - - List relationPairList = requirementDef.getRelationships(); - Either>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); - if (capResult.isRight()) { - return Either.right(capResult.right().value()); - } - Map calculatedCapability = capResult.left().value().getRight(); - - Either>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); - if (capResult.isRight()) { - return Either.right(capResult.right().value()); - - } - Map fulfilledCapability = capFullResult.left().value().getRight(); - - Either>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); - if (reqResult.isRight()) { - return Either.right(reqResult.right().value()); - } - Map calculatedRequirement = reqResult.left().value().getRight(); - - Either>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); - if (reqResult.isRight()) { - return Either.right(reqResult.right().value()); - } - Map fulfilledRequirement = reqFullResult.left().value().getRight(); - - for (CapabilityRequirementRelationship relationPair : relationPairList) { - Iterator> iterator = relations.entrySet().iterator(); - boolean isDeleted = false; - while (iterator.hasNext()) { - Entry entryInJson = iterator.next(); - RelationshipInstDataDefinition relationInJson = entryInJson.getValue(); - if (relationInJson.getFromId().equals(fromResInstanceUid) && relationInJson.getToId().equals(toResInstanceUid) && relationInJson.getUniqueId().equals(relationPair.getRelation().getId())) { - if (relationPair.getRelation().equalsTo(relationInJson)) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Remove relation from {} to {} capability {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationInJson.getType(), relationInJson.getCapabilityOwnerId(), - relationInJson.getRequirementOwnerId()); - iterator.remove(); - - // update calculated cap/req - StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapability, fulfilledCapability, toResInstanceUid, relationInJson, relationPair); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fulfilledRequirement, fromResInstanceUid, relationInJson, relationPair); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - isDeleted = true; - } - } - } - if (!isDeleted) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No relation to delete from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationPair.getCapability(), - relationPair.getRelation().getCapabilityOwnerId(), relationPair.getRelation().getRequirementOwnerId()); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - } - StorageOperationStatus status = updateCustomizationUUID(fromResInstanceUid, compositionDataDefinition); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - status = updateCustomizationUUID(toResInstanceUid, compositionDataDefinition); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - - // update jsons - // update metadata of container and composition json - status = updateAllAndCalculatedCapReqOnGraph(componentId, containerV, capResult, capFullResult, reqResult, reqFullResult); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - - return Either.left(requirementDef); - } - - /** - * Retrieves fulfilled requirement according to relation and received predicate - * - * @param componentId - * @param instanceId - * @param foundRelation - * @param predicate - * @return - */ - public Either getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef foundRelation, - BiPredicate predicate) { - - Either result = null; - Either>, StorageOperationStatus> reqFullResult = null; - MapListRequirementDataDefinition reqMapOfLists = null; - Optional foundRequirement; - RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation(); - Either containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (containerVEither.isRight()) { - TitanOperationStatus error = containerVEither.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - } - if (result == null) { - GraphVertex containerV = containerVEither.left().value(); - reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); - if (reqFullResult.isRight()) { - result = Either.right(reqFullResult.right().value()); - } - } - if (result == null) { - Map fulfilledRequirement = reqFullResult.left().value().getRight(); - reqMapOfLists = fulfilledRequirement.get(instanceId); - if (reqMapOfLists == null) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - if (result == null && reqMapOfLists != null) { - for (ListRequirementDataDefinition requirements : reqMapOfLists.getMapToscaDataDefinition().values()) { - foundRequirement = requirements.getListToscaDataDefinition().stream().filter(req -> predicate.test(relationshipInfo, req)).findFirst(); - if (foundRequirement.isPresent()) { - result = Either.left(foundRequirement.get()); - } - } - } - return result; - } - - /** - * Retrieves fulfilled capability according to relation and received predicate - * - * @param componentId - * @param instanceId - * @param foundRelation - * @param predicate - * @return - */ - public Either getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef foundRelation, - BiPredicate predicate) { - - Either result = null; - Either>, StorageOperationStatus> capFullResult = null; - MapListCapabilityDataDefinition capMapOfLists = null; - Optional foundRequirement; - - RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation(); - Either containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (containerVEither.isRight()) { - TitanOperationStatus error = containerVEither.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - } - if (result == null) { - GraphVertex containerV = containerVEither.left().value(); - capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); - if (capFullResult.isRight()) { - result = Either.right(capFullResult.right().value()); - } - } - if (result == null) { - Map fulfilledCapability = capFullResult.left().value().getRight(); - capMapOfLists = fulfilledCapability.get(instanceId); - if (capMapOfLists == null) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - if (result == null && capMapOfLists != null) { - for (ListCapabilityDataDefinition capabilities : capMapOfLists.getMapToscaDataDefinition().values()) { - foundRequirement = capabilities.getListToscaDataDefinition().stream().filter(cap -> predicate.test(relationshipInfo, cap)).findFirst(); - if (foundRequirement.isPresent()) { - result = Either.left(foundRequirement.get()); - } - } - } - return result; - } - - private StorageOperationStatus updateCalculatedRequirementsAfterDeleteRelation(Map calculatedRequirement, Map fullFilledRequirement, String fromResInstanceUid, - RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) { - StorageOperationStatus status; - String hereIsTheKey = null; - MapListRequirementDataDefinition reqByInstance = calculatedRequirement.get(fromResInstanceUid); - if (reqByInstance == null || reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()) == null) { - // move from fulfilled - status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey, relationship); - } else { - hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()); - ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey); - Optional requirementOptional = reqByType.getListToscaDataDefinition().stream() - .filter(req -> req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId().equals(relation.getRequirementId())).findFirst(); - - if (requirementOptional.isPresent()) { - - RequirementDataDefinition requirement = requirementOptional.get(); - String leftOccurrences = requirement.getLeftOccurrences(); - if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - Integer leftIntValue = Integer.parseInt(leftOccurrences); - ++leftIntValue; - requirement.setLeftOccurrences(String.valueOf(leftIntValue)); - } - if (relationship != null) { - relationship.setRequirement(requirement); - } - status = StorageOperationStatus.OK; - } else { - // move from fulfilled - status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey, relationship); - } - } - return status; - } - - private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map calculatedCapability, Map fullFilledCapability, String toResInstanceUid, - RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) { - StorageOperationStatus status; - String hereIsTheKey = null; - MapListCapabilityDataDefinition capByInstance = calculatedCapability.get(toResInstanceUid); - if (capByInstance == null || capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()) == null) { - // move from fulfilled - status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey, relationship); - } else { - hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()); - ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey); - Optional capabilityOptional = capByType.getListToscaDataDefinition().stream().filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId())) - .findFirst(); - - if (capabilityOptional.isPresent()) { - - CapabilityDataDefinition capability = capabilityOptional.get(); - String leftOccurrences = capability.getLeftOccurrences(); - if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { - Integer leftIntValue = Integer.parseInt(leftOccurrences); - ++leftIntValue; - capability.setLeftOccurrences(String.valueOf(leftIntValue)); - } - if (relationship != null) { - relationship.setCapability(capability); - } - status = StorageOperationStatus.OK; - } else { - // move from fulfilled - status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey, relationship); - } - } - return status; - } - - private StorageOperationStatus moveFromFullFilledCapabilty(Map calculatedCapability, Map fullFilledCapability, String toResInstanceUid, - RelationshipInstDataDefinition relation, String hereIsTheKey, CapabilityRequirementRelationship relationship) { - MapListCapabilityDataDefinition capByInstance = fullFilledCapability.get(toResInstanceUid); - if (capByInstance == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability in fulfilled list for instance {} ", toResInstanceUid); - return StorageOperationStatus.GENERAL_ERROR; - } - if (null == hereIsTheKey) - hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()); - if (null == hereIsTheKey) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability with id {} in fulfilled list for instance {} ", relation.getCapabilityId(), toResInstanceUid); - return StorageOperationStatus.GENERAL_ERROR; - } - ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey); - Iterator iterator = capByType.getListToscaDataDefinition().iterator(); - boolean found = false; - while (iterator.hasNext()) { - CapabilityDataDefinition cap = iterator.next(); - if (cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId())) { - found = true; - iterator.remove(); - // return to calculated list - String leftOccurrences = cap.getLeftOccurrences(); - Integer leftIntValue = Integer.parseInt(leftOccurrences); - ++leftIntValue; - cap.setLeftOccurrences(String.valueOf(leftIntValue)); - - MapListCapabilityDataDefinition mapListCapaDataDef = calculatedCapability.get(toResInstanceUid); - if (mapListCapaDataDef == null) { - mapListCapaDataDef = new MapListCapabilityDataDefinition(); - } - ListCapabilityDataDefinition findByKey = mapListCapaDataDef.findByKey(hereIsTheKey); - if (findByKey == null) { - findByKey = new ListCapabilityDataDefinition(); - mapListCapaDataDef.put(hereIsTheKey, findByKey); - } - findByKey.add(cap); - if (relationship != null) - relationship.setCapability(cap); - break; - } - } - if (!found) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getCapabilityOwnerId(), toResInstanceUid); - return StorageOperationStatus.GENERAL_ERROR; - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus moveFromFullFilledRequirement(Map calculatedRequirement, Map fullFilledRequirement, String fromResInstanceUid, - RelationshipInstDataDefinition relation, String hereIsTheKey, CapabilityRequirementRelationship relationship) { - MapListRequirementDataDefinition reqByInstance = fullFilledRequirement.get(fromResInstanceUid); - if (reqByInstance == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement in fullfilled list for instance {} ", fromResInstanceUid); - return StorageOperationStatus.GENERAL_ERROR; - } - if (null == hereIsTheKey) - hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()); - if (null == hereIsTheKey) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement with id {} in fulfilled list for instance {} ", relation.getRequirementId(), fromResInstanceUid); - return StorageOperationStatus.GENERAL_ERROR; - } - ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey); - Iterator iterator = reqByType.getListToscaDataDefinition().iterator(); - boolean found = false; - while (iterator.hasNext()) { - RequirementDataDefinition req = iterator.next(); - if (req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId().equals(relation.getRequirementId())) { - found = true; - iterator.remove(); - // return to calculated list - String leftOccurrences = req.getLeftOccurrences(); - Integer leftIntValue = Integer.parseInt(leftOccurrences); - ++leftIntValue; - req.setLeftOccurrences(String.valueOf(leftIntValue)); - - MapListRequirementDataDefinition mapListReqDataDef = calculatedRequirement.get(fromResInstanceUid); - if (mapListReqDataDef == null) { - mapListReqDataDef = new MapListRequirementDataDefinition(); - } - ListRequirementDataDefinition findByKey = mapListReqDataDef.findByKey(hereIsTheKey); - if (findByKey == null) { - findByKey = new ListRequirementDataDefinition(); - mapListReqDataDef.put(hereIsTheKey, findByKey); - } - findByKey.add(req); - if (relationship != null) - relationship.setRequirement(req); - break; - } - } - if (!found) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getRequirementOwnerId(), fromResInstanceUid); - return StorageOperationStatus.GENERAL_ERROR; - } - return StorageOperationStatus.OK; - - } - - public StorageOperationStatus updateCustomizationUUID(String componentInstanceId, CompositionDataDefinition compositionDataDefinition) { - ComponentInstanceDataDefinition componentInstance = compositionDataDefinition.getComponentInstances().get(componentInstanceId); - - if (componentInstance == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component instance by id {} from map of instances ", componentInstanceId); - return StorageOperationStatus.NOT_FOUND; - } - UUID uuid = UUID.randomUUID(); - componentInstance.setCustomizationUUID(uuid.toString()); - - return StorageOperationStatus.OK; - } - - public Either, StorageOperationStatus> connectInstancesInContainer(String fromResInstanceUid, String toResInstanceUid, RelationshipInfo relationPair, boolean originUI, - Map calculatedCapabilty, Map calculatedRequirement, Map fullfilledCapabilty, - Map fullfilledRequirement, CompositionDataDefinition compositionDataDefinition, String containerId) { - String requirement = relationPair.getRequirement(); - Map componentInstances = compositionDataDefinition.getComponentInstances(); - - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to associate resource instance {} to resource instance {} under component {}. Requirement is {}.", fromResInstanceUid, toResInstanceUid, containerId, requirement); - - ComponentInstanceDataDefinition fromResourceInstData = componentInstances.get(fromResInstanceUid); - if (fromResourceInstData == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find from resource instance {}.", fromResInstanceUid); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - ComponentInstanceDataDefinition toResourceInstData = componentInstances.get(toResInstanceUid); - if (toResourceInstData == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find to resource instance {}.", toResInstanceUid); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - - Either, StorageOperationStatus> reqVsCap = connectRequirementVsCapability(fromResourceInstData, toResourceInstData, relationPair, originUI, calculatedCapabilty, calculatedRequirement, fullfilledCapabilty, - fullfilledRequirement, containerId); - if (reqVsCap.isRight()) { - StorageOperationStatus status = reqVsCap.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to connect requirement {} between resource instance {} to resource instance {}. status is {}", requirement, fromResInstanceUid, toResInstanceUid, status); - return Either.right(status); - } - Map relationship = reqVsCap.left().value(); - - // add to json new relations - compositionDataDefinition.addRelation(((RelationshipInstDataDefinition) relationship.get(JsonPresentationFields.RELATIONSHIP)).getUniqueId(), (RelationshipInstDataDefinition) relationship.get(JsonPresentationFields.RELATIONSHIP)); - - return Either.left(relationship); - } - - private Either>, StorageOperationStatus> fetchContainerCalculatedCapability(GraphVertex containerV, EdgeLabelEnum capLabel) { - - Either>, TitanOperationStatus> calculatedCapabiltyEither = getDataAndVertexFromGraph(containerV, capLabel); - if (calculatedCapabiltyEither.isRight()) { - TitanOperationStatus error = calculatedCapabiltyEither.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilties for container {}.", containerV.getUniqueId(), error); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - } - Pair> calculatedCapabilty = calculatedCapabiltyEither.left().value(); - return Either.left(calculatedCapabilty); - } - - private Either>, StorageOperationStatus> fetchContainerCalculatedRequirement(GraphVertex containerV, EdgeLabelEnum reqLabel) { - Either>, TitanOperationStatus> calculatedRequirementEither = getDataAndVertexFromGraph(containerV, reqLabel); - if (calculatedRequirementEither.isRight()) { - TitanOperationStatus error = calculatedRequirementEither.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for container {}.", containerV.getUniqueId(), error); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - } - Pair> calculatedRequirement = calculatedRequirementEither.left().value(); - return Either.left(calculatedRequirement); - } - - @SuppressWarnings("unchecked") - private Either, StorageOperationStatus> connectRequirementVsCapability(ComponentInstanceDataDefinition fromResInstance, ComponentInstanceDataDefinition toResInstance, - RelationshipInfo relationPair, boolean originUI, Map calculatedCapabilty, Map calculatedRequirement, - Map fullfilledCapabilty, Map fullfilledRequirement, String containerId) { - String type = relationPair.getRelationship().getType(); - // capability - - String toInstId = toResInstance.getUniqueId(); - MapListCapabilityDataDefinition mapListCapabilityDataDefinition = calculatedCapabilty.get(toInstId); - Map capReqRelationship = new EnumMap<>(JsonPresentationFields.class); - - if (mapListCapabilityDataDefinition == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for instance {} in container {}.", toInstId, containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - ListCapabilityDataDefinition listCapabilityDataDefinition = mapListCapabilityDataDefinition.getMapToscaDataDefinition().get(type); - if (listCapabilityDataDefinition == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for type {} for instance {} in container {}.", type, toInstId, containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - CapabilityDataDefinition capabilityForRelation = null; - Iterator iteratorCap = listCapabilityDataDefinition.getListToscaDataDefinition().iterator(); - while (iteratorCap.hasNext()) { - CapabilityDataDefinition cap = iteratorCap.next(); - if (cap.getUniqueId().equals(relationPair.getCapabilityUid()) && cap.getOwnerId().equals(relationPair.getCapabilityOwnerId())) { - capabilityForRelation = cap; - capReqRelationship.put(JsonPresentationFields.CAPABILITY, (T) capabilityForRelation); - String leftOccurrences = cap.getLeftOccurrences(); - if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { - Integer leftIntValue = Integer.parseInt(leftOccurrences); - if (leftIntValue > 0) { - --leftIntValue; - capabilityForRelation.setLeftOccurrences(String.valueOf(leftIntValue)); - if (leftIntValue == 0) { - // remove from calculated - iteratorCap.remove(); - // move to fulfilled - MapListCapabilityDataDefinition mapListCapabiltyFullFilledInst = fullfilledCapabilty.get(toInstId); - if (mapListCapabiltyFullFilledInst == null) { - mapListCapabiltyFullFilledInst = new MapListCapabilityDataDefinition(); - fullfilledCapabilty.put(toInstId, mapListCapabiltyFullFilledInst); - } - - ListCapabilityDataDefinition listCapabilityFull = mapListCapabiltyFullFilledInst.findByKey(type); - if (listCapabilityFull == null) { - listCapabilityFull = new ListCapabilityDataDefinition(); - mapListCapabiltyFullFilledInst.put(type, listCapabilityFull); - } - listCapabilityFull.add(capabilityForRelation); - } - break; - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.", capabilityForRelation.getType(), toInstId, containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - } - } - } - if (capabilityForRelation == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch capabilty for type {} for instance {} in container {}.", type, toInstId, containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - - // requirements - String fromInstId = fromResInstance.getUniqueId(); - MapListRequirementDataDefinition mapListRequirementDataDefinition = calculatedRequirement.get(fromInstId); - if (mapListRequirementDataDefinition == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for instance {} in container {}.", fromInstId, containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - ListRequirementDataDefinition listRequirementDataDefinition = mapListRequirementDataDefinition.getMapToscaDataDefinition().get(type); - if (listRequirementDataDefinition == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for type {} for instance {} in container {}.", type, fromInstId, containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - - RequirementDataDefinition requirementForRelation = null; - Iterator iteratorReq = listRequirementDataDefinition.getListToscaDataDefinition().iterator(); - while (iteratorReq.hasNext()) { - RequirementDataDefinition req = iteratorReq.next(); - if (req.getUniqueId().equals(relationPair.getRequirementUid()) && req.getOwnerId().equals(relationPair.getRequirementOwnerId())) { - requirementForRelation = req; - capReqRelationship.put(JsonPresentationFields.REQUIREMENT, (T) requirementForRelation); - String leftOccurrences = req.getLeftOccurrences(); - if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - Integer leftIntValue = Integer.parseInt(leftOccurrences); - if (leftIntValue > 0) { - --leftIntValue; - req.setLeftOccurrences(String.valueOf(leftIntValue)); - if (leftIntValue == 0) { - // remove from calculated - iteratorReq.remove(); - // move to fulfilled - MapListRequirementDataDefinition mapListRequirementFullFilledInst = fullfilledRequirement.get(fromInstId); - if (mapListRequirementFullFilledInst == null) { - mapListRequirementFullFilledInst = new MapListRequirementDataDefinition(); - fullfilledRequirement.put(fromInstId, mapListRequirementFullFilledInst); - } - - ListRequirementDataDefinition listRequirementFull = mapListRequirementFullFilledInst.findByKey(type); - if (listRequirementFull == null) { - listRequirementFull = new ListRequirementDataDefinition(); - mapListRequirementFullFilledInst.put(type, listRequirementFull); - } - listRequirementFull.add(requirementForRelation); - } - break; - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No left occurrences requirement {} from {} to {} in container {}.", requirementForRelation.getCapability(), fromInstId, toInstId, containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - } - } - } - if (requirementForRelation == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch requirement for type {} for instance {} in container {}.", type, toInstId, containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - if (!capabilityForRelation.getType().equals(requirementForRelation.getCapability())) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No macth for capability from type {} and requirement {} from {} to {} in container {}.", capabilityForRelation.getType(), requirementForRelation.getCapability(), fromInstId, toInstId, - containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - - RelationshipInstDataDefinition relationshipTypeData = buildRelationshipInstData(fromInstId, toInstId, relationPair, originUI); - if (requirementForRelation.getRelationship() != null) - relationshipTypeData.setType(requirementForRelation.getRelationship()); - capReqRelationship.put(JsonPresentationFields.RELATIONSHIP, (T) relationshipTypeData); - return Either.left(capReqRelationship); - } - - private RelationshipInstDataDefinition buildRelationshipInstData(String fromResInstanceUid, String toInstId, RelationshipInfo relationPair, boolean originUI) { - - RelationshipInstDataDefinition relationshipInstData = new RelationshipInstDataDefinition(); - relationshipInstData.setUniqueId(UniqueIdBuilder.buildRelationsipInstInstanceUid(fromResInstanceUid, toInstId)); - - relationshipInstData.setType(relationPair.getRelationship().getType()); - Long creationDate = System.currentTimeMillis(); - relationshipInstData.setCreationTime(creationDate); - relationshipInstData.setModificationTime(creationDate); - relationshipInstData.setCapabilityOwnerId(relationPair.getCapabilityOwnerId()); - relationshipInstData.setRequirementOwnerId(relationPair.getRequirementOwnerId()); - relationshipInstData.setCapabilityId(relationPair.getCapabilityUid()); - relationshipInstData.setRequirementId(relationPair.getRequirementUid()); - relationshipInstData.setFromId(fromResInstanceUid); - relationshipInstData.setToId(toInstId); - relationshipInstData.setRequirement(relationPair.getRequirement()); - relationshipInstData.setCapability(relationPair.getCapability()); - relationshipInstData.setOriginUI(originUI); - - return relationshipInstData; - } - - public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map componentInstanceTMap, GraphVertex containerVertex, boolean allowDeleted) { - - StorageOperationStatus result = null; - String containerId = containerComponent.getUniqueId(); - Map instancesJsonData = null; - Either updateElement = null; - if (!validateInstanceNames(componentInstanceTMap)) { - result = StorageOperationStatus.INCONSISTENCY; - } - if (result == null && !validateInstanceNames(componentInstanceTMap)) { - result = StorageOperationStatus.INCONSISTENCY; - } - if (result == null && !allowDeleted && !validateDeletedResources(componentInstanceTMap)) { - result = StorageOperationStatus.INCONSISTENCY; - } - if (result == null) { - instancesJsonData = convertToComponentInstanceDataDefinition(componentInstanceTMap, containerId); - } - if (result == null && MapUtils.isNotEmpty(instancesJsonData)) { - containerVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - Map compositions = new HashMap<>(); - CompositionDataDefinition composition = new CompositionDataDefinition(); - composition.setComponentInstances(instancesJsonData); - compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), composition); - containerVertex.setJson(compositions); - updateElement = titanDao.updateVertex(containerVertex); - if (updateElement.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instances. ", containerComponent.getName()); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()); - } - } - if (result == null && updateElement != null) { - GraphVertex vertexC = updateElement.left().value(); - instancesJsonData.entrySet().forEach(i ->createInstanceEdge(vertexC, i.getValue())); - result = StorageOperationStatus.OK; - } - return result; - } - - private Map convertToComponentInstanceDataDefinition(Map componentInstanceTMap, String containerId) { - - Map instances = new HashMap<>(); - for (Entry entry : componentInstanceTMap.entrySet()) { - ComponentInstanceDataDefinition instance = buildComponentInstanceDataDefinition(entry.getKey(), containerId, null, true, ModelConverter.convertToToscaElement(entry.getValue())); - instances.put(instance.getUniqueId(), instance); - } - return instances; - } - - private boolean validateDeletedResources(Map resourcesInstancesMap) { - boolean result = true; - for (Component component : resourcesInstancesMap.values()) { - if (component.getIsDeleted() != null && component.getIsDeleted()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance. ", component.getName()); - result = false; - break; - } - } - return result; - } - - private boolean validateInstanceNames(Map resourcesInstancesMap) { - boolean result = true; - Set names = new HashSet<>(); - for (ComponentInstance instance : resourcesInstancesMap.keySet()) { - if (StringUtils.isEmpty(instance.getName())) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component instance {} name is empty. Cannot add component instance. ", instance.getUniqueId()); - result = false; - break; - } else if (names.contains(instance.getName())) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component instance with the name {} already exsists. Cannot add component instance. ", instance.getName()); - result = false; - break; - } else { - names.add(instance.getName()); - } - } - return result; - } - - public StorageOperationStatus addDeploymentArtifactsToInstance(String toscaElementId, String instanceId, Map instDeplArtifacts) { - return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS); - } - - public StorageOperationStatus addInformationalArtifactsToInstance(String toscaElementId, String instanceId, Map instDeplArtifacts) { - return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INSTANCE_ARTIFACTS, VertexTypeEnum.INSTANCE_ARTIFACTS); - } - - public StorageOperationStatus addArtifactsToInstance(String toscaElementId, String instanceId, Map instDeplArtifacts, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexType) { - Either metadataVertex = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - MapArtifactDataDefinition instArtifacts = new MapArtifactDataDefinition(instDeplArtifacts); - return addToscaDataDeepElementsBlockToToscaElement(metadataVertex.left().value(), edgeLabel, vertexType, instArtifacts, instanceId); - - } - - @SuppressWarnings({ "unchecked" }) - public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) { - Either metadataVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - GraphVertex metaVertex = metadataVertex.left().value(); - Map json = (Map) metaVertex.getJson(); - CompositionDataDefinition compositionDataDefinition = json.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - StorageOperationStatus status = updateCustomizationUUID(instanceId, compositionDataDefinition); - if (status != StorageOperationStatus.OK) { - log.debug("Failed to update customization UUID for instance {} in component {} error {}", instanceId, componentId, status); - return status; - } - Either updateVertex = titanDao.updateVertex(metaVertex); - if (updateVertex.isRight()) { - log.debug("Failed to update vertex of component {} error {}", componentId, updateVertex.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertex.right().value()); - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List groupInstances) { - if (groupInstances != null) { - Either, TitanOperationStatus> dataFromGraph = getDataFromGraph(componentId, EdgeLabelEnum.INST_GROUPS); - if (dataFromGraph.isRight()) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(dataFromGraph.right().value()); - } - MapGroupsDataDefinition grInstPerInstance = dataFromGraph.left().value().get(instanceId); - if (grInstPerInstance == null) { - log.debug("No instance groups for instance {} in component {}", instanceId, componentId); - return StorageOperationStatus.NOT_FOUND; - } - for (String instGroupForUpdate : groupInstances) { - GroupInstanceDataDefinition groupInst = grInstPerInstance.findByKey(instGroupForUpdate); - if (groupInst == null) { - log.debug("No group instance {} in group list for instance {} in component {}", instGroupForUpdate, instanceId, componentId); - continue; - } - UUID uuid = UUID.randomUUID(); - groupInst.setCustomizationUUID(uuid.toString()); - } - - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List groupInstances) { - - return addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, - new MapDataDefinition<>(groupInstances.stream().collect(Collectors.toMap(GroupInstanceDataDefinition::getName, gi -> gi))), componentInstance.getUniqueId()); - } - - public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map deploymentArtifacts) { - - return addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, new MapDataDefinition<>(deploymentArtifacts), - componentInstance.getUniqueId()); - } - - public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { - - List pathKeys = new ArrayList<>(); - pathKeys.add(componentInstanceId); - return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME); - } - - public StorageOperationStatus updateComponentInstanceCapabilityProperty(Component containerComponent, String componentInstanceId, String capabilityUniqueId, ComponentInstanceProperty property) { - List pathKeys = new ArrayList<>(); - pathKeys.add(componentInstanceId); - pathKeys.add(capabilityUniqueId); - return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME); - } - - public StorageOperationStatus overrideComponentCapabilitiesProperties(Component containerComponent, Map capabilityPropertyMap) { - return overrideToscaDataOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilityPropertyMap); - } - - public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { - List pathKeys = new ArrayList<>(); - pathKeys.add(componentInstanceId); - return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME); - } - - public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List properties) { - List pathKeys = new ArrayList<>(); - pathKeys.add(componentInstanceId); - return updateToscaDataDeepElementsOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, properties, pathKeys, JsonPresentationFields.NAME); - } - - public StorageOperationStatus updateComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property){ - List pathKeys = new ArrayList<>(); - pathKeys.add(componentInstanceId); - return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, property, pathKeys, JsonPresentationFields.NAME); - } - - public StorageOperationStatus addComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property){ - List pathKeys = new ArrayList<>(); - pathKeys.add(componentInstanceId); - return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, property, pathKeys, JsonPresentationFields.NAME); - } - - public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { - - List pathKeys = new ArrayList<>(); - pathKeys.add(componentInstanceId); - return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, property, pathKeys, JsonPresentationFields.NAME); - } - - public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List properties) { - List pathKeys = new ArrayList<>(); - pathKeys.add(componentInstanceId); - return updateToscaDataDeepElementsOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, properties, pathKeys, JsonPresentationFields.NAME); - } - - public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { - List pathKeys = new ArrayList<>(); - pathKeys.add(componentInstanceId); - return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, property, pathKeys, JsonPresentationFields.NAME); - } - - public StorageOperationStatus createInstanceEdge(GraphVertex metadataVertex, ComponentInstanceDataDefinition componentInstance) { - String instUniqueId = componentInstance.getUniqueId(); - - // create edge between container and origin ( in case of proxy this edge will be to ProxyService node type) - StorageOperationStatus result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.INSTANCE_OF, componentInstance.getComponentUid(), instUniqueId).either(v -> StorageOperationStatus.OK, - DaoStatusConverter::convertTitanStatusToStorageStatus); - - if (result == StorageOperationStatus.OK && componentInstance.getIsProxy()) { - // create edge between container and service origin - result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.PROXY_OF, componentInstance.getSourceModelUid(), instUniqueId) - .either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertTitanStatusToStorageStatus); - } - return result; - } - - public StorageOperationStatus createAllottedOfEdge(String componentId, String instanceId, String serviceUUID) { - Either vertexById = titanDao.getVertexById(componentId); - if ( vertexById.isRight() ){ - log.debug("Failed to fetch component metadata vertex for id {} error {}", componentId, vertexById.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(vertexById.right().value()); - } - GraphVertex metadataVertex = vertexById.left().value(); - - EnumMap props = new EnumMap<>(GraphPropertyEnum.class); - props.put(GraphPropertyEnum.UUID, serviceUUID); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - EnumMap hasNot = new EnumMap<>(GraphPropertyEnum.class); - hasNot.put(GraphPropertyEnum.IS_DELETED, true); - - Either, TitanOperationStatus> byCriteria = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props,hasNot, JsonParseFlagEnum.ParseMetadata ); - if ( byCriteria.isRight() ){ - log.debug("Failed to fetch vertex by criteria {} error {}", props, byCriteria.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value()); - } - List vertecies = byCriteria.left().value(); - StorageOperationStatus result = StorageOperationStatus.OK; - if ( vertecies != null ){ - GraphVertex serviceVertex = vertecies.get(0); - //remove previous edges - - log.debug("Try to create or update edge between resource {} and service {} ", metadataVertex, serviceVertex.getUniqueId()); - // create edge between container and service reference - result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.ALLOTTED_OF, serviceVertex.getUniqueId(), instanceId).either(v -> StorageOperationStatus.OK, - DaoStatusConverter::convertTitanStatusToStorageStatus); - } - return result; - } - - - public StorageOperationStatus removeInstanceEdge(GraphVertex metadataVertex, ComponentInstanceDataDefinition componentInstance) { - String instUniqueId = componentInstance.getUniqueId(); - - // create edge between container and origin ( in case of proxy this edge will be to ProxyService node type) - StorageOperationStatus result = removeOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.INSTANCE_OF, componentInstance.getComponentUid(), instUniqueId) - .either(v -> StorageOperationStatus.OK, - DaoStatusConverter::convertTitanStatusToStorageStatus); - - if (componentInstance.getIsProxy()) { - // create edge between container and service origin - result = removeOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.PROXY_OF, componentInstance.getSourceModelUid(), instUniqueId) - .either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertTitanStatusToStorageStatus); - } - return result; - } - - private Either createOrUpdateInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, String instUniqueId) { - Map properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.UNIQUE_ID, componentUid); - - return titanDao.getEdgeByChildrenVertexProperties(metadataVertex, edgeLabel, properties) - .left() - .bind(v -> addInstanceToPropertyOnEdge(instUniqueId, v, metadataVertex)) - .right() - .bind(s -> createInstanceEdge(metadataVertex, edgeLabel, componentUid, instUniqueId, s)); - } - - private Either removeOrUpdateInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, String instUniqueId) { - Map properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.UNIQUE_ID, componentUid); - - return titanDao.getEdgeByChildrenVertexProperties(metadataVertex, edgeLabel, properties).left().bind(v -> removeInstanceFromPropertyOnEdge(instUniqueId, v, metadataVertex)).right() - .map(err -> removeInstanceEdgeLogError(metadataVertex, edgeLabel, componentUid, err)); - } - - private Either addInstanceToPropertyOnEdge(String instUniqueId, Edge edge, GraphVertex metadataVertex) { - // edge exist need to add instance id to list on edge's property - List property = (List) titanDao.getProperty(edge, EdgePropertyEnum.INSTANCES); - if (property == null) { - property = new ArrayList<>(); - } - Optional findFirst = property.stream().filter(a -> a.equals(instUniqueId)).findFirst(); - if (!findFirst.isPresent()) { - property.add(instUniqueId); - } - try { - String jsonArr = JsonParserUtils.toJson(property); - log.debug("Update INSTANCES edge property with value {} ", jsonArr ); - - edge.property(EdgePropertyEnum.INSTANCES.getProperty(), jsonArr); - } catch (IOException e) { - log.debug("Failed to convert INSTANCES edge property to json for container {}", metadataVertex.getUniqueId(), e ); - return Either.right(TitanOperationStatus.GENERAL_ERROR); - } - return Either.left(metadataVertex); - } - - private Either removeInstanceFromPropertyOnEdge(String instUniqueId, Edge edge, GraphVertex metadataVertex) { - // edge exist need to add instance id to list on edge's property - List property = (List) titanDao.getProperty(edge, EdgePropertyEnum.INSTANCES); - if (property == null) { - property = new ArrayList<>(); - } - Optional findFirst = property.stream().filter(a -> a.equals(instUniqueId)).findFirst(); - if (findFirst.isPresent()) { - property.remove(instUniqueId); - } - if (property.isEmpty()) { - // For last instance need to remove edge - edge.remove(); - } else { - try { - String jsonArr = JsonParserUtils.toJson(property); - edge.property(EdgePropertyEnum.INSTANCES.getProperty(), jsonArr); - } catch (IOException e) { - log.debug("Failed to convert INSTANCES edge property to json for container {}", metadataVertex.getUniqueId(), e ); - return Either.right(TitanOperationStatus.GENERAL_ERROR); - } - } - return Either.left(metadataVertex); - } - - private Either createInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, String instUniqueId, TitanOperationStatus retrieveEdgeStatus) { - if (retrieveEdgeStatus == TitanOperationStatus.NOT_FOUND) { - // create new edge - Either vertexById = titanDao.getVertexById(componentUid); - if (vertexById.isRight()) { - return vertexById; - } - GraphVertex originVertex = vertexById.left().value(); - Map edgeProps = new EnumMap<>(EdgePropertyEnum.class); - List instList = new ArrayList<>(); - instList.add(instUniqueId); - edgeProps.put(EdgePropertyEnum.INSTANCES, instList); - - log.debug("Create new edge {} between {} and {} and properties {} ", edgeLabel, metadataVertex.getUniqueId(), originVertex.getUniqueId(), edgeProps); - TitanOperationStatus edgeResult = titanDao.createEdge(metadataVertex, originVertex, edgeLabel, edgeProps); - return edgeResult == TitanOperationStatus.OK ? Either.left(metadataVertex) : Either.right(edgeResult); - } - // error - log.debug("Failed to fetch edge with label {} and to vertex with id {} error {} ", edgeLabel, componentUid, retrieveEdgeStatus); - return Either.right(retrieveEdgeStatus); - } - - private TitanOperationStatus removeInstanceEdgeLogError(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, TitanOperationStatus retrieveEdgeStatus) { - if (retrieveEdgeStatus == TitanOperationStatus.NOT_FOUND) { - log.debug("No edge {} to remove between container {} and origin {}", edgeLabel, metadataVertex.getUniqueId(), componentUid); - } else { - // error - log.debug("Failed to fetch edge with label {} and to vertex with id {} error {} ", edgeLabel, componentUid, retrieveEdgeStatus); - } - return retrieveEdgeStatus; - } - - public void removeAllAllotedEdges(String uniqueId) { - Either vertexById = titanDao.getVertexById(uniqueId); - if (vertexById.isLeft()) { - GraphVertex originVertex = vertexById.left().value(); - TitanVertex vertex = originVertex.getVertex(); - Iterator edges = vertex.edges(Direction.OUT, EdgeLabelEnum.ALLOTTED_OF.name()); - while ( edges != null && edges.hasNext() ){ - Edge edge = edges.next(); - edge.remove(); - } - } - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java deleted file mode 100644 index 967fc16c49..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java +++ /dev/null @@ -1,962 +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.jsontitan.operations; - -import fj.data.Either; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.*; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DerivedNodeTypeResolver; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.springframework.beans.factory.annotation.Qualifier; - -import java.util.*; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -@org.springframework.stereotype.Component("node-type-operation") -public class NodeTypeOperation extends ToscaElementOperation { - public final static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1"); - public final static Pattern uuidNormativeNewVersion = Pattern.compile("^\\d{1,}.0"); - private static final Logger log = Logger.getLogger(NodeTypeOperation.class); - private DerivedNodeTypeResolver derivedResourceResolver; - - - public NodeTypeOperation(@Qualifier("derived-resource-resolver") DerivedNodeTypeResolver derivedNodeTypeResolver) { - this.derivedResourceResolver = derivedNodeTypeResolver; - } - - public Either createNodeType(NodeType nodeType) { - - Either result = null; - - nodeType.generateUUID(); - - //Set missing props such as names, default lifecycle state, dates etc... - nodeType = getResourceMetaDataFromResource(nodeType); - - //Set unique ID - String resourceUniqueId = nodeType.getUniqueId(); - if (resourceUniqueId == null) { - resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId(); - nodeType.setUniqueId(resourceUniqueId); - } - - // get derived from resources - List derivedResources = null; - Either, StorageOperationStatus> derivedResourcesResult = findDerivedResources(nodeType); - if (derivedResourcesResult.isRight()) { - result = Either.right(derivedResourcesResult.right().value()); - return result; - } else { - derivedResources = derivedResourcesResult.left().value(); - } - - //Create Vertext Object and fill according to given NodeType - GraphVertex nodeTypeVertex = new GraphVertex(VertexTypeEnum.NODE_TYPE); - fillToscaElementVertexData(nodeTypeVertex, nodeType, JsonParseFlagEnum.ParseAll); - - //Create Node Type in Graph - Either createdVertex = titanDao.createVertex(nodeTypeVertex); - if (createdVertex.isRight()) { - TitanOperationStatus status = createdVertex.right().value(); - log.error("Error returned after creating resource data node {}. status returned is ", nodeTypeVertex, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - nodeTypeVertex = createdVertex.left().value(); - - StorageOperationStatus assosiateCommon = assosiateCommonForToscaElement(nodeTypeVertex, nodeType, derivedResources); - if (assosiateCommon != StorageOperationStatus.OK) { - result = Either.right(assosiateCommon); - return result; - } - - StorageOperationStatus associateDerived = assosiateToDerived(nodeTypeVertex, derivedResources); - if (associateDerived != StorageOperationStatus.OK) { - result = Either.right(associateDerived); - return result; - } - StorageOperationStatus associateCategory = assosiateResourceMetadataToCategory(nodeTypeVertex, nodeType); - if (associateCategory != StorageOperationStatus.OK) { - result = Either.right(associateCategory); - return result; - } - - StorageOperationStatus associateAttributes = associateAttributesToResource(nodeTypeVertex, nodeType, derivedResources); - if (associateAttributes != StorageOperationStatus.OK) { - result = Either.right(associateAttributes); - return result; - } - - StorageOperationStatus associateRequirements = associateRequirementsToResource(nodeTypeVertex, nodeType, derivedResources); - if (associateRequirements != StorageOperationStatus.OK) { - result = Either.right(associateRequirements); - return result; - } - - StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(nodeTypeVertex, nodeType, derivedResources); - if (associateCapabilities != StorageOperationStatus.OK) { - result = Either.right(associateCapabilities); - return result; - } - StorageOperationStatus associateCapabilitiesProps = associateCapabilitiesPropertiesToResource(nodeTypeVertex, nodeType, derivedResources); - if (associateCapabilitiesProps != StorageOperationStatus.OK) { - result = Either.right(associateCapabilitiesProps); - return result; - } - - StorageOperationStatus associateInterfaces = associateInterfacesToResource(nodeTypeVertex, nodeType, derivedResources); - if (associateInterfaces != StorageOperationStatus.OK) { - result = Either.right(associateInterfaces); - return result; - } - - StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(nodeTypeVertex, nodeType, derivedResources); - if (addAdditionalInformation != StorageOperationStatus.OK) { - result = Either.right(addAdditionalInformation); - return result; - } - result = Either.left(nodeType); - return result; - - } - - private StorageOperationStatus associateInterfacesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { - // Note : currently only one derived supported!!!! - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.INTERFACE_ARTIFACTS); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map interfacArtsAll = dataFromDerived.left().value(); - - Map interfacArts = nodeType.getInterfaceArtifacts(); - if (interfacArts != null) { - interfacArtsAll.putAll(interfacArts); - } - if (!interfacArtsAll.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INTERFACE_ARTIFACTS, EdgeLabelEnum.INTERFACE_ARTIFACTS, interfacArtsAll); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - @Override - public Either getToscaElement(String uniqueId, ComponentParametersView componentParametersView) { - - Either componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata); - if (componentByLabelAndId.isRight()) { - return Either.right(componentByLabelAndId.right().value()); - } - GraphVertex componentV = componentByLabelAndId.left().value(); - - return getToscaElement(componentV, componentParametersView); - - } - - // ------------------------------------------------------------- - @Override - public Either getToscaElement(GraphVertex componentV, ComponentParametersView componentParametersView) { - NodeType toscaElement; - toscaElement = convertToComponent(componentV); - TitanOperationStatus status = null; - if (!componentParametersView.isIgnoreUsers()) { - status = setCreatorFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - status = setLastModifierFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (!componentParametersView.isIgnoreProperties()) { - status = setResourcePropertiesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK && status != TitanOperationStatus.NOT_FOUND) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (!componentParametersView.isIgnoreAttributesFrom()) { - status = setResourceAttributesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (!componentParametersView.isIgnoreDerivedFrom()) { - status = setResourceDerivedFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (!componentParametersView.isIgnoreCategories()) { - status = setResourceCategoryFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!componentParametersView.isIgnoreRequirements()) { - status = setResourceRequirementsFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - log.error("Failed to set requirement of resource {}. status is {}", componentV.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!componentParametersView.isIgnoreCapabilities()) { - status = setResourceCapabilitiesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (!componentParametersView.isIgnoreArtifacts()) { - status = setArtifactsFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!componentParametersView.isIgnoreAdditionalInformation()) { - status = setAdditionalInformationFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!componentParametersView.isIgnoreInterfaces()) { - status = setInterfacesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!componentParametersView.isIgnoreAllVersions()) { - status = setAllVersions(componentV, toscaElement); - if (status != TitanOperationStatus.OK && status != TitanOperationStatus.NOT_FOUND) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (!componentParametersView.isIgnoreCapabiltyProperties()) { - status = setComponentCapPropertiesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - } - return Either.left(toscaElement); - } - - private TitanOperationStatus setComponentCapPropertiesFromGraph(GraphVertex componentV, NodeType toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES_PROPERTIES); - if (result.isLeft()) { - toscaElement.setCapabilitiesProperties(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setInterfacesFromGraph(GraphVertex componentV, NodeType toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INTERFACE_ARTIFACTS); - if (result.isLeft()) { - toscaElement.setInterfaceArtifacts(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - protected TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) { - return setResourceCapabilitiesFromGraph(componentV, (NodeType) toscaElement); - } - - private TitanOperationStatus setResourceCapabilitiesFromGraph(GraphVertex componentV, NodeType toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES); - if (result.isLeft()) { - toscaElement.setCapabilities(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setResourceDerivedFromGraph(GraphVertex componentV, NodeType toscaElement) { - List derivedFromList = new ArrayList<>(); - - TitanOperationStatus listFromGraphStatus = findResourcesPathRecursively(componentV, derivedFromList); - if (TitanOperationStatus.OK != listFromGraphStatus) { - return listFromGraphStatus; - } - - if (!derivedFromList.isEmpty()) { - if (derivedFromList.size() > 1) { - List lastDerivedFrom = new ArrayList<>(); - lastDerivedFrom.add(derivedFromList.get(1)); - toscaElement.setDerivedFrom(lastDerivedFrom); - toscaElement.setDerivedList(derivedFromList); - } else { - toscaElement.setDerivedFrom(null); - toscaElement.setDerivedList(derivedFromList); - } - - } - return TitanOperationStatus.OK; - } - - protected TitanOperationStatus findResourcesPathRecursively(GraphVertex nodeTypeV, List resourcesPathList) { - Either parentResourceRes = titanDao.getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); - resourcesPathList.add((String) nodeTypeV.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME)); - while (parentResourceRes.isLeft()) { - - GraphVertex parent = parentResourceRes.left().value(); - resourcesPathList.add((String) parent.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME)); - parentResourceRes = titanDao.getChildVertex(parent, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); - } - TitanOperationStatus operationStatus = parentResourceRes.right().value(); - - if (operationStatus != TitanOperationStatus.NOT_FOUND) { - return operationStatus; - } else { - return TitanOperationStatus.OK; - } - - } - - protected TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) { - return setResourceRequirementsFromGraph(componentV, (NodeType) toscaElement); - } - - private TitanOperationStatus setResourceRequirementsFromGraph(GraphVertex componentV, NodeType toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.REQUIREMENTS); - if (result.isLeft()) { - toscaElement.setRequirements(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setResourceAttributesFromGraph(GraphVertex componentV, NodeType toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ATTRIBUTES); - if (result.isLeft()) { - toscaElement.setAttributes(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setResourcePropertiesFromGraph(GraphVertex componentV, NodeType toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.PROPERTIES); - if (result.isLeft()) { - toscaElement.setProperties(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private StorageOperationStatus assosiateToDerived(GraphVertex nodeTypeVertex, List derivedResources) { - for (GraphVertex derivedV : derivedResources) { - TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, derivedV, EdgeLabelEnum.DERIVED_FROM, null); - if (createEdge != TitanOperationStatus.OK) { - log.trace("Failed to associate resource {} to derived with id {}", nodeTypeVertex.getUniqueId(), derivedV.getUniqueId()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { - // Note : currently only one derived supported!!!! - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.ADDITIONAL_INFORMATION); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map addInformationAll = dataFromDerived.left().value(); - - Map addInformation = nodeType.getAdditionalInformation(); - if (addInformation != null) { - ToscaDataDefinition.mergeDataMaps(addInformationAll, addInformation); - } - if (!addInformationAll.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformationAll); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { - // Note : currently only one derived supported!!!! - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.CAPABILITIES); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map capabiltiesAll = dataFromDerived.left().value(); - - Map capabilties = nodeType.getCapabilities(); - if (capabilties != null) { - if (capabiltiesAll == null) { - capabiltiesAll = new HashMap<>(); - } - capabilties.values().forEach(l -> { - l.getListToscaDataDefinition().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { - String uid = UniqueIdBuilder.buildCapabilityUid(nodeTypeVertex.getUniqueId(), p.getName()); - p.setUniqueId(uid); - }); - }); - - ToscaDataDefinition.mergeDataMaps(capabiltiesAll, capabilties); - capabiltiesAll.values().forEach(l -> { - l.getListToscaDataDefinition().forEach(c -> { - List capabilitySources = c.getCapabilitySources(); - if (capabilitySources == null) { - capabilitySources = new ArrayList<>(); - } - capabilitySources.add((String) nodeType.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); - c.setCapabilitySources(capabilitySources); - }); - }); - } - capabiltiesAll.values().forEach(l -> { - l.getListToscaDataDefinition().forEach(c -> { - List capabilitySources = c.getCapabilitySources(); - if (capabilitySources == null) { - capabilitySources = new ArrayList<>(); - } - capabilitySources.add((String) nodeType.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); - c.setCapabilitySources(capabilitySources); - }); - }); - if (!capabiltiesAll.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILITIES, EdgeLabelEnum.CAPABILITIES, capabiltiesAll); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { - // Note : currently only one derived supported!!!! - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.REQUIREMENTS); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map requirementsAll = dataFromDerived.left().value(); - - Map requirements = nodeType.getRequirements(); - if (requirements != null) { - if (requirementsAll == null) { - requirementsAll = new HashMap<>(); - } - requirements.values().forEach(l -> { - l.getListToscaDataDefinition().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { - String uid = UniqueIdBuilder.buildRequirementUid(nodeTypeVertex.getUniqueId(), p.getName()); - p.setUniqueId(uid); - }); - }); - - ToscaDataDefinition.mergeDataMaps(requirementsAll, requirements); - - } - if (!requirementsAll.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.REQUIREMENTS, EdgeLabelEnum.REQUIREMENTS, requirementsAll); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateAttributesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { - // Note : currently only one derived supported!!!! - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.ATTRIBUTES); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map attributesAll = dataFromDerived.left().value(); - - Map attributes = nodeType.getAttributes(); - if (attributes != null) { - attributes.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { - String uid = UniqueIdBuilder.buildAttributeUid(nodeTypeVertex.getUniqueId(), p.getName()); - p.setUniqueId(uid); - }); - ToscaDataDefinition.mergeDataMaps(attributesAll, attributes); - } - if (!attributesAll.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ATTRIBUTES, EdgeLabelEnum.ATTRIBUTES, attributesAll); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - // TODO get from derived - private StorageOperationStatus associateCapabilitiesPropertiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List derivedResources) { - // // Note : currently only one derived supported!!!! - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.CAPABILITIES_PROPERTIES); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map propertiesAll = dataFromDerived.left().value(); - Map capabiltiesProps = nodeType.getCapabilitiesProperties(); - if (capabiltiesProps != null) { - capabiltiesProps.values().forEach(l -> { - if (l.getMapToscaDataDefinition() != null && l.getMapToscaDataDefinition().values() != null) { - Collection mapToscaDataDefinition = l.getMapToscaDataDefinition().values(); - mapToscaDataDefinition.stream().filter(p -> p != null && p.getUniqueId() == null).forEach(p -> { - String uid = UniqueIdBuilder.buildRequirementUid(nodeTypeVertex.getUniqueId(), p.getName()); - p.setUniqueId(uid); - }); - } - }); - ToscaDataDefinition.mergeDataMaps(propertiesAll, capabiltiesProps); - } - if (!propertiesAll.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, propertiesAll); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - public Either, StorageOperationStatus> findDerivedResources(NodeType nodeType) { - - List derivedResources = new ArrayList<>(); - List derivedFromResources = nodeType.getDerivedFrom(); - if (derivedFromResources != null && !derivedFromResources.isEmpty()) { - - for (String parentResource : derivedFromResources) { - Either, TitanOperationStatus> getParentResources = derivedResourceResolver.findDerivedResources(parentResource); - List resources = null; - if (getParentResources.isRight()) { - log.error("Cannot find parent resource by tosca resource name {} in the graph.", parentResource); - return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND); - - } else { - resources = getParentResources.left().value(); - if (resources == null || resources.size() == 0) { - log.error("Cannot find parent resource by tosca name {} in the graph. resources size is empty", parentResource); - return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND); - } else { - if (resources.size() > 1) { - return handleMultipleParent(parentResource, derivedResources, resources); - } else { - GraphVertex parentResourceData = resources.get(0); - derivedResources.add(parentResourceData); - } - } - - } - - } - } - return Either.left(derivedResources); - } - - Either, StorageOperationStatus> handleMultipleParent(String parentResource, List derivedResource, List fetchedDerivedResources) { - - Either, StorageOperationStatus> result = Either.left(derivedResource); - try { - fetchedDerivedResources.sort((d1, d2) -> { - return new Double(Double.parseDouble((String) d1.getMetadataProperty(GraphPropertyEnum.VERSION))).compareTo(Double.parseDouble((String) d2.getMetadataProperty(GraphPropertyEnum.VERSION))); - }); - - int actualHighestIndex = fetchedDerivedResources.size() - 1; - derivedResource.add(fetchedDerivedResources.get(actualHighestIndex)); - fetchedDerivedResources.remove(actualHighestIndex); - - StorageOperationStatus status = fixMultipleParent(fetchedDerivedResources); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during handle multiple parent {}. Exception is {}", parentResource, e.getMessage()); - result = Either.right(StorageOperationStatus.GENERAL_ERROR); - } - return result; - } - - private StorageOperationStatus fixMultipleParent(List fetchedDerivedResources) { - StorageOperationStatus result = StorageOperationStatus.OK; - for (GraphVertex fetchedDerivedResource : fetchedDerivedResources) { - fetchedDerivedResource.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, false); - Either updateVertexRes = titanDao.updateVertex(fetchedDerivedResource); - if (updateVertexRes.isRight()) { - TitanOperationStatus titatStatus = updateVertexRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set highest version of node type {} to false. Status is {}", fetchedDerivedResource.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME), titatStatus); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus); - break; - } - } - return result; - } - - private GraphVertex fillMetadata(GraphVertex nodeTypeVertex, NodeType nodeType) { - nodeTypeVertex.setLabel(VertexTypeEnum.NODE_TYPE); - - fillCommonMetadata(nodeTypeVertex, nodeType); - - return nodeTypeVertex; - } - - @Override - public Either deleteToscaElement(GraphVertex toscaElementVertex) { - Either nodeType = getToscaElement(toscaElementVertex, new ComponentParametersView()); - if (nodeType.isRight()) { - log.debug("Failed to fetch tosca element {} error {}", toscaElementVertex.getUniqueId(), nodeType.right().value()); - return nodeType; - } - TitanOperationStatus status = disassociateAndDeleteCommonElements(toscaElementVertex); - if (status != TitanOperationStatus.OK) { - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate capabilties for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES_PROPERTIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate capabilties properties for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INTERFACE_ARTIFACTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate interface artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - toscaElementVertex.getVertex().remove(); - log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId()); - - return nodeType; - } - - @SuppressWarnings("unchecked") - @Override - public Either createToscaElement(ToscaElement toscaElement) { - return createNodeType((NodeType) toscaElement); - } - - @Override - protected TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) { - return setResourceCategoryFromGraph(vertexComponent, toscaElement); - } - - @Override - protected StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) { - return validateResourceCategory(toscaElementToUpdate, elementV); - } - - @Override - protected StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex nodeTypeV) { - - NodeType nodeType = (NodeType) toscaElementToUpdate; - - List derivedFromResources = nodeType.getDerivedFrom(); - - // now supported only single derived from - if (derivedFromResources != null && !derivedFromResources.isEmpty() && derivedFromResources.get(0) != null) { - String firstDerived = derivedFromResources.get(0); - boolean derivedFromGenericType = null != nodeType.getDerivedFromGenericType(); - Either childVertex = titanDao.getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); - if (childVertex.isRight()) { - TitanOperationStatus getchieldError = childVertex.right().value(); - log.debug("Failed to fetch derived resource for element {} error {}", nodeTypeV.getUniqueId(), getchieldError); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getchieldError); - } - GraphVertex firstDerivedInChain = childVertex.left().value(); - - String firstCurrentDerived = (String) firstDerivedInChain.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME); - if (!firstDerived.equals(firstCurrentDerived) || derivedFromGenericType) { - - Map propertiesToMatch = new HashMap<>(); - propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - - propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, firstDerived); - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - Either, TitanOperationStatus> getParentResources = titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, JsonParseFlagEnum.NoParse); - - if (getParentResources.isRight()) { - TitanOperationStatus error = getParentResources.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch derived by criteria {}. error {} ", propertiesToMatch, error); - return DaoStatusConverter.convertTitanStatusToStorageStatus(error); - } - // must be only one - GraphVertex newDerivedV = getParentResources.left().value().get(0); - return updateDerived(toscaElementToUpdate, nodeTypeV, firstDerivedInChain, newDerivedV, false); - } - } - return StorageOperationStatus.OK; - } - - /** - * - * @param toscaElementToUpdate - * @param nodeTypeV - * @param preDerivedV - * @param newDerivedV - * @param mergeValues - * @return - */ - protected StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex nodeTypeV, GraphVertex preDerivedV, GraphVertex newDerivedV, boolean mergeValues) { - Set preDerivedChainIdList = new HashSet(); - preDerivedChainIdList.add(preDerivedV.getUniqueId()); - Either childVertex = titanDao.getChildVertex(preDerivedV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); - while (childVertex.isLeft()) { - GraphVertex currentChield = childVertex.left().value(); - preDerivedChainIdList.add(currentChield.getUniqueId()); - childVertex = titanDao.getChildVertex(currentChield, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); - } - - List derivedResources = new ArrayList<>(); - derivedResources.add(newDerivedV); - StorageOperationStatus updateStatus = updateDataFromNewDerived(derivedResources, nodeTypeV, (NodeType) toscaElementToUpdate, mergeValues, preDerivedChainIdList); - if (updateStatus != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update data for {} from new derived {} ", nodeTypeV.getUniqueId(), newDerivedV.getUniqueId(), updateStatus); - return updateStatus; - } - - Either deleteEdge = titanDao.deleteEdge(nodeTypeV, preDerivedV, EdgeLabelEnum.DERIVED_FROM); - if (deleteEdge.isRight()) { - TitanOperationStatus deleteError = deleteEdge.right().value(); - log.debug("Failed to disassociate element {} from derived {} , error {}", nodeTypeV.getUniqueId(), preDerivedV.getUniqueId(), deleteError); - return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteError); - } - - titanDao.createEdge(nodeTypeV, newDerivedV, EdgeLabelEnum.DERIVED_FROM, new HashMap<>()); - - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateDerivedDataByType(EdgeLabelEnum edgeLabel, GraphVertex nodeTypeV, NodeType nodeToUpdate, List newDerived) { - - switch (edgeLabel) { - case CAPABILITIES: - return associateCapabilitiesToResource(nodeTypeV, nodeToUpdate, newDerived); - case REQUIREMENTS: - return associateRequirementsToResource(nodeTypeV, nodeToUpdate, newDerived); - case PROPERTIES: - return associatePropertiesToResource(nodeTypeV, nodeToUpdate, newDerived); - case ATTRIBUTES: - return associateAttributesToResource(nodeTypeV, nodeToUpdate, newDerived); - case ADDITIONAL_INFORMATION: - return addAdditionalInformationToResource(nodeTypeV, nodeToUpdate, newDerived); - case CAPABILITIES_PROPERTIES: - return associateCapabilitiesPropertiesToResource(nodeTypeV, nodeToUpdate, newDerived); - default: - return StorageOperationStatus.OK; - } - - } - - private StorageOperationStatus updateDataFromNewDerived(List newDerived, GraphVertex nodeTypeV, NodeType nodeToUpdate, boolean mergeValues, Set preDerivedChainIdList) { - EnumSet edgeLabels = EnumSet.of(EdgeLabelEnum.CAPABILITIES, EdgeLabelEnum.REQUIREMENTS, EdgeLabelEnum.PROPERTIES, EdgeLabelEnum.ATTRIBUTES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.ADDITIONAL_INFORMATION); - StorageOperationStatus status = null; - for (EdgeLabelEnum edge : edgeLabels) { - status = updateDataByType(newDerived, nodeTypeV, edge, nodeToUpdate, mergeValues, preDerivedChainIdList); - if (status != StorageOperationStatus.OK) { - break; - } - } - return status; - - } - - private StorageOperationStatus updateDataByType(List newDerivedList, GraphVertex nodeTypeV, EdgeLabelEnum label, NodeType nodeElement, boolean mergeValues, Set preDerivedChainIdList) { - log.debug("Update data from derived for element {} type {}", nodeTypeV.getUniqueId(), label); - Either dataFromGraph = getDataVertex(nodeTypeV, label); - if (dataFromGraph.isRight()) { - if (TitanOperationStatus.NOT_FOUND == dataFromGraph.right().value()) - return associateDerivedDataByType(label, nodeTypeV, nodeElement, newDerivedList); - return DaoStatusConverter.convertTitanStatusToStorageStatus(dataFromGraph.right().value()); - } - GraphVertex dataV = dataFromGraph.left().value(); - - Map mapFromGraph = (Map) dataV.getJson(); - Map valuesFrmPrev = null; - if (isSimpleHierarchy(label)) { - if (mergeValues) { - valuesFrmPrev = mapFromGraph.entrySet().stream().filter(e -> e.getValue().getOwnerId() != null).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - } - mapFromGraph.entrySet().removeIf(e -> preDerivedChainIdList.contains(e.getValue().getOwnerId())); - } else { - final Map valuesFrmPrevFinal = new HashMap<>(); - mapFromGraph.entrySet().stream().forEach(e -> { - T value = e.getValue(); - value = ToscaDataDefinition.removeAndCollectByOwnerId(value, preDerivedChainIdList); - valuesFrmPrevFinal.put(e.getKey(), value); - }); - valuesFrmPrev = valuesFrmPrevFinal; - mapFromGraph.entrySet().removeIf(e->e.getValue().isEmpty()); - } - - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(newDerivedList, label); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map dataFromDerivedAll = dataFromDerived.left().value(); - - Either, String> merged = ToscaDataDefinition.mergeDataMaps(dataFromDerivedAll, mapFromGraph); - if (merged.isRight()) { - log.debug("property {} cannot be overriden", merged.right().value()); - return StorageOperationStatus.INVALID_PROPERTY; - } - if (mergeValues && valuesFrmPrev != null) { - valuesFrmPrev.entrySet().forEach(e -> { - T newData = merged.left().value().get(e.getKey()); - if (newData != null) { - if (isSimpleHierarchy(label)) { - e.getValue().mergeFunction(newData, true); - }else{ - e.getValue().updateIfExist(newData, true); - } - } - }); - } - dataV.setJson(dataFromDerivedAll); - Either updateDataV = updateOrCopyOnUpdate(dataV, nodeTypeV, label); - if (updateDataV.isRight()) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(updateDataV.right().value()); - } - return StorageOperationStatus.OK; - } - - private boolean isSimpleHierarchy(EdgeLabelEnum label) { - switch (label) { - case PROPERTIES: - case ATTRIBUTES: - case ADDITIONAL_INFORMATION: - case ARTIFACTS: - case GROUPS: - case INPUTS: - return true; - default: - return false; - } - } - - @Override - public void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) { - fillMetadata(elementV, (NodeType) toscaElementToUpdate); - } - - public Either shouldUpdateDerivedVersion(ToscaElement toscaElementToUpdate, GraphVertex nodeTypeV) { - NodeType nodeType = (NodeType) toscaElementToUpdate; - - Either childVertex = titanDao.getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); - if (childVertex.isRight()) { - TitanOperationStatus getchildError = childVertex.right().value(); - if (getchildError == TitanOperationStatus.NOT_FOUND) { - log.debug("derived resource for element {} not found", nodeTypeV.getUniqueId()); - return Either.right(StorageOperationStatus.OK); - } - - log.debug("Failed to fetch derived resource for element {} error {}", nodeTypeV.getUniqueId(), getchildError); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getchildError)); - } - GraphVertex firstDerivedInChain = childVertex.left().value(); - - String currentVersion = (String) firstDerivedInChain.getMetadataProperty(GraphPropertyEnum.VERSION); - - Map props = new HashMap<>(); - props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, nodeType.getDerivedFrom().get(0)); - props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - Map propsHasNot = new HashMap<>(); - propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); - Either, TitanOperationStatus> byCriteria = titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, props, propsHasNot, JsonParseFlagEnum.NoParse); - if (byCriteria.isRight()) { - log.debug("Failed to fetch derived by props {} error {}", props, byCriteria.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value())); - } - List lastDerived = byCriteria.left().value(); - // now supported only one derived!!! Change in future!(Evg) - GraphVertex derivedFromHighest = lastDerived.get(0); - String highestVersion = (String) derivedFromHighest.getMetadataProperty(GraphPropertyEnum.VERSION); - if (!highestVersion.equals(currentVersion)) { - - // need to update to latest version of derived from - StorageOperationStatus updateDerived = updateDerived(toscaElementToUpdate, nodeTypeV, firstDerivedInChain, derivedFromHighest, true); - - if (updateDerived != StorageOperationStatus.OK) { - log.debug("Failed to update {} to highest derived {} from error {}", nodeTypeV.getUniqueId(), derivedFromHighest.getUniqueId(), updateDerived); - return Either.right(updateDerived); - } - return getToscaElement(nodeTypeV.getUniqueId(), new ComponentParametersView()); - } - // no version changes - return Either.right(StorageOperationStatus.OK); - } - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperation.java deleted file mode 100644 index efbac3301e..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperation.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.utils.MapUtil; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.PolicyDefinition; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.common.log.wrappers.Logger; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -@org.springframework.stereotype.Component -public class PolicyOperation { - - private static final Logger log = Logger.getLogger(PolicyOperation.class.getName()); - private TopologyTemplateOperation topologyTemplateOperation; - private TitanDao titanDao; - - public PolicyOperation(TopologyTemplateOperation topologyTemplateOperation, TitanDao titanDao) { - this.topologyTemplateOperation = topologyTemplateOperation; - this.titanDao = titanDao; - } - - /** - * updates a list of policy properties by overriding the existing ones with the same name - * @param containerComponent the container of the policy of which its properties are to be updated - * @param policyId the id of the policy of which its properties are to be updated - * @param propertiesToUpdate the policy properties to update - * @return the update operation status - */ - public StorageOperationStatus updatePolicyProperties(Component containerComponent, String policyId, List propertiesToUpdate) { - log.debug("#updatePolicyProperties - updating the properties of policy {} in component {}", policyId, containerComponent.getUniqueId()); - PolicyDefinition policy = containerComponent.getPolicyById(policyId); - return titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.NoParse) - .either(containerVertex -> updatePolicyProperties(containerVertex, policy, propertiesToUpdate), - DaoStatusConverter::convertTitanStatusToStorageStatus); - } - - private StorageOperationStatus updatePolicyProperties(GraphVertex container, PolicyDefinition policy, List propertiesToUpdate) { - List policyProperties = policy.getProperties(); - List updatedPolicyProperties = updatePolicyProperties(policyProperties, propertiesToUpdate); - policy.setProperties(updatedPolicyProperties); - return topologyTemplateOperation.updatePolicyOfToscaElement(container, policy); - } - - private List updatePolicyProperties(List currentPolicyProperties, List toBeUpdatedProperties) { - Map currPropsByName = MapUtil.toMap(currentPolicyProperties, PropertyDataDefinition::getName); - overrideCurrentPropertiesWithUpdatedProperties(currPropsByName, toBeUpdatedProperties); - return new ArrayList<>(currPropsByName.values()); - } - - private void overrideCurrentPropertiesWithUpdatedProperties(Map currPropsByName, List toBeUpdatedProperties) { - toBeUpdatedProperties.forEach(prop -> currPropsByName.put(prop.getName(), prop)); - } - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/RequirementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/RequirementOperation.java deleted file mode 100644 index 1fd37500bf..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/RequirementOperation.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright © 2016-2018 European Support Limited - * - * 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. - */ - -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -@org.springframework.stereotype.Component("requirement-operation") -public class RequirementOperation extends BaseOperation { - private static final Logger LOGGER = LoggerFactory.getLogger(RequirementOperation.class); - - public Either, StorageOperationStatus> addRequirement( - String componentId, - List requirementDefinitions) { - return addOrUpdateRequirements( componentId, requirementDefinitions, false); - } - - public Either, StorageOperationStatus> updateRequirement( - String componentId, - List requirementDefinitions) { - return addOrUpdateRequirements( componentId, requirementDefinitions, true); - } - - - private Either, StorageOperationStatus> addOrUpdateRequirements(String componentId, - List requirementDefinitions, - boolean isUpdateAction) { - - StorageOperationStatus statusRes = performUpdateToscaAction(isUpdateAction, - componentId, Collections - .singletonList(convertToListRequirementDataDefinition(requirementDefinitions))); - if (!statusRes.equals(StorageOperationStatus.OK)) { - titanDao.rollback(); - LOGGER.error("Failed to find the parent capability of capability type {}." - + " status is {}", componentId, statusRes); - return Either.right(statusRes); - } - titanDao.commit(); - return Either.left(requirementDefinitions); - } - - public StorageOperationStatus deleteRequirements(Component component, - String requirementToDelete) { - return deleteToscaDataElements(component.getUniqueId(), - EdgeLabelEnum.REQUIREMENTS, Collections.singletonList(requirementToDelete)); - } - - private static ListRequirementDataDefinition convertToListRequirementDataDefinition( - List requirementDefinitions) { - List requirementDataDefinitions = - new ArrayList<>(requirementDefinitions); - return new ListRequirementDataDefinition(requirementDataDefinitions); - } - - private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, - String componentId, List toscaDataList) { - if (isUpdate) { - return updateToscaDataOfToscaElement(componentId, EdgeLabelEnum.REQUIREMENTS, - VertexTypeEnum.REQUIREMENTS, toscaDataList, JsonPresentationFields.CAPABILITY); - } else { - return addToscaDataToToscaElement(componentId, EdgeLabelEnum.REQUIREMENTS, - VertexTypeEnum.REQUIREMENTS, toscaDataList, JsonPresentationFields.CAPABILITY); - } - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java deleted file mode 100644 index 5ddc5287ed..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java +++ /dev/null @@ -1,1624 +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.jsontitan.operations; - -import com.google.gson.reflect.TypeToken; -import fj.data.Either; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; -import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DistributionStatusEnum; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.PolicyDefinition; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; -import org.openecomp.sdc.be.model.jsontitan.utils.CapabilityRequirementNameResolver; -import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; -import org.openecomp.sdc.be.model.operations.StorageException; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.common.util.ValidationUtils; -import org.springframework.beans.factory.annotation.Autowired; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -@org.springframework.stereotype.Component("topology-template-operation") -public class TopologyTemplateOperation extends ToscaElementOperation { - - private static final Logger log = Logger.getLogger(TopologyTemplateOperation.class); - private Set nodeTypeSet = new HashSet<>(Arrays.asList(OriginTypeEnum.VFC, OriginTypeEnum.CP, OriginTypeEnum.VL, OriginTypeEnum.Configuration, OriginTypeEnum.VFCMT)); - - @Autowired - private ArchiveOperation archiveOperation; - - public Either createTopologyTemplate(TopologyTemplate topologyTemplate) { - Either result = null; - - topologyTemplate.generateUUID(); - - topologyTemplate = getResourceMetaDataFromResource(topologyTemplate); - String resourceUniqueId = topologyTemplate.getUniqueId(); - if (resourceUniqueId == null) { - resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId(); - topologyTemplate.setUniqueId(resourceUniqueId); - } - - GraphVertex topologyTemplateVertex = new GraphVertex(); - topologyTemplateVertex = fillMetadata(topologyTemplateVertex, topologyTemplate, JsonParseFlagEnum.ParseAll); - - Either createdVertex = titanDao.createVertex(topologyTemplateVertex); - if (createdVertex.isRight()) { - TitanOperationStatus status = createdVertex.right().value(); - log.debug("Error returned after creating topology template data node {}. status returned is ", topologyTemplateVertex, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - topologyTemplateVertex = createdVertex.left().value(); - - StorageOperationStatus assosiateCommon = assosiateCommonForToscaElement(topologyTemplateVertex, topologyTemplate, null); - if (assosiateCommon != StorageOperationStatus.OK) { - result = Either.right(assosiateCommon); - return result; - } - - StorageOperationStatus associateCategory = assosiateMetadataToCategory(topologyTemplateVertex, topologyTemplate); - if (associateCategory != StorageOperationStatus.OK) { - result = Either.right(associateCategory); - return result; - } - - StorageOperationStatus associateInputs = associateInputsToComponent(topologyTemplateVertex, topologyTemplate); - if (associateInputs != StorageOperationStatus.OK) { - result = Either.right(associateInputs); - return result; - } - StorageOperationStatus associateGroups = associateGroupsToComponent(topologyTemplateVertex, topologyTemplate); - if (associateGroups != StorageOperationStatus.OK) { - result = Either.right(associateGroups); - return result; - } - StorageOperationStatus associatePolicies = associatePoliciesToComponent(topologyTemplateVertex, topologyTemplate); - if (associatePolicies != StorageOperationStatus.OK) { - result = Either.right(associatePolicies); - return result; - } - StorageOperationStatus associateInstAttr = associateInstAttributesToComponent(topologyTemplateVertex, topologyTemplate); - if (associateInstAttr != StorageOperationStatus.OK) { - result = Either.right(associateInstAttr); - return result; - } - StorageOperationStatus associateInstProperties = associateInstPropertiesToComponent(topologyTemplateVertex, topologyTemplate); - if (associateInstProperties != StorageOperationStatus.OK) { - result = Either.right(associateInstProperties); - return result; - } - StorageOperationStatus associateInstInputs = associateInstInputsToComponent(topologyTemplateVertex, topologyTemplate); - if (associateInstProperties != StorageOperationStatus.OK) { - result = Either.right(associateInstInputs); - return result; - } - StorageOperationStatus associateInstGroups = associateInstGroupsToComponent(topologyTemplateVertex, topologyTemplate); - if (associateInstGroups != StorageOperationStatus.OK) { - result = Either.right(associateInstInputs); - return result; - } - - StorageOperationStatus associateRequirements = associateRequirementsToResource(topologyTemplateVertex, topologyTemplate); - if (associateRequirements != StorageOperationStatus.OK) { - result = Either.right(associateRequirements); - return result; - } - - StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(topologyTemplateVertex, topologyTemplate); - if (associateCapabilities != StorageOperationStatus.OK) { - result = Either.right(associateCapabilities); - return result; - } - - StorageOperationStatus associateArtifacts = associateTopologyTemplateArtifactsToComponent(topologyTemplateVertex, topologyTemplate); - if (associateArtifacts != StorageOperationStatus.OK) { - result = Either.right(associateArtifacts); - return result; - } - - StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(topologyTemplateVertex, topologyTemplate); - if (addAdditionalInformation != StorageOperationStatus.OK) { - result = Either.right(addAdditionalInformation); - return result; - } - StorageOperationStatus associateCapProperties = associateCapPropertiesToResource(topologyTemplateVertex, topologyTemplate); - if (associateCapProperties != StorageOperationStatus.OK) { - result = Either.right(associateCapProperties); - return result; - } - - StorageOperationStatus associateInterfaces = associateInterfacesToComponent(topologyTemplateVertex, topologyTemplate); - if (associateInterfaces != StorageOperationStatus.OK) { - result = Either.right(associateInterfaces); - return result; - } - - StorageOperationStatus associatePathProperties = associateForwardingPathToResource(topologyTemplateVertex, topologyTemplate); - if (associateCapProperties != StorageOperationStatus.OK) { - result = Either.right(associatePathProperties); - return result; - } - - - return Either.left(topologyTemplate); - - } - - private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - return associatePoliciesToComponent(nodeTypeVertex, topologyTemplate.getPolicies()); - } - - private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex, Map policies) { - if (policies != null && !policies.isEmpty()) { - policies.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { - String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName()); - p.setUniqueId(uid); - }); - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.POLICIES, EdgeLabelEnum.POLICIES, policies); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateForwardingPathToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) { - Map forwardingPaths = topologyTemplate.getForwardingPaths(); - return associateForwardingPathToComponent(topologyTemplateVertex, forwardingPaths); - } - - private StorageOperationStatus associateNodeFilterToResource(GraphVertex topologyTemplateVertex, - TopologyTemplate topologyTemplate) { - Map nodeFilters = - topologyTemplate.getNodeFilterComponents(); - return associateNodeFiltersToComponent(topologyTemplateVertex, nodeFilters); - } - - private StorageOperationStatus associateCapPropertiesToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) { - Map calculatedCapProperties = topologyTemplate - .getCalculatedCapabilitiesProperties(); - if (MapUtils.isNotEmpty(calculatedCapProperties)) { - Either associateElementToData = associateElementToData - (topologyTemplateVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, - EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapProperties); - if (associateElementToData.isRight()) { - return associateElementToData.right().value(); - } - } - - Map capabilitiesProperties = topologyTemplate.getCapabilitiesProperties(); - if (MapUtils.isNotEmpty(capabilitiesProperties)) { - Either associateElementToData = - associateElementToData(topologyTemplateVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, - EdgeLabelEnum.CAPABILITIES_PROPERTIES, capabilitiesProperties); - if (associateElementToData.isRight()) { - return associateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map calculatedCapabilities = topologyTemplate.getCalculatedCapabilities(); - if (calculatedCapabilities != null && !calculatedCapabilities.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calculatedCapabilities); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - Map fullfilledCapabilities = topologyTemplate.getFullfilledCapabilities(); - if (fullfilledCapabilities != null && !fullfilledCapabilities.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullfilledCapabilities); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - Map capabilities = topologyTemplate.getCapabilities(); - if(MapUtils.isNotEmpty(capabilities)) { - Either associateElementToData = - associateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILITIES, - EdgeLabelEnum.CAPABILITIES, capabilities); - if (associateElementToData.isRight()) { - return associateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - - } - - private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map calculatedRequirements = topologyTemplate.getCalculatedRequirements(); - if (calculatedRequirements != null && !calculatedRequirements.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calculatedRequirements); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - Map fullfilledRequirements = topologyTemplate.getFullfilledRequirements(); - if (fullfilledRequirements != null && !fullfilledRequirements.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullfilledRequirements); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - Map requirements = topologyTemplate.getRequirements(); - if(MapUtils.isNotEmpty(requirements)) { - Either associateElementToData = - associateElementToData(nodeTypeVertex, VertexTypeEnum.REQUIREMENTS, - EdgeLabelEnum.REQUIREMENTS, requirements); - if (associateElementToData.isRight()) { - return associateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateTopologyTemplateArtifactsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map addInformation = topologyTemplate.getServiceApiArtifacts(); - - if (addInformation != null && !addInformation.isEmpty()) { - addInformation.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); - a.setUniqueId(uniqueId); - }); - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.SERVICE_API_ARTIFACTS, EdgeLabelEnum.SERVICE_API_ARTIFACTS, addInformation); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - Map instArtifacts = topologyTemplate.getInstDeploymentArtifacts(); - - if (instArtifacts != null && !instArtifacts.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, instArtifacts); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - Map instInfoArtifacts = topologyTemplate.getInstanceArtifacts(); - - if (instInfoArtifacts != null && !instInfoArtifacts.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS, instInfoArtifacts); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - - Map addInformation = topologyTemplate.getAdditionalInformation(); - - if (addInformation != null && !addInformation.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformation); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map instProps = topologyTemplate.getInstProperties(); - return associateInstPropertiesToComponent(nodeTypeVertex, instProps); - } - - public StorageOperationStatus associateInstInputsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map instProps = topologyTemplate.getInstInputs(); - return associateInstInputsToComponent(nodeTypeVertex, instProps); - } - - public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map instGroups = topologyTemplate.getInstGroups(); - return associateInstGroupsToComponent(nodeTypeVertex, instGroups); - } - - - public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map instProps) { - if (instProps != null && !instProps.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_PROPERTIES, EdgeLabelEnum.INST_PROPERTIES, instProps); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus associateInstInputsToComponent(GraphVertex nodeTypeVertex, Map instInputs) { - if (instInputs != null && !instInputs.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, instInputs); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, Map instGroups) { - if (instGroups != null && !instGroups.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, instGroups); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - - public StorageOperationStatus deleteInstInputsToComponent(GraphVertex nodeTypeVertex, Map instInputs) { - - if (instInputs != null && !instInputs.isEmpty()) { - instInputs.entrySet().forEach(i -> { - List uniqueKeys = new ArrayList<>(i.getValue().getMapToscaDataDefinition().keySet()); - List pathKeys = new ArrayList<>(); - pathKeys.add(i.getKey()); - - StorageOperationStatus status = deleteToscaDataDeepElements(nodeTypeVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, uniqueKeys, pathKeys, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - return; - } - }); - } - - return StorageOperationStatus.OK; - } - - public StorageOperationStatus addInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map instInputs) { - - if (instInputs != null && !instInputs.isEmpty()) { - instInputs.entrySet().forEach(i -> { - StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(nodeTypeVertex, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, i.getValue(), i.getKey()); - if (status != StorageOperationStatus.OK) { - return; - } - }); - } - - return StorageOperationStatus.OK; - } - - public StorageOperationStatus associateInstDeploymentArtifactsToComponent(GraphVertex nodeTypeVertex, Map instArtifacts) { - return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); - } - - public StorageOperationStatus associateInstArtifactsToComponent(GraphVertex nodeTypeVertex, Map instArtifacts) { - return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS); - } - - private StorageOperationStatus associateInstanceArtifactsToComponent(GraphVertex nodeTypeVertex, Map instProps, VertexTypeEnum vertexType, EdgeLabelEnum edgeLabel) { - if (instProps != null && !instProps.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, vertexType, edgeLabel, instProps); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus associateOrAddCalcCapReqToComponent(GraphVertex nodeTypeVertex, Map calcRequirements, Map calcCapabilty, Map calculatedCapabilitiesProperties) { - if (calcRequirements != null && !calcRequirements.isEmpty()) { - Either assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calcRequirements); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - Map fullFilled = new HashMap<>(); - assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullFilled); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - if (calcCapabilty != null && !calcCapabilty.isEmpty()) { - Either assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calcCapabilty); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - Map fullFilled = new HashMap<>(); - assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullFilled); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - if (calculatedCapabilitiesProperties != null && !calculatedCapabilitiesProperties.isEmpty()) { - return associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, - EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapabilitiesProperties) - .right() - .on(v -> StorageOperationStatus.OK); - } - return StorageOperationStatus.OK; - } - - private Either associateOrAddElementToData(GraphVertex nodeTypeVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map dataMap) { - return titanDao.getChildVertex(nodeTypeVertex, edgeLabelEnum, JsonParseFlagEnum.ParseJson) - .either(dataVertex -> addElementsToComponent(nodeTypeVertex, dataVertex, vertexTypeEnum, edgeLabelEnum, dataMap), - status -> associateElementToDataIfNotFound(status, nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap)); - } - - private Either associateElementToDataIfNotFound(TitanOperationStatus status, GraphVertex nodeTypeVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map dataMap) { - if (status == TitanOperationStatus.NOT_FOUND) { - return associateElementToData(nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap); - } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - private Either addElementsToComponent(GraphVertex nodeTypeVertex, GraphVertex dataVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map dataMap) { - Optional error = dataMap.entrySet() - .stream() - .map(e -> addElementToComponent(nodeTypeVertex.getUniqueId(), vertexTypeEnum, edgeLabelEnum, e)) - .filter(s -> s != StorageOperationStatus.OK) - .findFirst(); - if (error.isPresent()) { - return Either.right(error.get()); - } - return Either.left(dataVertex); - } - - private StorageOperationStatus associateInstAttributesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map instAttr = topologyTemplate.getInstAttributes(); - return associateInstAttributeToComponent(nodeTypeVertex, instAttr); - } - - public StorageOperationStatus associateForwardingPathToComponent(GraphVertex nodeTypeVertex, Map forwardingPathMap) { - if (forwardingPathMap != null && !forwardingPathMap.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FORWARDING_PATH, EdgeLabelEnum.FORWARDING_PATH, forwardingPathMap); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus associateInstAttributeToComponent(GraphVertex nodeTypeVertex, Map instAttr) { - if (instAttr != null && !instAttr.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_ATTRIBUTES, EdgeLabelEnum.INST_ATTRIBUTES, instAttr); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, Map groups) { - - if (groups != null && !groups.isEmpty()) { - groups.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { - String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName()); - p.setUniqueId(uid); - }); - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.GROUPS, EdgeLabelEnum.GROUPS, groups); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - return associateGroupsToComponent(nodeTypeVertex, topologyTemplate.getGroups()); - } - - public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map inputs = topologyTemplate.getInputs(); - return associateInputsToComponent(nodeTypeVertex, inputs, topologyTemplate.getUniqueId()); - } - - public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, Map inputs, String id) { - if (inputs != null && !inputs.isEmpty()) { - inputs.values().stream().filter(e -> e.getUniqueId() == null).forEach(e -> e.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(id, e.getName()))); - - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INPUTS, EdgeLabelEnum.INPUTS, inputs); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private GraphVertex fillMetadata(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate, JsonParseFlagEnum flag) { - nodeTypeVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); - fillCommonMetadata(nodeTypeVertex, topologyTemplate); - if (flag == JsonParseFlagEnum.ParseAll || flag == JsonParseFlagEnum.ParseJson) { - nodeTypeVertex.setJson(topologyTemplate.getCompositions()); - } - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.CSAR_UUID, topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, topologyTemplate.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS)); - - return nodeTypeVertex; - - } - - private StorageOperationStatus assosiateMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - if (topologyTemplate.getResourceType() == null) { - // service - return associateServiceMetadataToCategory(nodeTypeVertex, topologyTemplate); - } else { - // VF - return assosiateResourceMetadataToCategory(nodeTypeVertex, topologyTemplate); - } - } - - private StorageOperationStatus associateServiceMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - String categoryName = topologyTemplate.getCategories().get(0).getName(); - Either category = categoryOperation.getCategory(categoryName, VertexTypeEnum.SERVICE_CATEGORY); - if (category.isRight()) { - log.trace("NO category {} for service {}", categoryName, topologyTemplate.getUniqueId()); - return StorageOperationStatus.CATEGORY_NOT_FOUND; - } - GraphVertex categoryV = category.left().value(); - TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, categoryV, EdgeLabelEnum.CATEGORY, new HashMap<>()); - if (createEdge != TitanOperationStatus.OK) { - log.trace("Failed to associate resource {} to category {} with id {}", topologyTemplate.getUniqueId(), categoryName, categoryV.getUniqueId()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge); - } - return StorageOperationStatus.OK; - } - - @Override - public Either getToscaElement(String uniqueId, ComponentParametersView componentParametersView) { - JsonParseFlagEnum parseFlag = componentParametersView.detectParseFlag(); - - Either componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.TOPOLOGY_TEMPLATE, parseFlag); - if (componentByLabelAndId.isRight()) { - return Either.right(componentByLabelAndId.right().value()); - } - GraphVertex componentV = componentByLabelAndId.left().value(); - - return getToscaElement(componentV, componentParametersView); - - } - // ------------------------------------------------------------- - - public Either getToscaElement(GraphVertex componentV, ComponentParametersView componentParametersView) { - TopologyTemplate toscaElement; - - toscaElement = convertToTopologyTemplate(componentV); - TitanOperationStatus status; - if (!componentParametersView.isIgnoreUsers()) { - status = setCreatorFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - status = setLastModifierFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!componentParametersView.isIgnoreCategories()) { - status = setTopologyTempalteCategoriesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - } - if (!componentParametersView.isIgnoreArtifacts()) { - TitanOperationStatus storageStatus = setAllArtifactsFromGraph(componentV, toscaElement); - if (storageStatus != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(storageStatus)); - } - } - if (!componentParametersView.isIgnoreComponentInstancesProperties()) { - status = setComponentInstancesPropertiesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!componentParametersView.isIgnoreCapabilities()) { - status = setCapabilitiesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!componentParametersView.isIgnoreRequirements()) { - status = setRequirementsFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!componentParametersView.isIgnoreAllVersions()) { - status = setAllVersions(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!componentParametersView.isIgnoreAdditionalInformation()) { - status = setAdditionalInformationFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (!componentParametersView.isIgnoreGroups()) { - status = setGroupsFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - } - if (!componentParametersView.isIgnorePolicies()) { - status = setPoliciesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - } - if (!componentParametersView.isIgnoreComponentInstances()) { - status = setInstGroupsFromGraph(componentV, toscaElement); - - //Mark all CIs that has archived origins - archiveOperation.setArchivedOriginsFlagInComponentInstances(componentV); - - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - } - if (!componentParametersView.isIgnoreInputs()) { - status = setInputsFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - } - if (!componentParametersView.isIgnoreProperties()) { - status = setPropertiesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - } - - if (!componentParametersView.isIgnoreComponentInstancesInputs()) { - status = setComponentInstancesInputsFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - } - - if (!componentParametersView.isIgnoreCapabiltyProperties()) { - status = setComponentInstancesCapPropertiesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - } - - if (!componentParametersView.isIgnoreForwardingPath()) { - status = setForwardingGraphPropertiesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - } - - if (!componentParametersView.isIgnoreNodeFilter()) { - status = setNodeFilterComponentFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - } - - if (!componentParametersView.isIgnoreInterfaces()) { - TitanOperationStatus storageStatus = setInterfacesFromGraph(componentV, toscaElement); - if (storageStatus != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(storageStatus)); - - } - } - - if (!componentParametersView.isIgnoreComponentInstancesInterfaces()) { - TitanOperationStatus storageStatus = - setComponentInstancesInterfacesFromGraph(componentV, toscaElement); - if (storageStatus != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(storageStatus)); - } - } - - if (!componentParametersView.isIgnoreDataType()) { - TitanOperationStatus storageStatus = setDataTypesFromGraph(componentV, toscaElement); - if (storageStatus != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(storageStatus)); - } - } - - return Either.left(toscaElement); - } - - private TitanOperationStatus setDataTypesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.DATA_TYPES); - if (result.isLeft()) { - toscaElement.setDataTypes(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setPoliciesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.POLICIES); - if (result.isLeft()) { - toscaElement.setPolicies(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setInterfacesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INTERFACE); - if (result.isLeft()) { - topologyTemplate.setInterfaces(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - - private TitanOperationStatus setComponentInstancesInterfacesFromGraph(GraphVertex componentV, - TopologyTemplate topologyTemplate) { - Either, TitanOperationStatus> result = - getDataFromGraph(componentV, EdgeLabelEnum.INST_INTERFACES); - if (result.isLeft()) { - result.left().value().entrySet().forEach(entry -> topologyTemplate - .addComponentInstanceInterfaceMap(entry.getKey(), entry.getValue())); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private StorageOperationStatus associateInterfacesToComponent(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) { - Map interfaceMap = topologyTemplate.getInterfaces(); - if (interfaceMap != null && !interfaceMap.isEmpty()) { - Either assosiateElementToData = associateElementToData(topologyTemplateVertex, VertexTypeEnum.INTERFACE, EdgeLabelEnum.INTERFACE, interfaceMap); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus associateNodeFiltersToComponent(GraphVertex nodeTypeVertex, - Map filterMaps) { - if (filterMaps != null && !filterMaps.isEmpty()) { - Either assosiateElementToData = associateElementToData - (nodeTypeVertex, VertexTypeEnum.NODE_FILTER_TEMPLATE, - EdgeLabelEnum.NODE_FILTER_TEMPLATE, filterMaps); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private TitanOperationStatus setForwardingGraphPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.FORWARDING_PATH); - if (result.isLeft()) { - topologyTemplate.setForwardingPaths(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - - private TitanOperationStatus setComponentInstancesCapPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES); - if (result.isLeft()) { - topologyTemplate.setCalculatedCapabilitiesProperties(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - Either, TitanOperationStatus> capPropResult = - getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES_PROPERTIES); - if (capPropResult.isLeft()) { - topologyTemplate.setCapabilitiesProperties(capPropResult.left().value()); - } else { - if (capPropResult.right().value() != TitanOperationStatus.NOT_FOUND) { - return capPropResult.right().value(); - } - } - - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setPropertiesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.PROPERTIES); - if (result.isLeft()) { - toscaElement.setProperties(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setInstGroupsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_GROUPS); - if (result.isLeft()) { - topologyTemplate.setInstGroups(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setComponentInstancesPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_PROPERTIES); - if (result.isLeft()) { - topologyTemplate.setInstProperties(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setComponentInstancesInputsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_INPUTS); - if (result.isLeft()) { - topologyTemplate.setInstInputs(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setNodeFilterComponentFromGraph(GraphVertex componentV, - TopologyTemplate topologyTemplate) { - Either, TitanOperationStatus> result = - getDataFromGraph(componentV, - EdgeLabelEnum.NODE_FILTER_TEMPLATE); - if (result.isLeft()) { - topologyTemplate.setNodeFilterComponents(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - @Override - protected TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); - if (result.isLeft()) { - ((TopologyTemplate) toscaElement).setCalculatedRequirements(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); - if (result.isLeft()) { - ((TopologyTemplate) toscaElement).setFullfilledRequirements(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - Either, TitanOperationStatus> requirementResult = - getDataFromGraph(componentV, EdgeLabelEnum.REQUIREMENTS); - if (requirementResult.isLeft()) { - toscaElement.setRequirements(requirementResult.left().value()); - } else { - if (requirementResult.right().value() != TitanOperationStatus.NOT_FOUND) { - return requirementResult.right().value(); - } - } - return TitanOperationStatus.OK; - - } - - protected TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAPABILITIES); - if (result.isLeft()) { - ((TopologyTemplate) toscaElement).setCalculatedCapabilities(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); - if (result.isLeft()) { - ((TopologyTemplate) toscaElement).setFullfilledCapabilities(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - Either, TitanOperationStatus> capabilitiesResult = - getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES); - if (capabilitiesResult.isLeft()) { - toscaElement.setCapabilities(capabilitiesResult.left().value()); - } else { - if (capabilitiesResult.right().value() != TitanOperationStatus.NOT_FOUND) { - return capabilitiesResult.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setAllArtifactsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { - TitanOperationStatus storageStatus = setArtifactsFromGraph(componentV, toscaElement); - if (storageStatus != TitanOperationStatus.OK) { - return storageStatus; - } - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.SERVICE_API_ARTIFACTS); - if (result.isLeft()) { - toscaElement.setServiceApiArtifacts(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - Either, TitanOperationStatus> resultInstArt = getDataFromGraph(componentV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); - if (resultInstArt.isLeft()) { - toscaElement.setInstDeploymentArtifacts(resultInstArt.left().value()); - } else { - if (resultInstArt.right().value() != TitanOperationStatus.NOT_FOUND) { - return resultInstArt.right().value(); - } - } - Either, TitanOperationStatus> instanceArt = getDataFromGraph(componentV, EdgeLabelEnum.INSTANCE_ARTIFACTS); - if (instanceArt.isLeft()) { - toscaElement.setInstanceArtifacts(instanceArt.left().value()); - } else { - if (instanceArt.right().value() != TitanOperationStatus.NOT_FOUND) { - return instanceArt.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setInputsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INPUTS); - if (result.isLeft()) { - toscaElement.setInputs(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setGroupsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.GROUPS); - if (result.isLeft()) { - toscaElement.setGroups(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setTopologyTempalteCategoriesFromGraph(GraphVertex componentV, ToscaElement toscaElement) { - List categories = new ArrayList<>(); - - switch (componentV.getType()) { - case RESOURCE: - return setResourceCategoryFromGraph(componentV, toscaElement); - case SERVICE: - return setServiceCategoryFromGraph(componentV, toscaElement, categories); - - default: - log.debug("Not supported component type {} ", componentV.getType()); - break; - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setServiceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement, List categories) { - Either childVertex = titanDao.getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); - if (childVertex.isRight()) { - log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value()); - return childVertex.right().value(); - } - GraphVertex categoryV = childVertex.left().value(); - Map metadataProperties = categoryV.getMetadataProperties(); - CategoryDefinition category = new CategoryDefinition(); - category.setUniqueId(categoryV.getUniqueId()); - category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME)); - category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME)); - - Type listTypeCat = new TypeToken>() { - }.getType(); - List iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS.getProperty()), listTypeCat); - category.setIcons(iconsfromJsonCat); - categories.add(category); - toscaElement.setCategories(categories); - - return TitanOperationStatus.OK; - } - - @SuppressWarnings("unchecked") - private TopologyTemplate convertToTopologyTemplate(GraphVertex componentV) { - - TopologyTemplate topologyTemplate = super.convertToComponent(componentV); - - Map json = (Map) componentV.getJson(); - topologyTemplate.setCompositions(json); - - return topologyTemplate; - } - - @Override - public Either deleteToscaElement(GraphVertex toscaElementVertex) { - Either nodeType = getToscaElement(toscaElementVertex, new ComponentParametersView()); - if (nodeType.isRight()) { - log.debug("Failed to fetch tosca element {} error {}", toscaElementVertex.getUniqueId(), nodeType.right().value()); - return nodeType; - } - TitanOperationStatus status = disassociateAndDeleteCommonElements(toscaElementVertex); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_ATTRIBUTES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate instances attributes for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_PROPERTIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate instances properties for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate instances inputs for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.GROUPS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate groups for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.POLICIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate policies for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_GROUPS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate instance groups for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INPUTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate inputs for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate instance inputs for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES_PROPERTIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate capabilities properties for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAPABILITIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate calculated capabiliites for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_CAPABILITIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate fullfilled capabilities for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate calculated capabiliites properties for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_REQUIREMENTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate calculated requirements for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate full filled requirements for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate instance artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.SERVICE_API_ARTIFACTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INTERFACE); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate interfaces for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INSTANCE_ARTIFACTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate instance artifact for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, - EdgeLabelEnum.REQUIREMENTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate requirements for {} error {}", - toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, - EdgeLabelEnum.CAPABILITIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate capabilities for {} error {}", - toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INTERFACES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate instances interfaces for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - toscaElementVertex.getVertex().remove(); - log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId()); - - return nodeType; - } - - @SuppressWarnings("unchecked") - @Override - public Either createToscaElement(ToscaElement toscaElement) { - return createTopologyTemplate((TopologyTemplate) toscaElement); - } - - @Override - protected TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) { - return setTopologyTempalteCategoriesFromGraph(vertexComponent, toscaElement); - } - - @Override - protected StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) { - // Product isn't supported now!! - // TODO add for Product - if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.SERVICE) { - return validateServiceCategory(toscaElementToUpdate, elementV); - } else { - // Resource - return validateResourceCategory(toscaElementToUpdate, elementV); - } - } - - @Override - protected StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV) { - // not relevant now for topology template - return StorageOperationStatus.OK; - } - - @Override - public void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) { - fillMetadata(elementV, (TopologyTemplate) toscaElementToUpdate, flag); - } - - private StorageOperationStatus validateServiceCategory(T toscaElementToUpdate, GraphVertex elementV) { - StorageOperationStatus status = StorageOperationStatus.OK; - List newCategoryList = toscaElementToUpdate.getCategories(); - CategoryDefinition newCategory = newCategoryList.get(0); - - Either childVertex = titanDao.getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); - if (childVertex.isRight()) { - log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value()); - } - - GraphVertex categoryV = childVertex.left().value(); - Map metadataProperties = categoryV.getMetadataProperties(); - String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); - - String newCategoryName = newCategory.getName(); - if (newCategoryName != null && !newCategoryName.equals(categoryNameCurrent)) { - // the category was changed - Either getCategoryVertex = categoryOperation.getCategory(newCategoryName, VertexTypeEnum.SERVICE_CATEGORY); - - if (getCategoryVertex.isRight()) { - return getCategoryVertex.right().value(); - } - GraphVertex newCategoryV = getCategoryVertex.left().value(); - status = moveCategoryEdge(elementV, newCategoryV); - log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status); - } - return status; - } - - public Either updateDistributionStatus(String uniqueId, User user, DistributionStatusEnum distributionStatus) { - - Either result = null; - String userId = user.getUserId(); - Either getRes = findUserVertex(userId); - GraphVertex userVertex = null; - GraphVertex serviceVertex = null; - if (getRes.isRight()) { - TitanOperationStatus status = getRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Cannot find user {} in the graph. status is {}", userId, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - userVertex = getRes.left().value(); - getRes = titanDao.getVertexById(uniqueId, JsonParseFlagEnum.ParseMetadata); - if (getRes.isRight()) { - TitanOperationStatus status = getRes.right().value(); - log.debug("Cannot find service {} in the graph. status is {}", uniqueId, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (result == null) { - serviceVertex = getRes.left().value(); - Iterator edgeIterator = serviceVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER.name()); - if (edgeIterator.hasNext()) { - log.debug("Remove existing edge from user to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER); - edgeIterator.next().remove(); - } - } - if (result == null) { - TitanOperationStatus status = titanDao.createEdge(userVertex, serviceVertex, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER, null); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to associate user {} to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (result == null) { - serviceVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, distributionStatus.name()); - long lastUpdateDate = System.currentTimeMillis(); - serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate); - Either updateRes = titanDao.updateVertex(serviceVertex); - if (updateRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value())); - } - } - if (result == null) { - result = Either.left(serviceVertex); - } - return result; - } - - /** - * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId - * - * @param componentId - * @param instanceId - * @param capabilityName - * @param capabilityType - * @param ownerId - * @return - */ - public Either, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) { - - Either, StorageOperationStatus> result = null; - Map mapPropertiesDataDefinition = null; - Either componentByLabelAndId = getComponentByLabelAndId(componentId, ToscaElementTypeEnum.TOPOLOGY_TEMPLATE, JsonParseFlagEnum.NoParse); - if (componentByLabelAndId.isRight()) { - result = Either.right(componentByLabelAndId.right().value()); - } - if (componentByLabelAndId.isLeft()) { - Either, TitanOperationStatus> getDataRes = getDataFromGraph(componentByLabelAndId.left().value(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES); - if (getDataRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getDataRes.right().value())); - } else { - mapPropertiesDataDefinition = getDataRes.left().value(); - } - } - if (isNotEmptyMapOfProperties(instanceId, mapPropertiesDataDefinition)) { - result = Either.left(findComponentInstanceCapabilityProperties(instanceId, capabilityName, capabilityType, ownerId, mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition())); - } - return result; - } - - public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceId, MapCapabilityProperty instanceProperties) { - return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, instanceProperties, componentInstanceId); - } - - public StorageOperationStatus updateComponentInstanceInterfaces(Component containerComponent, - String componentInstanceId, - MapInterfaceDataDefinition instanceInterfaces) { - if (MapUtils.isNotEmpty(instanceInterfaces.getMapToscaDataDefinition())) { - return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), - EdgeLabelEnum.INST_INTERFACES, instanceInterfaces, componentInstanceId); - } - return StorageOperationStatus.OK; - } - - - private boolean isNotEmptyMapOfProperties(String instanceId, Map mapPropertiesDataDefinition) { - return MapUtils.isNotEmpty(mapPropertiesDataDefinition) && - mapPropertiesDataDefinition.get(instanceId) != null && - MapUtils.isNotEmpty(mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition()); - } - - private List findComponentInstanceCapabilityProperties(String instanceId, String capabilityName, String capabilityType, String ownerId, Map propertiesMap) { - List capPropsList = null; - for (Entry capProp : propertiesMap.entrySet()) { - if (isBelongingPropertyMap(instanceId, capabilityName, capabilityType, ownerId, capProp)) { - Map capMap = capProp.getValue().getMapToscaDataDefinition(); - if (capMap != null && !capMap.isEmpty()) { - capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList()); - break; - } - } - } - if (capPropsList == null) { - capPropsList = new ArrayList<>(); - } - return capPropsList; - } - - private boolean isBelongingPropertyMap(String instanceId, String capabilityName, String capabilityType, String ownerId, Entry capProp) { - if (capProp != null) { - String[] path = capProp.getKey().split(ModelConverter.CAP_PROP_DELIM); - if (path.length < 4) { - log.debug("wrong key format for capabilty, key {}", capProp); - return false; - } - return path[path.length - 2].equals(capabilityType) && path[path.length - 1].equals(capabilityName) && path[1].equals(ownerId) && path[0].equals(instanceId); - } - return false; - } - - public StorageOperationStatus addPolicyToToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) { - fillPolicyDefinition(componentV, policyDefinition, counter); - return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID); - } - - public StorageOperationStatus addPoliciesToToscaElement(GraphVertex componentV, List policies) { - return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policies, JsonPresentationFields.UNIQUE_ID); - } - - public StorageOperationStatus updatePolicyOfToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition) { - return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID); - } - - public StorageOperationStatus updatePoliciesOfToscaElement(GraphVertex componentV, List policiesDefinitions) { - return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policiesDefinitions, JsonPresentationFields.UNIQUE_ID); - } - - public StorageOperationStatus removePolicyFromToscaElement(GraphVertex componentV, String policyId) { - return deleteToscaDataElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyId, JsonPresentationFields.UNIQUE_ID); - } - - public StorageOperationStatus updateGroupOfToscaElement(GraphVertex componentV, GroupDefinition groupDefinition) { - return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition, JsonPresentationFields.NAME); - } - - private void fillPolicyDefinition(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) { - String policyName = buildSubComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME), policyDefinition.getPolicyTypeName(), counter); - policyDefinition.setName(policyName); - policyDefinition.setInvariantName(policyName); - policyDefinition.setComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME)); - policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentV.getUniqueId(), policyName)); - policyDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); - policyDefinition.setPolicyUUID(UniqueIdBuilder.generateUUID()); - } - - public static String buildSubComponentName(String componentName, String subComponentTypeName, int counter) { - String normalizedComponentName = ValidationUtils.normalizeComponentInstanceName(componentName); - String typeSuffix = subComponentTypeName.substring(subComponentTypeName.lastIndexOf('.') + 1, subComponentTypeName.length()); - return normalizedComponentName + Constants.GROUP_POLICY_NAME_DELIMETER + typeSuffix + Constants.GROUP_POLICY_NAME_DELIMETER + counter; - } - - void revertNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) { - if (MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())) { - GraphVertex toscaElementV = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse) - .left() - .on(this::throwStorageException); - if (MapUtils.isNotEmpty(toscaElement.getComponentInstances())) { - toscaElement.getComponentInstances().values().forEach(i -> CapabilityRequirementNameResolver.revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), this::getOriginToscaElement)); - } - if (MapUtils.isNotEmpty(toscaElement.getGroups())) { - toscaElement.getGroups().values().forEach(g -> CapabilityRequirementNameResolver.revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), this::getOriginToscaElement)); - } - topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, toscaElement.getCalculatedCapabilities()); - topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, toscaElement.getCalculatedRequirements()); - topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, toscaElement.getCalculatedCapabilitiesProperties()); - } - } - - public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) { - if (MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())) { - GraphVertex toscaElementV = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse) - .left() - .on(this::throwStorageException); - if (MapUtils.isNotEmpty(toscaElement.getComponentInstances())) { - toscaElement.getComponentInstances().values().forEach(i -> CapabilityRequirementNameResolver.updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), i.getNormalizedName(), this::getOriginToscaElement)); - } - if (MapUtils.isNotEmpty(toscaElement.getGroups())) { - toscaElement.getGroups().values().forEach(g -> CapabilityRequirementNameResolver.updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), g.getName(), this::getOriginToscaElement)); - } - topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, toscaElement.getCalculatedCapabilities()); - topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, toscaElement.getCalculatedRequirements()); - topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, toscaElement.getCalculatedCapabilitiesProperties()); - } - } - - private ToscaElement getOriginToscaElement(ComponentInstanceDataDefinition instance) { - log.debug("#getOriginToscaElement - origin name: {}", instance.getComponentName()); - ToscaElementTypeEnum elementType = detectToscaType(instance.getOriginType()); - Either getOriginRes; - if (elementType == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE) { - getOriginRes = this.getToscaElement(CapabilityRequirementNameResolver.getActualComponentUid(instance), getFilter()); - - } else { - getOriginRes = nodeTypeOperation.getToscaElement(CapabilityRequirementNameResolver.getActualComponentUid(instance), getFilter()); - } - if (getOriginRes.isRight()) { - log.debug("Failed to get an origin component with uniqueId {}", CapabilityRequirementNameResolver.getActualComponentUid(instance)); - throw new StorageException(getOriginRes.right().value()); - } - return getOriginRes.left().value(); - } - - private ToscaElementTypeEnum detectToscaType(OriginTypeEnum originType) { - log.debug("#detectToscaType - type: {}", originType); - if (nodeTypeSet.contains(originType)){ - return ToscaElementTypeEnum.NODE_TYPE; - } else { - return ToscaElementTypeEnum.TOPOLOGY_TEMPLATE; - } - } - - private ComponentParametersView getFilter() { - ComponentParametersView filter = new ComponentParametersView(); - filter.setIgnoreCapabilities(false); - filter.setIgnoreCapabiltyProperties(false); - filter.setIgnoreRequirements(false); - return filter; - } - public void updateCapReqPropertiesOwnerId(String componentId, TopologyTemplate toscaElement) { - GraphVertex toscaElementV = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse) - .left().on(this::throwStorageException); - updateCapOwnerId(toscaElement, componentId); - updateReqOwnerId(toscaElement, componentId); - updatePropertiesOwnerId(toscaElement, componentId); - topologyTemplateOperation - - .updateFullToscaData(toscaElementV, EdgeLabelEnum.CAPABILITIES, - VertexTypeEnum.CAPABILITIES, toscaElement.getCapabilities()); - topologyTemplateOperation - .updateFullToscaData(toscaElementV, EdgeLabelEnum.REQUIREMENTS, - VertexTypeEnum.REQUIREMENTS, toscaElement.getRequirements()); - topologyTemplateOperation - .updateFullToscaData(toscaElementV, EdgeLabelEnum.PROPERTIES, - VertexTypeEnum.PROPERTIES, toscaElement.getProperties()); - } - - private void updateCapOwnerId(ToscaElement toscaElement, String ownerId) { - if(MapUtils.isNotEmpty(toscaElement.getCapabilities())) { - toscaElement.getCapabilities().values().stream().flatMap(listCapDef -> listCapDef.getListToscaDataDefinition().stream()) - .forEach(capabilityDefinition -> capabilityDefinition.setOwnerId(ownerId)); - } - } - - private void updateReqOwnerId(ToscaElement toscaElement, String ownerId) { - if(MapUtils.isNotEmpty(toscaElement.getRequirements())) { - toscaElement.getRequirements().values().stream().flatMap(listReqDef -> listReqDef.getListToscaDataDefinition().stream()) - .forEach(requirementDefinition -> requirementDefinition.setOwnerId(ownerId)); - } - } - - private void updatePropertiesOwnerId(ToscaElement toscaElement, String ownerId) { - Map properties = toscaElement.getProperties(); - if(MapUtils.isNotEmpty(properties)) { - properties.values().forEach(propertyDataDefinition -> propertyDataDefinition.setParentUniqueId(ownerId)); - } - } - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaDataOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaDataOperation.java deleted file mode 100644 index 0abc0111bf..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaDataOperation.java +++ /dev/null @@ -1,25 +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.jsontitan.operations; - -@org.springframework.stereotype.Component("tosca-data-operation") -public class ToscaDataOperation extends BaseOperation { -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementLifecycleOperation.java deleted file mode 100644 index afad869bb1..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementLifecycleOperation.java +++ /dev/null @@ -1,1583 +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.jsontitan.operations; - -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; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; -import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; -import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.*; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DistributionStatusEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; -import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; -import org.openecomp.sdc.common.log.wrappers.Logger; - -import java.util.*; -import java.util.stream.Collectors; - -@org.springframework.stereotype.Component("tosca-element-lifecycle-operation") - -/** - * Allows to perform lifecycle operations: checkin, checkout, submit for testing, start certification and certification process for tosca element - */ -public class ToscaElementLifecycleOperation extends BaseOperation { - - private static final String FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS = "Failed to delete last state edge. Status is {}. "; - private static final String FAILED_TO_GET_VERTICES = "Failed to get vertices by id {}. Status is {}. "; - public static final String VERSION_DELIMITER = "."; - public static final String VERSION_DELIMITER_REGEXP = "\\."; - - private static final Logger log = Logger.getLogger(ToscaElementLifecycleOperation.class); - - /** - * Performs changing a lifecycle state of tosca element from "checked out" or "ready for certification" to "checked in" - * - * @param currState - * @param toscaElementId - * @param modifierId - * @param ownerId - * @return - */ - public Either checkinToscaELement(LifecycleStateEnum currState, String toscaElementId, String modifierId, String ownerId) { - Either updateResult = null; - Either result = null; - Map vertices = null; - ToscaElementOperation operation; - try { - Either, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckin(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - updateResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); - } else { - vertices = getVerticesRes.left().value(); - updateResult = checkinToscaELement(currState, vertices.get(toscaElementId), vertices.get(ownerId), vertices.get(modifierId), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - } - if (updateResult.isLeft()) { - operation = getToscaElementOperation(vertices.get(toscaElementId).getLabel()); - result = operation.getToscaElement(updateResult.left().value().getUniqueId()); - if (result.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated tosca element {}. Status is {}", toscaElementId, result.right().value()); - } - } else { - result = Either.right(updateResult.right().value()); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during checkin of tosca element {}. {} ", toscaElementId, e.getMessage()); - } - return result; - } - - /** - * Returns vertex presenting owner of tosca element specified by uniqueId - * - * @param toscaElementId - * @return - */ - public Either getToscaElementOwner(String toscaElementId) { - Either result = null; - GraphVertex toscaElement = null; - Either getToscaElementRes = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value())); - } - if (result == null) { - toscaElement = getToscaElementRes.left().value(); - Iterator vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name()); - if (vertices == null || !vertices.hasNext()) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } else { - result = Either.left(convertToUser(vertices.next())); - } - } - return result; - } - - /** - * Returns vertex presenting owner of tosca element specified by uniqueId - * - * @param toscaElement - * @return - */ - public Either getToscaElementOwner(GraphVertex toscaElement) { - Either result = null; - Iterator vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name()); - if (vertices == null || !vertices.hasNext()) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } else { - result = Either.left(convertToUser(vertices.next())); - } - return result; - } - - /** - * Performs checkout of a tosca element - * - * @param toscaElementId - * @param modifierId - * @param ownerId - * @return - */ - public Either checkoutToscaElement(String toscaElementId, String modifierId, String ownerId) { - Either result = null; - Map vertices = null; - try { - Either, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckout(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); - } - if (result == null) { - vertices = getVerticesRes.left().value(); - // update previous component if not certified - StorageOperationStatus status = updatePreviousVersion(vertices.get(toscaElementId), vertices.get(ownerId)); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update vertex with id {} . Status is {}. ", status); - result = Either.right(status); - } - } - if (result == null) { - result = cloneToscaElementForCheckout(vertices.get(toscaElementId), vertices.get(modifierId)); - if (result.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to checkout tosca element {}. Status is {} ", toscaElementId, result.right().value()); - } - - } - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during checkout tosca element {}. {}", toscaElementId, e.getMessage()); - } - return result; - } - - /** - * Performs undo checkout for tosca element - * - * @param toscaElementId - * @return - */ - public Either undoCheckout(String toscaElementId) { - Either result = null; - Either getToscaElementRes = null; - Iterator nextVersionComponentIter = null; - ToscaElementOperation operation; - Vertex preVersionVertex = null; - try { - getToscaElementRes = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.ParseMetadata); - if (getToscaElementRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value())); - } - GraphVertex currVersionV = getToscaElementRes.left().value(); - if (result == null && hasPreviousVersion(currVersionV)) { - // find previous version - nextVersionComponentIter = currVersionV.getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name()); - if (nextVersionComponentIter == null || !nextVersionComponentIter.hasNext()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch previous version of tosca element with name {}. ", currVersionV.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString()); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - if (result == null) { - preVersionVertex = nextVersionComponentIter.next().outVertex(); - StorageOperationStatus updateOldResourceResult = updateOldToscaElementBeforeUndoCheckout(preVersionVertex); - if (updateOldResourceResult != StorageOperationStatus.OK) { - result = Either.right(updateOldResourceResult); - } - } - } - if (result == null) { - StorageOperationStatus updateCatalogRes = updateEdgeToCatalogRootByUndoCheckout((TitanVertex) preVersionVertex, currVersionV); - if (updateCatalogRes != StorageOperationStatus.OK) { - return Either.right(updateCatalogRes); - } - operation = getToscaElementOperation(currVersionV.getLabel()); - result = operation.deleteToscaElement(currVersionV); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during undo checkout tosca element {}. {}", toscaElementId, e.getMessage()); - } - return result; - } - - private boolean hasPreviousVersion(GraphVertex toscaElementVertex) { - boolean hasPreviousVersion = true; - String version = (String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION); - if (StringUtils.isEmpty(version) || "0.1".equals(version)) - hasPreviousVersion = false; - return hasPreviousVersion; - } - - /** - * Performs request certification for tosca element - * - * @param toscaElementId - * @param modifierId - * @param ownerId - * @return - */ - public Either requestCertificationToscaElement(String toscaElementId, String modifierId, String ownerId) { - Either resultUpdate = null; - Either result = null; - GraphVertex toscaElement = null; - GraphVertex modifier = null; - GraphVertex owner; - try { - Either, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); - } - if (result == null) { - toscaElement = getVerticesRes.left().value().get(toscaElementId); - modifier = getVerticesRes.left().value().get(modifierId); - owner = getVerticesRes.left().value().get(ownerId); - - StorageOperationStatus status = handleRelationsUponRequestForCertification(toscaElement, modifier, owner); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - LifecycleStateEnum nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION; - - toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); - toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - - resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); - if (resultUpdate.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); - result = Either.right(resultUpdate.right().value()); - } - } - if (result == null) { - ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); - result = operation.getToscaElement(toscaElement.getUniqueId()); - } - return result; - - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage()); - } - return result; - } - - /** - * Starts certification of tosca element - * - * @param toscaElementId - * @param modifierId - * @param ownerId - * @return - */ - public Either startCertificationToscaElement(String toscaElementId, String modifierId, String ownerId) { - Either result = null; - Either resultUpdate = null; - GraphVertex toscaElement = null; - GraphVertex modifier = null; - GraphVertex owner; - try { - Either, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); - } - if (result == null) { - toscaElement = getVerticesRes.left().value().get(toscaElementId); - modifier = getVerticesRes.left().value().get(modifierId); - owner = getVerticesRes.left().value().get(ownerId); - - StorageOperationStatus status = handleRelationsUponCertification(toscaElement, modifier, owner); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations during certification of tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFICATION_IN_PROGRESS; - - toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); - toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - - resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); - if (resultUpdate.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Couldn't set lifecycle for component {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); - result = Either.right(resultUpdate.right().value()); - } - } - if (result == null) { - ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); - result = operation.getToscaElement(toscaElement.getUniqueId()); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during start certification tosca element {}. {}", toscaElementId, e.getMessage()); - } - return result; - } - - public Either certifyToscaElement(String toscaElementId, String modifierId, String ownerId) { - Either result = null; - Either cloneRes = null; - GraphVertex toscaElement = null; - GraphVertex modifier = null; - GraphVertex certifiedToscaElement = null; - Integer majorVersion = null; - - StorageOperationStatus status; - try { - Either, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); - } - if (result == null) { - toscaElement = getVerticesRes.left().value().get(toscaElementId); - modifier = getVerticesRes.left().value().get(modifierId); - majorVersion = getMajorVersion((String) toscaElement.getMetadataProperty(GraphPropertyEnum.VERSION)); - status = handleRelationsOfPreviousToscaElementBeforeCertifying(toscaElement, modifier, majorVersion); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations of previous tosca element before certifying {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - cloneRes = cloneToscaElementForCertify(toscaElement, modifier, majorVersion); - if (cloneRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element during certification. "); - result = Either.right(cloneRes.right().value()); - } - } - if (result == null) { - certifiedToscaElement = cloneRes.left().value(); - status = handleRelationsOfNewestCertifiedToscaElement(toscaElement, certifiedToscaElement); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations of newest certified tosca element {}. Status is {}. ", certifiedToscaElement.getUniqueId(), status); - } - } - if (result == null) { - return getToscaElementOperation(toscaElement.getLabel()).getToscaElement(certifiedToscaElement.getUniqueId()); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during certification tosca element {}. {}", toscaElementId, e.getMessage()); - } - return result; - } - - /** - * Deletes (marks as deleted) all tosca elements according received name and uuid - * - * @param vertexType - * @param componentType - * @param componentName - * @param uuid - * @return - */ - public Either deleteOldToscaElementVersions(VertexTypeEnum vertexType, ComponentTypeEnum componentType, String componentName, String uuid) { - - Either result = null; - ToscaElementOperation operation = getToscaElementOperation(componentType); - - try { - Map properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.UUID, uuid); - properties.put(GraphPropertyEnum.NAME, componentName); - Either, TitanOperationStatus> getToscaElementsRes = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.ParseMetadata); - if (getToscaElementsRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementsRes.right().value())); - } - if (result == null) { - result = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value()); - } - if (result == null) { - result = Either.left(true); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage()); - } - return result; - } - - /** - * Performs cancelation or failure of certification for received tosca element - * - * @param toscaElementId - * @param modifierId - * @param ownerId - * @param nextState - * @return - */ - public Either cancelOrFailCertification(String toscaElementId, String modifierId, String ownerId, LifecycleStateEnum nextState) { - Either result = null; - StorageOperationStatus status; - ToscaElementOperation operation = null; - GraphVertex toscaElement = null; - GraphVertex modifier = null; - try { - Either, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); - } - if (result == null) { - toscaElement = getVerticesRes.left().value().get(toscaElementId); - modifier = getVerticesRes.left().value().get(modifierId); - operation = getToscaElementOperation(toscaElement.getLabel()); - toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - toscaElement.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifier.getUniqueId()); - toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); - - Either updateVertexRes = titanDao.updateVertex(toscaElement); - if (updateVertexRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update vertex {} . Status is {}. ", toscaElementId, updateVertexRes.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertexRes.right().value())); - } - } - if (result == null) { - // cancel certification process - status = handleRelationsUponCancelCertification(toscaElement, nextState); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations upon cancel certification {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - // fail certification - status = handleRelationsUponFailCertification(toscaElement, nextState); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations upon fail certification {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - result = operation.getToscaElement(toscaElementId); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during cancel or fail certification of tosca element {}. {}. ", toscaElementId, e.getMessage()); - } - return result; - } - - public Either findUser(String userId) { - return findUserVertex(userId); - } - - private Either markToscaElementsAsDeleted(ToscaElementOperation operation, List toscaElements) { - Either result = Either.left(true); - for (GraphVertex resourceToDelete : toscaElements) { - if (!((String) resourceToDelete.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())) { - Either deleteElementRes = operation.markComponentToDelete(resourceToDelete); - if (deleteElementRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete tosca element {}. Status is {}. ", resourceToDelete.getUniqueId(), deleteElementRes.right().value()); - result = Either.right(deleteElementRes.right().value()); - break; - } - } - } - return result; - } - - private StorageOperationStatus handleRelationsOfNewestCertifiedToscaElement(GraphVertex toscaElement, GraphVertex certifiedToscaElement) { - StorageOperationStatus result = null; - Edge foundEdge = null; - Iterator certReqUserEdgeIter = null; - // add rfc relation to preserve follower information - // get user of certification request - certReqUserEdgeIter = toscaElement.getVertex().edges(Direction.IN, GraphEdgeLabels.LAST_STATE.name()); - if (certReqUserEdgeIter == null || !certReqUserEdgeIter.hasNext()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. "); - result = StorageOperationStatus.NOT_FOUND; - } - if (result == null) { - TitanOperationStatus createVersionEdgeStatus = titanDao.createEdge(toscaElement, certifiedToscaElement, EdgeLabelEnum.VERSION, new HashMap<>()); - if (createVersionEdgeStatus != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create version edge from last element {} to new certified element {}. status=", toscaElement.getUniqueId(), certifiedToscaElement.getUniqueId(), - createVersionEdgeStatus); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(createVersionEdgeStatus); - } - } - if (result == null) { - if (certReqUserEdgeIter!=null) { - while (certReqUserEdgeIter.hasNext()) { - Edge edge = certReqUserEdgeIter.next(); - if (((String) titanDao.getProperty(edge, EdgePropertyEnum.STATE)).equals(LifecycleStateEnum.READY_FOR_CERTIFICATION.name())) { - foundEdge = edge; - break; - } - - } - } - if (foundEdge == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. "); - result = StorageOperationStatus.NOT_FOUND; - } - } - if (result == null) { - TitanOperationStatus createEdgeRes = titanDao.createEdge(foundEdge.outVertex(), certifiedToscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, foundEdge); - if (createEdgeRes != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create rfc relation for component {}. status=", certifiedToscaElement.getUniqueId(), createEdgeRes); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes); - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private StorageOperationStatus handleRelationsUponFailCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) { - StorageOperationStatus result = null; - TitanOperationStatus status = null; - Edge originEdge; - Vertex user = null; - if (nextState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) { - // fail certification - // delete relation CERTIFICATION_IN_PROGRESS - Map properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - - Either deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties); - if (deleteResult.isRight()) { - status = deleteResult.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - if (result == null) { - // delete relation READY_FOR_CERTIFICATION - properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION); - deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); - if (deleteResult.isRight()) { - status = deleteResult.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS, status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - // delete relation NOT_CERTIFIED_CHECKIN (in order to change to STATE) - properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); - if (deleteResult.isRight()) { - status = deleteResult.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS, status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - // create new STATE relation NOT_CERTIFIED_CHECKIN - originEdge = deleteResult.left().value(); - user = originEdge.outVertex(); - status = titanDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - // delete relation LAST_MODIFIER (in order to change tester to designer) - deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - // create new LAST_MODIFIER relation - originEdge = deleteResult.left().value(); - status = titanDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.LAST_MODIFIER, originEdge); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private StorageOperationStatus handleRelationsUponCancelCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) { - StorageOperationStatus result = null; - Edge originEdge; - if (nextState == LifecycleStateEnum.READY_FOR_CERTIFICATION) { - // delete relation CERTIFICATION_IN_PROGRESS - Map properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties); - - if (deleteResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", deleteResult.right().value()); - result = StorageOperationStatus.INCONSISTENCY; - } - if (result == null) { - // delete relation READY_FOR_CERTIFICATION (LAST_STATE) - properties.put(GraphPropertyEnum.STATE, nextState); - deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); - - if (deleteResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS, deleteResult.right().value()); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - // create relation READY_FOR_CERTIFICATION (STATE) - originEdge = deleteResult.left().value(); - TitanOperationStatus status = titanDao.createEdge(originEdge.outVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - } - return result; - } - - private StorageOperationStatus handleRelationsOfPreviousToscaElementBeforeCertifying(GraphVertex toscaElement, GraphVertex modifier, Integer majorVersion) { - StorageOperationStatus result = null; - if (majorVersion > 0) { - Either findRes = findLastCertifiedToscaElementVertex(toscaElement); - if (findRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch last certified tosca element {} . Status is {}. ", toscaElement.getMetadataProperty(GraphPropertyEnum.NAME), findRes.right().value()); - result = findRes.right().value(); - } - if (result == null) { - Vertex lastCertifiedVertex = findRes.left().value(); - Map properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, false); - TitanOperationStatus status = titanDao.updateVertexMetadataPropertiesWithJson(lastCertifiedVertex, properties); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set highest version of tosca element {} to [{}]. Status is {}", toscaElement.getUniqueId(), false, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - // remove previous certified version from the catalog - GraphVertex lastCertifiedV = new GraphVertex(); - lastCertifiedV.setVertex((TitanVertex) lastCertifiedVertex); - lastCertifiedV.setUniqueId((String) titanDao.getProperty((TitanVertex) lastCertifiedVertex, GraphPropertyEnum.UNIQUE_ID.getProperty())); - StorageOperationStatus res = updateEdgeToCatalogRoot(null, lastCertifiedV); - if (res != StorageOperationStatus.OK) { - return res; - } - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private StorageOperationStatus handleRelationsUponRequestForCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { - TitanOperationStatus status; - StorageOperationStatus result = null; - - if (((String) toscaElement.getMetadataProperty(GraphPropertyEnum.STATE)).equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - // remove CHECKOUT relation - Either deleteRes = titanDao.deleteEdge(owner, toscaElement, EdgeLabelEnum.STATE); - if (deleteRes.isRight()) { - status = deleteRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete edge. Status is {}. ", status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (result == null) { - // create CHECKIN relation - Map properties = new EnumMap<>(EdgePropertyEnum.class); - properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - status = titanDao.createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, properties); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } - } else { - status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); - if (status != TitanOperationStatus.OK) { - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } - if (result == null) { - // create RFC relation - Map properties = new EnumMap<>(EdgePropertyEnum.class); - properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION); - status = titanDao.createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, properties); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private StorageOperationStatus handleRelationsUponCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { - - StorageOperationStatus result = null; - TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); - if (status != TitanOperationStatus.OK) { - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (result == null) { - Map properties = new EnumMap<>(EdgePropertyEnum.class); - properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } - if (result == null) { - Either updateRelationsRes = updateLastModifierEdge(toscaElement, owner, modifier); - if (updateRelationsRes.isRight()) { - result = updateRelationsRes.right().value(); - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private Either findLastCertifiedToscaElementVertex(GraphVertex toscaElement) { - return findLastCertifiedToscaElementVertexRecursively(toscaElement.getVertex()); - } - - private Either findLastCertifiedToscaElementVertexRecursively(Vertex vertex) { - if (isCertifiedVersion((String) vertex.property(GraphPropertyEnum.VERSION.getProperty()).value())) { - return Either.left(vertex); - } - Iterator edgeIter = vertex.edges(Direction.IN, EdgeLabelEnum.VERSION.name()); - if (!edgeIter.hasNext()) { - return Either.right(StorageOperationStatus.NOT_FOUND); - } - return findLastCertifiedToscaElementVertexRecursively(edgeIter.next().outVertex()); - } - - private boolean isCertifiedVersion(String version) { - String[] versionParts = version.split(VERSION_DELIMITER_REGEXP); - if (Integer.parseInt(versionParts[0]) > 0 && Integer.parseInt(versionParts[1]) == 0) { - return true; - } - return false; - } - - private StorageOperationStatus updateOldToscaElementBeforeUndoCheckout(Vertex previousVersionToscaElement) { - - StorageOperationStatus result = StorageOperationStatus.OK; - String previousVersion = (String) previousVersionToscaElement.property(GraphPropertyEnum.VERSION.getProperty()).value(); - if (!previousVersion.endsWith(".0")) { - try { - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update vertex of previous version of tosca element", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty())); - - Map propertiesToUpdate = new HashMap<>(); - propertiesToUpdate.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true); - Map jsonMetadataMap = JsonParserUtils.toMap((String) previousVersionToscaElement.property(GraphPropertyEnum.METADATA.getProperty()).value()); - jsonMetadataMap.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true); - propertiesToUpdate.put(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.toJson(jsonMetadataMap)); - - titanDao.setVertexProperties(previousVersionToscaElement, propertiesToUpdate); - - Iterator edgesIter = previousVersionToscaElement.edges(Direction.IN, EdgeLabelEnum.LAST_STATE.name()); - if (!edgesIter.hasNext()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch last modifier vertex for tosca element {}. ", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty())); - result = StorageOperationStatus.NOT_FOUND; - } else { - Edge lastStateEdge = edgesIter.next(); - Vertex lastModifier = lastStateEdge.outVertex(); - TitanOperationStatus replaceRes = titanDao.replaceEdgeLabel(lastModifier, previousVersionToscaElement, lastStateEdge, EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE); - if (replaceRes != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to replace label from {} to {}. status = {}", EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE, replaceRes); - result = StorageOperationStatus.INCONSISTENCY; - if (replaceRes != TitanOperationStatus.INVALID_ID) { - result = DaoStatusConverter.convertTitanStatusToStorageStatus(replaceRes); - } - } - - } - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during update previous tosca element {} before undo checkout. {} ", e.getMessage()); - } - } - return result; - } - - private StorageOperationStatus updatePreviousVersion(GraphVertex toscaElementVertex, GraphVertex ownerVertex) { - StorageOperationStatus result = null; - String ownerId = (String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID); - String toscaElementId = toscaElementVertex.getUniqueId(); - if (!toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())) { - toscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, false); - Either updateVertexRes = titanDao.updateVertex(toscaElementVertex); - if (updateVertexRes.isRight()) { - TitanOperationStatus titatStatus = updateVertexRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update tosca element vertex {}. Status is {}", toscaElementVertex.getUniqueId(), titatStatus); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus); - } - Either deleteEdgeRes = null; - if (result == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to replace edge with label {} to label {} from {} to {}. ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId); - - deleteEdgeRes = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE); - if (deleteEdgeRes.isRight()) { - TitanOperationStatus titanStatus = deleteEdgeRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete edge with label {} from {} to {}. Status is {} ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId, titanStatus); - if (!titanStatus.equals(TitanOperationStatus.INVALID_ID)) { - result = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); - } else { - result = StorageOperationStatus.INCONSISTENCY; - } - } - } - if (result == null) { - TitanOperationStatus createEdgeRes = titanDao.createEdge(ownerVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_STATE, deleteEdgeRes.left().value()); - if (createEdgeRes != TitanOperationStatus.OK) { - result = DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes); - } - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private Either cloneToscaElementForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) { - - Either result = null; - Either cloneResult = null; - ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel()); - // check if component with the next version doesn't exist. - Iterator nextVersionComponentIter = toscaElementVertex.getVertex().edges(Direction.OUT, EdgeLabelEnum.VERSION.name()); - if (nextVersionComponentIter != null && nextVersionComponentIter.hasNext()) { - Vertex nextVersionVertex = nextVersionComponentIter.next().inVertex(); - String fetchedVersion = (String) nextVersionVertex.property(GraphPropertyEnum.VERSION.getProperty()).value(); - String fetchedName = (String) nextVersionVertex.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to checkout component {} with version {}. The component with name {} and version {} was fetched from graph as existing following version. ", - toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString(), toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION).toString(), fetchedName, fetchedVersion); - result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS); - } - if (result == null) { - toscaElementVertex.getOrSetDefaultInstantiationTypeForToscaElementJson(); - cloneResult = operation.cloneToscaElement(toscaElementVertex, cloneGraphVertexForCheckout(toscaElementVertex, modifierVertex), modifierVertex); - if (cloneResult.isRight()) { - result = Either.right(cloneResult.right().value()); - } - } - GraphVertex clonedVertex = null; - if (result == null) { - clonedVertex = cloneResult.left().value(); - TitanOperationStatus status = titanDao.createEdge(toscaElementVertex.getVertex(), cloneResult.left().value().getVertex(), EdgeLabelEnum.VERSION, new HashMap<>()); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION, - toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), cloneResult.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (result == null) { - Boolean isHighest = (Boolean) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); - GraphVertex prevVersionInCatalog = (isHighest != null && isHighest) ? null : toscaElementVertex; - StorageOperationStatus updateCatalogRes = updateEdgeToCatalogRoot(clonedVertex, prevVersionInCatalog); - if (updateCatalogRes != StorageOperationStatus.OK) { - return Either.right(updateCatalogRes); - } - result = operation.getToscaElement(cloneResult.left().value().getUniqueId()); - if (result.isRight()) { - return result; - } - ToscaElement toscaElement = result.left().value(); - if (toscaElement.getToscaType() == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE) { - result = handleFixTopologyTemplate(toscaElementVertex, result, operation, clonedVertex, toscaElement); - } - } - - return result; - } - - private Either handleFixTopologyTemplate(GraphVertex toscaElementVertex, Either result, ToscaElementOperation operation, GraphVertex clonedVertex, - ToscaElement toscaElement) { - TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; - Map instInputs = topologyTemplate.getInstInputs(); - Map instGroups = topologyTemplate.getInstGroups(); - Map instArtifactsMap = topologyTemplate.getInstanceArtifacts(); - Map origCompMap = new HashMap<>(); - if (instInputs == null) { - instInputs = new HashMap<>(); - } - if (instGroups == null) { - instGroups = new HashMap<>(); - } - if (instArtifactsMap == null) { - instArtifactsMap = new HashMap<>(); - } - Map instancesMap = topologyTemplate.getComponentInstances(); - boolean isAddInstGroup = instGroups == null || instGroups.isEmpty(); - boolean needUpdateComposition = false; - - if (instancesMap != null && !instancesMap.isEmpty()) { - for (ComponentInstanceDataDefinition vfInst : instancesMap.values()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "vfInst name is {} . OriginType {}. ", vfInst.getName(), vfInst.getOriginType()); - if (vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) { - collectInstanceInputAndGroups(instInputs, instGroups, instArtifactsMap, origCompMap, isAddInstGroup, vfInst, clonedVertex); - } - needUpdateComposition = needUpdateComposition || fixToscaComponentName(vfInst, origCompMap); - if (needUpdateComposition) { - instancesMap.put(vfInst.getUniqueId(), vfInst); - } - } - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before add to graph instInputs {} instGroups {} needUpdateComposition {}", instInputs, instGroups, needUpdateComposition); - if (!instInputs.isEmpty()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before add inst inputs {} ", instInputs == null ? 0 : instInputs.size()); - GraphVertex toscaDataVertex = null; - Either instInpVertexEither = titanDao.getChildVertex(toscaElementVertex, EdgeLabelEnum.INST_INPUTS, JsonParseFlagEnum.ParseJson); - if (instInpVertexEither.isLeft()) { - toscaDataVertex = instInpVertexEither.left().value(); - } - - StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, toscaDataVertex, instInputs); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update instance inputs . Status is {}. ", status); - result = Either.right(status); - return result; - } - - } - if (!instGroups.isEmpty()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before add inst groups {} ", instGroups == null ? 0 : instGroups.size()); - GraphVertex toscaDataVertex = null; - Either instGrVertexEither = titanDao.getChildVertex(toscaElementVertex, EdgeLabelEnum.INST_GROUPS, JsonParseFlagEnum.ParseJson); - if (instGrVertexEither.isLeft()) { - toscaDataVertex = instGrVertexEither.left().value(); - } - - StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, toscaDataVertex, instGroups); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update instance group . Status is {}. ", status); - result = Either.right(status); - return result; - } - - } - if (needUpdateComposition) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before update Instances "); - Map jsonComposition = (Map) clonedVertex.getJson(); - CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - compositionDataDefinition.setComponentInstances(instancesMap); - Either updateElement = titanDao.updateVertex(clonedVertex); - if (updateElement.isRight()) { - TitanOperationStatus status = updateElement.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update instances on metadata vertex . Status is {}. ", status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - } - - result = operation.getToscaElement(clonedVertex.getUniqueId()); - - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "RI map empty on component {}", toscaElement.getUniqueId()); - } - return result; - } - - // TODO remove after jsonModelMigration - public boolean resolveToscaComponentName(ComponentInstanceDataDefinition vfInst, Map origCompMap) { - return fixToscaComponentName(vfInst, origCompMap); - } - - private boolean fixToscaComponentName(ComponentInstanceDataDefinition vfInst, Map origCompMap) { - if (vfInst.getToscaComponentName() == null || vfInst.getToscaComponentName().isEmpty()) { - String ciUid = vfInst.getUniqueId(); - String origCompUid = vfInst.getComponentUid(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "fixToscaComponentName:: Ri id {} . origin component id is {}. type is{} ", ciUid, origCompUid, vfInst.getOriginType()); - ToscaElement origComp = null; - if (!origCompMap.containsKey(origCompUid)) { - Either origCompEither; - if (vfInst.getOriginType() == null || vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) { - origCompEither = topologyTemplateOperation.getToscaElement(origCompUid); - } else { - origCompEither = nodeTypeOperation.getToscaElement(origCompUid); - } - if (origCompEither.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value()); - return false; - } - origComp = origCompEither.left().value(); - origCompMap.put(origCompUid, origComp); - } else { - origComp = origCompMap.get(origCompUid); - } - String toscaName = (String) origComp.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Origin component id is {}. toscaName {}", origCompUid, toscaName); - vfInst.setToscaComponentName(toscaName); - return true; - } - return false; - } - - private void collectInstanceInputAndGroups(Map instInputs, Map instGroups, Map instArtifactsMap, Map origCompMap, - boolean isAddInstGroup, ComponentInstanceDataDefinition vfInst, GraphVertex clonedVertex) { - String ciUid = vfInst.getUniqueId(); - String origCompUid = vfInst.getComponentUid(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "collectInstanceInputAndGroups:: Ri id {} . origin component id is {}. ", ciUid, origCompUid); - TopologyTemplate origComp = null; - if (!origCompMap.containsKey(origCompUid)) { - Either origCompEither = topologyTemplateOperation.getToscaElement(origCompUid); - if (origCompEither.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value()); - return; - } - origComp = (TopologyTemplate) origCompEither.left().value(); - origCompMap.put(origCompUid, origComp); - } else { - origComp = (TopologyTemplate) origCompMap.get(origCompUid); - } - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Orig component {}. ", origComp.getUniqueId()); - - Map origInputs = origComp.getInputs(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Orig component inputs size {}. ", origInputs == null ? 0 : origInputs.size()); - if (origInputs != null) { - if (!instInputs.containsKey(ciUid)) { - MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(origInputs); - instInputs.put(ciUid, instProperties); - } else { - - MapPropertiesDataDefinition instInputMap = instInputs.get(ciUid); - Map instProp = instInputMap.getMapToscaDataDefinition(); - origInputs.forEach((propName, propMap) -> { - if (!instProp.containsKey(propName)) { - instProp.put(propName, propMap); - } - }); - } - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "ComponentInstanseInputs {}. ", instInputs.get(ciUid)); - } - - if (isAddInstGroup) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before create group instance. "); - List filteredGroups = null; - - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check vf groups before filter. Size is {} ", filteredGroups == null ? 0 : filteredGroups.size()); - if (origComp.getGroups() != null && !origComp.getGroups().isEmpty()) { - filteredGroups = origComp.getGroups().values().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList()); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check vf groups . Size is {} ", filteredGroups == null ? 0 : filteredGroups.size()); - } - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check vf groups after filter. Size is {} ", filteredGroups == null ? 0 : filteredGroups.size()); - if (CollectionUtils.isNotEmpty(filteredGroups)) { - MapArtifactDataDefinition instArifacts = null; - if (!instArtifactsMap.containsKey(ciUid)) { - - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "istance artifacts not found "); - - Map deploymentArtifacts = origComp.getDeploymentArtifacts(); - - instArifacts = new MapArtifactDataDefinition(deploymentArtifacts); - addToscaDataDeepElementsBlockToToscaElement(clonedVertex, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArifacts, ciUid); - - instArtifactsMap.put(ciUid, instArifacts); - - } else { - instArifacts = instArtifactsMap.get(ciUid); - } - - if (instArifacts != null) { - Map instDeplArtifMap = instArifacts.getMapToscaDataDefinition(); - - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check group dep artifacts. Size is {} ", instDeplArtifMap == null ? 0 : instDeplArtifMap.values().size()); - Map groupInstanceToCreate = new HashMap<>(); - for (GroupDataDefinition group : filteredGroups) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "create new groupInstance {} ", group.getName()); - GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition(group, vfInst, instDeplArtifMap); - List artifactsUid = new ArrayList<>(); - List artifactsId = new ArrayList<>(); - if (instDeplArtifMap!=null) { - for (ArtifactDataDefinition artifact : instDeplArtifMap.values()) { - Optional op = group.getArtifacts().stream().filter(p -> p.equals(artifact.getGeneratedFromId())).findAny(); - if (op.isPresent()) { - artifactsUid.add(artifact.getArtifactUUID()); - artifactsId.add(artifact.getUniqueId()); - - } - } - } - groupInstance.setGroupInstanceArtifacts(artifactsId); - groupInstance.setGroupInstanceArtifactsUuid(artifactsUid); - groupInstanceToCreate.put(groupInstance.getName(), groupInstance); - } - if (MapUtils.isNotEmpty(groupInstanceToCreate)) { - instGroups.put(vfInst.getUniqueId(), new MapGroupsDataDefinition(groupInstanceToCreate)); - - } - } - } - } - } - - private GraphVertex cloneGraphVertexForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) { - GraphVertex nextVersionToscaElementVertex = new GraphVertex(); - String uniqueId = UniqueIdBuilder.buildComponentUniqueId(); - Map metadataProperties = new HashMap<>(toscaElementVertex.getMetadataProperties()); - nextVersionToscaElementVertex.setMetadataProperties(metadataProperties); - nextVersionToscaElementVertex.setUniqueId(uniqueId); - nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel()); - nextVersionToscaElementVertex.setType(toscaElementVertex.getType()); - - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId); - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name()); - String nextVersion = getNextVersion((String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION)); - if (isFirstCheckoutAfterCertification(nextVersion)) { - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UUID, IdBuilderUtils.generateUUID()); - } - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, nextVersion); - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())) { - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - } - if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) { - nextVersionToscaElementVertex.setMetadataJson(new HashMap<>(toscaElementVertex.getMetadataJson())); - nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties(); - } - long currTime = System.currentTimeMillis(); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CREATION_DATE, currTime); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currTime); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId()); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId()); - if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE) { - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CONFORMANCE_LEVEL, ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel()); - } - - if (!MapUtils.isEmpty(toscaElementVertex.getJson())) { - nextVersionToscaElementVertex.setJson(new HashMap(toscaElementVertex.getJson())); - } - return nextVersionToscaElementVertex; - } - - private Either cloneToscaElementForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) { - Either result; - Either, StorageOperationStatus> deleteResult = null; - GraphVertex clonedToscaElement = null; - result = getToscaElementOperation(toscaElementVertex.getLabel()).cloneToscaElement(toscaElementVertex, cloneGraphVertexForCertify(toscaElementVertex, modifierVertex, majorVersion), modifierVertex); - if (result.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element {} for certification. Sattus is {}. ", toscaElementVertex.getUniqueId(), result.right().value()); - } else { - clonedToscaElement = result.left().value(); - StorageOperationStatus updateEdgeToCatalog = updateEdgeToCatalogRoot(clonedToscaElement, toscaElementVertex); - if (updateEdgeToCatalog != StorageOperationStatus.OK) { - return Either.right(updateEdgeToCatalog); - } - deleteResult = deleteAllPreviousNotCertifiedVersions(toscaElementVertex); - if (deleteResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete all previous npt certified versions of tosca element {}. Status is {}. ", toscaElementVertex.getUniqueId(), deleteResult.right().value()); - result = Either.right(deleteResult.right().value()); - } - } - if (result.isLeft()) { - result = handlePreviousVersionRelation(clonedToscaElement, deleteResult.left().value(), majorVersion); - } - return result; - } - - private Either handlePreviousVersionRelation(GraphVertex clonedToscaElement, List deletedVersions, Integer majorVersion) { - Either result = null; - Vertex previousCertifiedToscaElement = null; - if (majorVersion > 0) { - List firstMinorVersionVertex = deletedVersions.stream().filter(gv -> getMinorVersion((String) gv.getMetadataProperty(GraphPropertyEnum.VERSION)) == 1).collect(Collectors.toList()); - - if (CollectionUtils.isEmpty(firstMinorVersionVertex)) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } else { - previousCertifiedToscaElement = getPreviousCertifiedToscaElement(firstMinorVersionVertex.get(0)); - if (previousCertifiedToscaElement == null) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - if (result == null) { - TitanOperationStatus status = titanDao.createEdge(previousCertifiedToscaElement, clonedToscaElement.getVertex(), EdgeLabelEnum.VERSION, new HashMap<>()); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION, - previousCertifiedToscaElement.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), clonedToscaElement.getUniqueId(), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - } - if (result == null) { - result = Either.left(clonedToscaElement); - } - return result; - } - - private Vertex getPreviousCertifiedToscaElement(GraphVertex graphVertex) { - - Iterator edges = graphVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name()); - if (edges.hasNext()) { - return edges.next().outVertex(); - } - return null; - } - - private Either, StorageOperationStatus> deleteAllPreviousNotCertifiedVersions(GraphVertex toscaElementVertex) { - Either, StorageOperationStatus> result = null; - - ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel()); - List previosVersions = null; - Object uuid = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.UUID); - Object componentName = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NAME); - try { - Map properties = new HashMap<>(); - properties.put(GraphPropertyEnum.UUID, uuid); - properties.put(GraphPropertyEnum.NAME, componentName); - Either, TitanOperationStatus> getToscaElementsRes = titanDao.getByCriteria(toscaElementVertex.getLabel(), properties, JsonParseFlagEnum.ParseMetadata); - if (getToscaElementsRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementsRes.right().value())); - } - if (result == null) { - previosVersions = getToscaElementsRes.left().value(); - Either deleteResult = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value()); - if (deleteResult.isRight()) { - result = Either.right(deleteResult.right().value()); - } - } - if (result == null) { - result = Either.left(previosVersions); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage()); - } - return result; - } - - private GraphVertex cloneGraphVertexForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) { - - GraphVertex nextVersionToscaElementVertex = new GraphVertex(); - String uniqueId = IdBuilderUtils.generateUniqueId(); - Map metadataProperties = new EnumMap<>(toscaElementVertex.getMetadataProperties()); - nextVersionToscaElementVertex.setMetadataProperties(metadataProperties); - nextVersionToscaElementVertex.setUniqueId(uniqueId); - nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel()); - nextVersionToscaElementVertex.setType(toscaElementVertex.getType()); - - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId); - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name()); - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, (majorVersion + 1) + VERSION_DELIMITER + "0"); - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CREATION_DATE, System.currentTimeMillis()); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, null); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId()); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId()); - - if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED)) { - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - } - if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) { - nextVersionToscaElementVertex.setMetadataJson(new HashMap<>(toscaElementVertex.getMetadataJson())); - nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties(); - } - if (!MapUtils.isEmpty(toscaElementVertex.getJson())) { - nextVersionToscaElementVertex.setJson(new HashMap(toscaElementVertex.getJson())); - } - return nextVersionToscaElementVertex; - } - - - private Either checkinToscaELement(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex, LifecycleStateEnum nextState) { - Either updateRelationsRes; - Either result = changeStateToCheckedIn(currState, toscaElementVertex, ownerVertex, modifierVertex); - if (result.isLeft()) { - toscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); - toscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - result = updateToscaElementVertexMetadataPropertiesAndJson(toscaElementVertex); - } - if (result.isLeft()) { - updateRelationsRes = updateLastModifierEdge(toscaElementVertex, ownerVertex, modifierVertex); - if (updateRelationsRes.isRight()) { - result = Either.right(updateRelationsRes.right().value()); - } - } - return result; - } - - private Either updateToscaElementVertexMetadataPropertiesAndJson(GraphVertex toscaElementVertex) { - - Either result; - - Either updateVertexRes = titanDao.updateVertex(toscaElementVertex); - if (updateVertexRes.isRight()) { - TitanOperationStatus titatStatus = updateVertexRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update state of tosca element vertex {} metadata. Status is {}", toscaElementVertex.getUniqueId(), titatStatus); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus)); - } else { - result = Either.left(updateVertexRes.left().value()); - } - return result; - } - - private Either changeStateToCheckedIn(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) { - Either result = null; - LifecycleStateEnum nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN; - String faileToUpdateStateMsg = "Failed to update state of tosca element {}. Status is {}"; - - if (currState == LifecycleStateEnum.READY_FOR_CERTIFICATION) { - // In case of cancel "ready for certification" remove last state edge with "STATE" property equals to "NOT_CERTIFIED_CHECKIN" - Map vertexProperties = new EnumMap<>(GraphPropertyEnum.class); - vertexProperties.put(GraphPropertyEnum.STATE, nextState); - Either deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElementVertex, EdgeLabelEnum.LAST_STATE, vertexProperties); - if (deleteResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId(), deleteResult.right().value()); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "failed to update last state relation"); - result = Either.right(StorageOperationStatus.INCONSISTENCY); - } - } - if (result == null) { - // Remove CHECKOUT relation - Either deleteEdgeResult = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE); - if (deleteEdgeResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteEdgeResult.right().value())); - } - } - if (result == null) { - // Create CHECKIN relation - Map edgeProperties = new EnumMap<>(EdgePropertyEnum.class); - edgeProperties.put(EdgePropertyEnum.STATE, nextState); - TitanOperationStatus createEdgeRes = titanDao.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.STATE, edgeProperties); - if (createEdgeRes != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes)); - } - } - if (result == null) { - result = Either.left(toscaElementVertex); - } - return result; - } - - private Either updateLastModifierEdge(GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) { - Either result = null; - if (!modifierVertex.getMetadataProperties().get(GraphPropertyEnum.USERID).equals(ownerVertex.getMetadataProperties().get(GraphPropertyEnum.USERID))) { - Either deleteEdgeRes = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.LAST_MODIFIER); - if (deleteEdgeRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete last modifier {} to tosca element {}. Edge type is {}", ownerVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteEdgeRes.right().value())); - } - if (result == null) { - TitanOperationStatus createEdgeRes = titanDao.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); - - if (createEdgeRes != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to associate user {} to component {}. Edge type is {}", modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes)); - } else { - result = Either.left(modifierVertex); - } - } - } else { - result = Either.left(ownerVertex); - } - return result; - } - - private Map> prepareParametersToGetVerticesForCheckin(String toscaElementId, String modifierId, String ownerId) { - Map> verticesToGetParameters = new HashMap<>(); - verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseMetadata)); - verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); - verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); - return verticesToGetParameters; - } - - private Map> prepareParametersToGetVerticesForRequestCertification(String toscaElementId, String modifierId, String ownerId) { - Map> verticesToGetParameters = new HashMap<>(); - verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseAll)); - verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); - verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); - return verticesToGetParameters; - } - - private Map> prepareParametersToGetVerticesForCheckout(String toscaElementId, String modifierId, String ownerId) { - //Implementation is currently identical - return prepareParametersToGetVerticesForRequestCertification(toscaElementId,modifierId, ownerId); - } - - private String getNextCertifiedVersion(String version) { - String[] versionParts = version.split(VERSION_DELIMITER_REGEXP); - Integer nextMajorVersion = Integer.parseInt(versionParts[0]) + 1; - return nextMajorVersion + VERSION_DELIMITER + "0"; - } - - private String getNextVersion(String currVersion) { - String[] versionParts = currVersion.split(VERSION_DELIMITER_REGEXP); - Integer minorVersion = Integer.parseInt(versionParts[1]) + 1; - return versionParts[0] + VERSION_DELIMITER + minorVersion; - } - - private Integer getMinorVersion(String version) { - String[] versionParts = version.split(VERSION_DELIMITER_REGEXP); - return Integer.parseInt(versionParts[1]); - } - - private Integer getMajorVersion(String version) { - String[] versionParts = version.split(VERSION_DELIMITER_REGEXP); - return Integer.parseInt(versionParts[0]); - } - - private boolean isFirstCheckoutAfterCertification(String version) { - return (Integer.parseInt(version.split(VERSION_DELIMITER_REGEXP)[0]) != 0 && Integer.parseInt(version.split(VERSION_DELIMITER_REGEXP)[1]) == 1); - } - - public Either forceCerificationOfToscaElement(String toscaElementId, String modifierId, String ownerId, String currVersion) { - Either resultUpdate = null; - Either result = null; - GraphVertex toscaElement = null; - GraphVertex modifier = null; - GraphVertex owner; - try { - Either, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); - } - if (result == null) { - toscaElement = getVerticesRes.left().value().get(toscaElementId); - modifier = getVerticesRes.left().value().get(modifierId); - owner = getVerticesRes.left().value().get(ownerId); - - StorageOperationStatus status = handleRelationsUponForceCertification(toscaElement, modifier, owner); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFIED; - - toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - toscaElement.addMetadataProperty(GraphPropertyEnum.VERSION, getNextCertifiedVersion(currVersion)); - - resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); - if (resultUpdate.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); - result = Either.right(resultUpdate.right().value()); - } - } - if (result == null) { - ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); - result = operation.getToscaElement(toscaElement.getUniqueId()); - } - return result; - - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage()); - } - return result; - } - - private StorageOperationStatus handleRelationsUponForceCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { - - StorageOperationStatus result = null; - TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); - if (status != TitanOperationStatus.OK) { - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (result == null) { - Map properties = new EnumMap<>(EdgePropertyEnum.class); - properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFIED); - status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private StorageOperationStatus updateEdgeToCatalogRootByUndoCheckout(TitanVertex preV, GraphVertex curV) { - if (preV == null) { - return updateEdgeToCatalogRoot(null, curV); - } - String uniqueIdPreVer = (String) titanDao.getProperty((TitanVertex) preV, GraphPropertyEnum.UNIQUE_ID.getProperty()); - LifecycleStateEnum state = LifecycleStateEnum.findState((String) titanDao.getProperty(preV, GraphPropertyEnum.STATE.getProperty())); - if (state == LifecycleStateEnum.CERTIFIED) { - return updateEdgeToCatalogRoot(null, curV); - } - return titanDao.getVertexById(uniqueIdPreVer) - .either(l -> updateEdgeToCatalogRoot(l, curV), - DaoStatusConverter::convertTitanStatusToStorageStatus); - } - - private StorageOperationStatus updateEdgeToCatalogRoot(GraphVertex newVersionV, GraphVertex prevVersionV) { - Either catalog = titanDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT); - if (catalog.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch catalog vertex. error {}", catalog.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(catalog.right().value()); - } - GraphVertex catalogV = catalog.left().value(); - if (newVersionV != null) { - Boolean isAbstract = (Boolean) newVersionV.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT); - - if ( isAbstract == null || !isAbstract ) { - // no new vertex, only delete previous - TitanOperationStatus result = titanDao.createEdge(catalogV, newVersionV, EdgeLabelEnum.CATALOG_ELEMENT, null); - if (result != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge from {} to catalog vertex. error {}", newVersionV.getUniqueId(), result); - return DaoStatusConverter.convertTitanStatusToStorageStatus(result); - } - } - } - if (prevVersionV != null) { - Boolean isAbstract = (Boolean) prevVersionV.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT); - if (isAbstract == null || !isAbstract) { - // if prev == null -> new resource was added - Either deleteResult = titanDao.deleteEdge(catalogV, prevVersionV, EdgeLabelEnum.CATALOG_ELEMENT); - if (deleteResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete edge from {} to catalog vertex. error {}", prevVersionV.getUniqueId(), deleteResult.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteResult.right().value()); - } - } - } - return StorageOperationStatus.OK; - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java deleted file mode 100644 index f700c2eb69..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java +++ /dev/null @@ -1,1360 +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.jsontitan.operations; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import fj.data.Either; -import org.apache.commons.collections.CollectionUtils; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; -import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.catalog.CatalogComponent; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.category.SubCategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.common.util.ValidationUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.StopWatch; - -import java.lang.reflect.Type; -import java.util.*; -import java.util.Map.Entry; -import java.util.stream.Collectors; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public abstract class ToscaElementOperation extends BaseOperation { - private static final String FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR = "failed to fetch {} for tosca element with id {}, error {}"; - - private static final String CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS = "Cannot find user {} in the graph. status is {}"; - - private static final String FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS = "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. "; - - private static Logger log = Logger.getLogger(ToscaElementOperation.class.getName()); - - private static final Gson gson = new Gson(); - - @Autowired - protected CategoryOperation categoryOperation; - - protected Gson getGson() { - return gson; - } - - - protected Either getComponentByLabelAndId(String uniqueId, ToscaElementTypeEnum nodeType, JsonParseFlagEnum parseFlag) { - - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesToMatch.put(GraphPropertyEnum.UNIQUE_ID, uniqueId); - - VertexTypeEnum vertexType = ToscaElementTypeEnum.getVertexTypeByToscaType(nodeType); - Either, TitanOperationStatus> getResponse = titanDao.getByCriteria(vertexType, propertiesToMatch, parseFlag); - if (getResponse.isRight()) { - log.debug("Couldn't fetch component with type {} and unique id {}, error: {}", vertexType, uniqueId, getResponse.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value())); - - } - List componentList = getResponse.left().value(); - if (componentList.isEmpty()) { - log.debug("Component with type {} and unique id {} was not found", vertexType, uniqueId); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - GraphVertex vertexG = componentList.get(0); - return Either.left(vertexG); - } - - public Either getToscaElement(String uniqueId) { - return getToscaElement(uniqueId, new ComponentParametersView()); - } - - public Either markComponentToDelete(GraphVertex componentToDelete) { - Either result = null; - - Boolean isDeleted = (Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_DELETED); - if (isDeleted != null && isDeleted && !(Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION)) { - // component already marked for delete - result = Either.left(componentToDelete); - return result; - } else { - - componentToDelete.addMetadataProperty(GraphPropertyEnum.IS_DELETED, Boolean.TRUE); - componentToDelete.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - - Either updateNode = titanDao.updateVertex(componentToDelete); - - StorageOperationStatus updateComponent; - if (updateNode.isRight()) { - log.debug("Failed to update component {}. status is {}", componentToDelete.getUniqueId(), updateNode.right().value()); - updateComponent = DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()); - result = Either.right(updateComponent); - return result; - } - - result = Either.left(componentToDelete); - return result; - } - } - - /** - * Performs a shadow clone of previousToscaElement - * - * @param previousToscaElement - * @param nextToscaElement - * @param user - * @return - */ - public Either cloneToscaElement(GraphVertex previousToscaElement, GraphVertex nextToscaElement, GraphVertex user) { - - Either result = null; - GraphVertex createdToscaElementVertex = null; - TitanOperationStatus status; - - Either createNextVersionRes = titanDao.createVertex(nextToscaElement); - if (createNextVersionRes.isRight()) { - status = createNextVersionRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create tosca element vertex {} with version {} on graph. Status is {}. ", previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), - previousToscaElement.getMetadataProperty(GraphPropertyEnum.VERSION), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - createdToscaElementVertex = createNextVersionRes.left().value(); - Map properties = new HashMap<>(); - properties.put(EdgePropertyEnum.STATE, createdToscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE)); - status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.STATE, properties); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.STATE, user.getUniqueId(), - previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (result == null) { - status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.LAST_MODIFIER, user.getUniqueId(), - nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (result == null) { - status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.CREATOR, new HashMap<>()); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.CREATOR, user.getUniqueId(), - nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (result == null) { - Iterator edgesToCopyIter = previousToscaElement.getVertex().edges(Direction.OUT); - while (edgesToCopyIter.hasNext()) { - Edge currEdge = edgesToCopyIter.next(); - Vertex currVertex = currEdge.inVertex(); - status = titanDao.createEdge(createdToscaElementVertex.getVertex(), currVertex, EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()), currEdge); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from tosca element vertex {} to vertex with label {} on graph. Status is {}. ", currEdge.label(), createdToscaElementVertex.getUniqueId(), - currVertex.property(GraphPropertyEnum.LABEL.getProperty()), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - break; - } - } - } - - if (result == null) { - result = Either.left(createdToscaElementVertex); - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element {} with the name {}. ", previousToscaElement.getUniqueId(), previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME)); - } - return result; - } - - protected TitanOperationStatus setLastModifierFromGraph(GraphVertex componentV, ToscaElement toscaElement) { - Either parentVertex = titanDao.getParentVertex(componentV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse); - if (parentVertex.isRight()) { - log.debug("Failed to fetch last modifier for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value()); - return parentVertex.right().value(); - } - GraphVertex userV = parentVertex.left().value(); - String userId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); - toscaElement.setLastUpdaterUserId(userId); - toscaElement.setLastUpdaterFullName(buildFullName(userV)); - return TitanOperationStatus.OK; - } - - public String buildFullName(GraphVertex userV) { - - String fullName = (String) userV.getMetadataProperty(GraphPropertyEnum.FIRST_NAME); - if (fullName == null) { - fullName = ""; - } else { - fullName = fullName + " "; - } - String lastName = (String) userV.getMetadataProperty(GraphPropertyEnum.LAST_NAME); - if (lastName != null) { - fullName += lastName; - } - return fullName; - } - - protected TitanOperationStatus setCreatorFromGraph(GraphVertex componentV, ToscaElement toscaElement) { - Either parentVertex = titanDao.getParentVertex(componentV, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse); - if (parentVertex.isRight()) { - log.debug("Failed to fetch creator for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value()); - return parentVertex.right().value(); - } - GraphVertex userV = parentVertex.left().value(); - String creatorUserId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); - toscaElement.setCreatorUserId(creatorUserId); - toscaElement.setCreatorFullName(buildFullName(userV)); - - return TitanOperationStatus.OK; - } - - protected T getResourceMetaDataFromResource(T toscaElement) { - if (toscaElement.getNormalizedName() == null || toscaElement.getNormalizedName().isEmpty()) { - toscaElement.setNormalizedName(ValidationUtils.normaliseComponentName(toscaElement.getName())); - } - if (toscaElement.getSystemName() == null || toscaElement.getSystemName().isEmpty()) { - toscaElement.setSystemName(ValidationUtils.convertToSystemName(toscaElement.getName())); - } - - LifecycleStateEnum lifecycleStateEnum = toscaElement.getLifecycleState(); - if (lifecycleStateEnum == null) { - toscaElement.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - } - long currentDate = System.currentTimeMillis(); - if (toscaElement.getCreationDate() == null) { - toscaElement.setCreationDate(currentDate); - } - toscaElement.setLastUpdateDate(currentDate); - - return toscaElement; - } - - protected void fillCommonMetadata(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { - if (toscaElement.isHighestVersion() == null) { - toscaElement.setHighestVersion(true); - } - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_DELETED, toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, toscaElement.getMetadataValueOrDefault(JsonPresentationFields.HIGHEST_VERSION, Boolean.TRUE)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.STATE, toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_TYPE)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.VERSION, toscaElement.getMetadataValue(JsonPresentationFields.VERSION)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME, toscaElement.getMetadataValue(JsonPresentationFields.NORMALIZED_NAME)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, toscaElement.getMetadataValue(JsonPresentationFields.UNIQUE_ID)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UUID, toscaElement.getMetadataValue(JsonPresentationFields.UUID)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.INVARIANT_UUID, toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NAME, toscaElement.getMetadataValue(JsonPresentationFields.NAME)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.SYSTEM_NAME, toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_ARCHIVED)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME, toscaElement.getMetadataValue(JsonPresentationFields.ARCHIVE_TIME)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_VSP_ARCHIVED)); - toscaElement.getMetadata().entrySet().stream().filter(e -> e.getValue() != null).forEach(e -> nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.getByPresentation(e.getKey()), e.getValue())); - - nodeTypeVertex.setUniqueId(toscaElement.getUniqueId()); - nodeTypeVertex.setType(toscaElement.getComponentType()); - - } - - protected StorageOperationStatus assosiateToUsers(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { - // handle user - String userId = toscaElement.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 DaoStatusConverter.convertTitanStatusToStorageStatus(status); - - } - GraphVertex creatorVertex = findUser.left().value(); - GraphVertex updaterVertex = creatorVertex; - String updaterId = toscaElement.getLastUpdaterUserId(); - if (updaterId != null && !updaterId.equals(userId)) { - findUser = findUserVertex(updaterId); - if (findUser.isRight()) { - TitanOperationStatus status = findUser.right().value(); - log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, userId, status); - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } else { - updaterVertex = findUser.left().value(); - } - } - Map props = new EnumMap<>(EdgePropertyEnum.class); - props.put(EdgePropertyEnum.STATE, (String) toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); - - TitanOperationStatus result = titanDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.STATE, props); - log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.STATE); - if (TitanOperationStatus.OK != result) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(result); - } - result = titanDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.LAST_MODIFIER, null); - log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); - if (!result.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); - return DaoStatusConverter.convertTitanStatusToStorageStatus(result); - } - - toscaElement.setLastUpdaterUserId(toscaElement.getCreatorUserId()); - toscaElement.setLastUpdaterFullName(toscaElement.getCreatorFullName()); - - result = titanDao.createEdge(creatorVertex, nodeTypeVertex, EdgeLabelEnum.CREATOR, null); - log.debug("After associating user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR); - if (!result.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR); - return DaoStatusConverter.convertTitanStatusToStorageStatus(result); - } - return StorageOperationStatus.OK; - } - - protected StorageOperationStatus assosiateResourceMetadataToCategory(GraphVertex nodeTypeVertex, ToscaElement nodeType) { - String subcategoryName = nodeType.getCategories().get(0).getSubcategories().get(0).getName(); - String categoryName = nodeType.getCategories().get(0).getName(); - Either getCategoryVertex = getResourceCategoryVertex(nodeType.getUniqueId(), subcategoryName, categoryName); - - if (getCategoryVertex.isRight()) { - return getCategoryVertex.right().value(); - } - - GraphVertex subCategoryV = getCategoryVertex.left().value(); - - TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, subCategoryV, EdgeLabelEnum.CATEGORY, new HashMap<>()); - if (createEdge != TitanOperationStatus.OK) { - log.trace("Failed to associate resource {} to category {} with id {}", nodeType.getUniqueId(), subcategoryName, subCategoryV.getUniqueId()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge); - } - return StorageOperationStatus.OK; - } - - protected Either getResourceCategoryVertex(String elementId, String subcategoryName, String categoryName) { - Either category = categoryOperation.getCategory(categoryName, VertexTypeEnum.RESOURCE_CATEGORY); - if (category.isRight()) { - log.trace("Failed to fetch category {} for resource {} error {}", categoryName, elementId, category.right().value()); - return Either.right(category.right().value()); - } - GraphVertex categoryV = category.left().value(); - - if (subcategoryName != null) { - Either subCategory = categoryOperation.getSubCategoryForCategory(categoryV, subcategoryName); - if (subCategory.isRight()) { - log.trace("Failed to fetch subcategory {} of category for resource {} error {}", subcategoryName, categoryName, elementId, subCategory.right().value()); - return Either.right(subCategory.right().value()); - } - - GraphVertex subCategoryV = subCategory.left().value(); - return Either.left(subCategoryV); - } - return Either.left(categoryV); - } - - private StorageOperationStatus associateArtifactsToResource(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { - Map artifacts = toscaElement.getArtifacts(); - Either status; - if (artifacts != null) { - artifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); - a.setUniqueId(uniqueId); - }); - status = associateElementToData(nodeTypeVertex, VertexTypeEnum.ARTIFACTS, EdgeLabelEnum.ARTIFACTS, artifacts); - if (status.isRight()) { - return status.right().value(); - } - } - Map toscaArtifacts = toscaElement.getToscaArtifacts(); - if (toscaArtifacts != null) { - toscaArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); - a.setUniqueId(uniqueId); - }); - status = associateElementToData(nodeTypeVertex, VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, toscaArtifacts); - if (status.isRight()) { - return status.right().value(); - } - } - Map deploymentArtifacts = toscaElement.getDeploymentArtifacts(); - if (deploymentArtifacts != null) { - deploymentArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); - a.setUniqueId(uniqueId); - }); - status = associateElementToData(nodeTypeVertex, VertexTypeEnum.DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS, deploymentArtifacts); - if (status.isRight()) { - return status.right().value(); - } - } - return StorageOperationStatus.OK; - } - - protected TitanOperationStatus disassociateAndDeleteCommonElements(GraphVertex toscaElementVertex) { - TitanOperationStatus status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ARTIFACTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disaccociate artifact for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.TOSCA_ARTIFACTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disaccociate tosca artifact for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to deployment artifact for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.PROPERTIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disaccociate properties for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disaccociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disaccociate additional information for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disaccociate capabilities for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - return TitanOperationStatus.OK; - } - - protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement, List derivedResources) { - - StorageOperationStatus associateUsers = assosiateToUsers(nodeTypeVertex, toscaElement); - if (associateUsers != StorageOperationStatus.OK) { - return associateUsers; - } - StorageOperationStatus associateArtifacts = associateArtifactsToResource(nodeTypeVertex, toscaElement); - if (associateArtifacts != StorageOperationStatus.OK) { - return associateArtifacts; - } - StorageOperationStatus associateProperties = associatePropertiesToResource(nodeTypeVertex, toscaElement, derivedResources); - if (associateProperties != StorageOperationStatus.OK) { - return associateProperties; - } - StorageOperationStatus associateAdditionaInfo = associateAdditionalInfoToResource(nodeTypeVertex, toscaElement); - if (associateAdditionaInfo != StorageOperationStatus.OK) { - return associateAdditionaInfo; - } - if (needConnectToCatalog(toscaElement)) { - StorageOperationStatus associateToCatalog = associateToCatalogRoot(nodeTypeVertex); - if (associateToCatalog != StorageOperationStatus.OK) { - return associateToCatalog; - } - } - return StorageOperationStatus.OK; - } - - private boolean needConnectToCatalog(ToscaElement toscaElement) { - Boolean isAbstract = (Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT); - if (isAbstract != null && isAbstract) { - return false; - } - return toscaElement.isHighestVersion(); - } - - private StorageOperationStatus associateToCatalogRoot(GraphVertex nodeTypeVertex) { - Either catalog = titanDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT); - if (catalog.isRight()) { - log.debug("Failed to fetch catalog vertex. error {}", catalog.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(catalog.right().value()); - } - TitanOperationStatus createEdge = titanDao.createEdge(catalog.left().value(), nodeTypeVertex, EdgeLabelEnum.CATALOG_ELEMENT, null); - - return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge); - } - - protected StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType, List derivedResources) { - // Note : currently only one derived supported!!!! - Either, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.PROPERTIES); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map propertiesAll = dataFromDerived.left().value(); - - Map properties = nodeType.getProperties(); - - if (properties != null) { - properties.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { - String uid = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId(), p.getName()); - p.setUniqueId(uid); - }); - - Either, String> eitherMerged = ToscaDataDefinition.mergeDataMaps(propertiesAll, properties); - if (eitherMerged.isRight()) { - // TODO re-factor error handling - moving BL to operation resulted in loss of info about the invalid property - log.debug("property {} cannot be overriden", eitherMerged.right().value()); - return StorageOperationStatus.INVALID_PROPERTY; - } - } - if (!propertiesAll.isEmpty()) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES, EdgeLabelEnum.PROPERTIES, propertiesAll); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateAdditionalInfoToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType) { - Map additionalInformation = nodeType.getAdditionalInformation(); - if (additionalInformation != null) { - Either assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, additionalInformation); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - protected Either, StorageOperationStatus> getDataFromDerived(List derivedResources, EdgeLabelEnum edge) { - Map propertiesAll = new HashMap<>(); - - if (derivedResources != null && !derivedResources.isEmpty()) { - for (GraphVertex derived : derivedResources) { - Either, TitanOperationStatus> derivedProperties = titanDao.getChildrenVertecies(derived, edge, JsonParseFlagEnum.ParseJson); - if (derivedProperties.isRight()) { - if (derivedProperties.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to get properties for derived from {} error {}", derived.getUniqueId(), derivedProperties.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(derivedProperties.right().value())); - } else { - continue; - } - } - List propList = derivedProperties.left().value(); - for (GraphVertex propV : propList) { - Map propertiesFromDerived = (Map) propV.getJson(); - if (propertiesFromDerived != null) { - propertiesFromDerived.entrySet().forEach(x -> x.getValue().setOwnerIdIfEmpty(derived.getUniqueId())); - propertiesAll.putAll(propertiesFromDerived); - } - } - } - } - return Either.left(propertiesAll); - } - - protected TitanOperationStatus setArtifactsFromGraph(GraphVertex componentV, ToscaElement toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ARTIFACTS); - if (result.isLeft()) { - toscaElement.setArtifacts(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - result = getDataFromGraph(componentV, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); - if (result.isLeft()) { - toscaElement.setDeploymentArtifacts(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - result = getDataFromGraph(componentV, EdgeLabelEnum.TOSCA_ARTIFACTS); - if (result.isLeft()) { - toscaElement.setToscaArtifacts(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - protected TitanOperationStatus setAllVersions(GraphVertex componentV, ToscaElement toscaElement) { - Map allVersion = new HashMap<>(); - - allVersion.put((String) componentV.getMetadataProperty(GraphPropertyEnum.VERSION), componentV.getUniqueId()); - ArrayList allChildrenAndParants = new ArrayList<>(); - Either childResourceRes = titanDao.getChildVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); - while (childResourceRes.isLeft()) { - GraphVertex child = childResourceRes.left().value(); - allChildrenAndParants.add(child); - childResourceRes = titanDao.getChildVertex(child, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); - } - TitanOperationStatus operationStatus = childResourceRes.right().value(); - - if (operationStatus != TitanOperationStatus.NOT_FOUND) { - return operationStatus; - } else { - Either parentResourceRes = titanDao.getParentVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); - while (parentResourceRes.isLeft()) { - GraphVertex parent = parentResourceRes.left().value(); - allChildrenAndParants.add(parent); - parentResourceRes = titanDao.getParentVertex(parent, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); - } - operationStatus = parentResourceRes.right().value(); - if (operationStatus != TitanOperationStatus.NOT_FOUND) { - return operationStatus; - } else { - allChildrenAndParants.stream().filter(vertex -> { - Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED); - return (isDeleted == null || !isDeleted); - }).forEach(vertex -> allVersion.put((String) vertex.getMetadataProperty(GraphPropertyEnum.VERSION), vertex.getUniqueId())); - - toscaElement.setAllVersions(allVersion); - return TitanOperationStatus.OK; - } - } - } - - protected Either, StorageOperationStatus> getFollowedComponent(String userId, Set lifecycleStates, Set lastStateStates, ComponentTypeEnum neededType) { - - Either, StorageOperationStatus> result = null; - - Map props = null; - - if (userId != null) { - props = new EnumMap<>(GraphPropertyEnum.class); - // for Designer retrieve specific user - props.put(GraphPropertyEnum.USERID, userId); - } - // in case of user id == null -> get all users by label - // for Tester and Admin retrieve all users - Either, TitanOperationStatus> usersByCriteria = titanDao.getByCriteria(VertexTypeEnum.USER, props, JsonParseFlagEnum.NoParse); - if (usersByCriteria.isRight()) { - log.debug("Failed to fetch users by criteria {} error {}", props, usersByCriteria.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(usersByCriteria.right().value())); - } - List users = usersByCriteria.left().value(); - - List components = new ArrayList<>(); - List componentsPerUser; - for (GraphVertex userV : users) { - - HashSet ids = new HashSet<>(); - Either, TitanOperationStatus> childrenVertecies = titanDao.getChildrenVertecies(userV, EdgeLabelEnum.STATE, JsonParseFlagEnum.NoParse); - if (childrenVertecies.isRight() && childrenVertecies.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.STATE, childrenVertecies.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value())); - } - - // get all resource with current state - if (childrenVertecies.isLeft()) { - componentsPerUser = fetchComponents(lifecycleStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.STATE); - - if (componentsPerUser != null) { - for (T comp : componentsPerUser) { - ids.add(comp.getUniqueId()); - components.add(comp); - } - } - } - if (lastStateStates != null && !lastStateStates.isEmpty()) { - // get all resource with last state - childrenVertecies = titanDao.getChildrenVertecies(userV, EdgeLabelEnum.LAST_STATE, JsonParseFlagEnum.NoParse); - if (childrenVertecies.isRight() && childrenVertecies.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.LAST_STATE, childrenVertecies.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value())); - } - if (childrenVertecies.isLeft()) { - boolean isFirst; - componentsPerUser = fetchComponents(lastStateStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.LAST_STATE); - if (componentsPerUser != null) { - for (T comp : componentsPerUser) { - isFirst = true; - - if (ids.contains(comp.getUniqueId())) { - isFirst = false; - } - if (isFirst) { - components.add(comp); - } - - } - } - } - } - - } // whlile users - ; - result = Either.left(components); - return result; - - } - - private List fetchComponents(Set lifecycleStates, List vertices, ComponentTypeEnum neededType, EdgeLabelEnum edgelabel) { - List components = new ArrayList<>(); - for (GraphVertex node : vertices) { - - Iterator edges = node.getVertex().edges(Direction.IN, edgelabel.name()); - while (edges.hasNext()) { - Edge edge = edges.next(); - String stateStr = (String) titanDao.getProperty(edge, EdgePropertyEnum.STATE); - - LifecycleStateEnum nodeState = LifecycleStateEnum.findState(stateStr); - if (nodeState == null) { - log.debug("no supported STATE {} for element {}", stateStr, node.getUniqueId()); - continue; - } - if (lifecycleStates != null && lifecycleStates.contains(nodeState)) { - - Boolean isDeleted = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_DELETED); - Boolean isArchived = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED); - if (isDeleted != null && isDeleted || isArchived != null && isArchived) { - log.trace("Deleted/Archived element {}, discard", node.getUniqueId()); - continue; - } - - Boolean isHighest = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); - if (isHighest) { - - ComponentTypeEnum componentType = node.getType(); - // get only latest versions - - if (componentType == null) { - log.debug("No supported type {} for vertex {}", componentType, node.getUniqueId()); - continue; - } - if (neededType == componentType) { - switch (componentType) { - case SERVICE: - case PRODUCT: - handleNode(components, node, componentType); - break; - case RESOURCE: - Boolean isAbtract = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT); - if (isAbtract == null || !isAbtract) { - handleNode(components, node, componentType); - } // if not abstract - break; - default: - log.debug("not supported node type {}", componentType); - break; - }// case - } // needed type - } - } // if - } // while edges - } // while resources - return components; - } - - protected void handleNode(List components, GraphVertex vertexComponent, ComponentTypeEnum nodeType) { - - Either component = getLightComponent(vertexComponent, nodeType, new ComponentParametersView(true)); - if (component.isRight()) { - log.debug("Failed to get component for id = {} error : {} skip resource", vertexComponent.getUniqueId(), component.right().value()); - } else { - components.add(component.left().value()); - } - } - - protected Either getLightComponent(String componentUid, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) { - Either getVertexRes = titanDao.getVertexById(componentUid); - if (getVertexRes.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexRes.right().value())); - } - return getLightComponent(getVertexRes.left().value(), nodeType, parametersFilter); - } - - protected Either getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) { - - log.trace("Starting to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId()); - - titanDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata); - - T toscaElement = convertToComponent(vertexComponent); - - TitanOperationStatus status = setCreatorFromGraph(vertexComponent, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - status = setLastModifierFromGraph(vertexComponent, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = setCategoriesFromGraph(vertexComponent, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (!parametersFilter.isIgnoreAllVersions()) { - status = setAllVersions(vertexComponent, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!parametersFilter.isIgnoreCapabilities()) { - status = setCapabilitiesFromGraph(vertexComponent, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!parametersFilter.isIgnoreRequirements()) { - status = setRequirementsFromGraph(vertexComponent, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - log.debug("Ended to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId()); - return Either.left(toscaElement); - } - - @SuppressWarnings("unchecked") - protected T convertToComponent(GraphVertex componentV) { - ToscaElement toscaElement = null; - VertexTypeEnum label = componentV.getLabel(); - switch (label) { - case NODE_TYPE: - toscaElement = new NodeType(); - break; - case TOPOLOGY_TEMPLATE: - toscaElement = new TopologyTemplate(); - break; - default: - log.debug("Not supported tosca type {}", label); - break; - } - - Map jsonMetada = componentV.getMetadataJson(); - if (toscaElement != null) { - toscaElement.setMetadata(jsonMetada); - } - return (T) toscaElement; - } - - protected TitanOperationStatus setResourceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) { - - Either childVertex = titanDao.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); - if (childVertex.isRight()) { - log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(), childVertex.right().value()); - return childVertex.right().value(); - } - Vertex subCategoryV = childVertex.left().value(); - catalogComponent.setSubCategoryNormalizedName((String) subCategoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); - Either parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); - Vertex categoryV = parentVertex.left().value(); - catalogComponent.setCategoryNormalizedName((String) categoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); - - return TitanOperationStatus.OK; - } - - protected TitanOperationStatus setServiceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) { - Either childVertex = titanDao.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); - if (childVertex.isRight()) { - log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(), childVertex.right().value()); - return childVertex.right().value(); - } - Vertex categoryV = childVertex.left().value(); - catalogComponent.setCategoryNormalizedName((String) categoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); - - return TitanOperationStatus.OK; - } - - protected TitanOperationStatus setResourceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement) { - List categories = new ArrayList<>(); - SubCategoryDefinition subcategory; - - Either childVertex = titanDao.getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); - if (childVertex.isRight()) { - log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value()); - return childVertex.right().value(); - } - GraphVertex subCategoryV = childVertex.left().value(); - Map metadataProperties = subCategoryV.getMetadataProperties(); - subcategory = new SubCategoryDefinition(); - subcategory.setUniqueId(subCategoryV.getUniqueId()); - subcategory.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME)); - subcategory.setName((String) metadataProperties.get(GraphPropertyEnum.NAME)); - - Type listTypeSubcat = new TypeToken>() { - }.getType(); - List iconsfromJsonSubcat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeSubcat); - subcategory.setIcons(iconsfromJsonSubcat); - - Either parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); - if (parentVertex.isRight()) { - log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value()); - return childVertex.right().value(); - } - GraphVertex categoryV = parentVertex.left().value(); - metadataProperties = categoryV.getMetadataProperties(); - - CategoryDefinition category = new CategoryDefinition(); - category.setUniqueId(categoryV.getUniqueId()); - category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME)); - category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME)); - - Type listTypeCat = new TypeToken>() { - }.getType(); - List iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeCat); - category.setIcons(iconsfromJsonCat); - - category.addSubCategory(subcategory); - categories.add(category); - toscaElement.setCategories(categories); - - return TitanOperationStatus.OK; - } - - public Either updateToscaElement(T toscaElementToUpdate, GraphVertex elementV, ComponentParametersView filterResult) { - Either result = null; - - log.debug("In updateToscaElement. received component uid = {}", (toscaElementToUpdate == null ? null : toscaElementToUpdate.getUniqueId())); - if (toscaElementToUpdate == null) { - log.error("Service object is null"); - result = Either.right(StorageOperationStatus.BAD_REQUEST); - return result; - } - - String modifierUserId = toscaElementToUpdate.getLastUpdaterUserId(); - if (modifierUserId == null || modifierUserId.isEmpty()) { - log.error("UserId is missing in the request."); - result = Either.right(StorageOperationStatus.BAD_REQUEST); - return result; - } - Either findUser = findUserVertex(modifierUserId); - - if (findUser.isRight()) { - TitanOperationStatus status = findUser.right().value(); - log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, modifierUserId, status); - return result; - } - - GraphVertex modifierV = findUser.left().value(); - String toscaElementId = toscaElementToUpdate.getUniqueId(); - - Either parentVertex = titanDao.getParentVertex(elementV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse); - if (parentVertex.isRight()) { - log.debug("Failed to fetch last modifier for tosca element with id {} error {}", toscaElementId, parentVertex.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertex.right().value())); - } - GraphVertex userV = parentVertex.left().value(); - String currentModifier = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); - - String prevSystemName = (String) elementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME); - - if (currentModifier.equals(modifierUserId)) { - log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier."); - } else { - log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId); - StorageOperationStatus status = moveLastModifierEdge(elementV, modifierV); - log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - return result; - } - } - - final long currentTimeMillis = System.currentTimeMillis(); - log.debug("Going to update the last Update Date of the resource from {} to {}", elementV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE), currentTimeMillis); - elementV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currentTimeMillis); - - StorageOperationStatus checkCategories = validateCategories(toscaElementToUpdate, elementV); - if (checkCategories != StorageOperationStatus.OK) { - result = Either.right(checkCategories); - return result; - } - - // update all data on vertex - fillToscaElementVertexData(elementV, toscaElementToUpdate, JsonParseFlagEnum.ParseMetadata); - - Either updateElement = titanDao.updateVertex(elementV); - - if (updateElement.isRight()) { - log.error("Failed to update resource {}. status is {}", toscaElementId, updateElement.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); - return result; - } - GraphVertex updateElementV = updateElement.left().value(); - - // DE230195 in case resource name changed update TOSCA artifacts - // file names accordingly - String newSystemName = (String) updateElementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME); - if (newSystemName != null && !newSystemName.equals(prevSystemName)) { - Either, TitanOperationStatus> resultToscaArt = getDataFromGraph(updateElementV, EdgeLabelEnum.TOSCA_ARTIFACTS); - if (resultToscaArt.isRight()) { - log.debug("Failed to get tosca artifact from graph for tosca element {} error {}", toscaElementId, resultToscaArt.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resultToscaArt.right().value())); - } - - Map toscaArtifacts = resultToscaArt.left().value(); - if (toscaArtifacts != null) { - for (Entry artifact : toscaArtifacts.entrySet()) { - generateNewToscaFileName(toscaElementToUpdate.getComponentType().getValue().toLowerCase(), newSystemName, artifact.getValue()); - } - // TODO call to new Artifact operation in order to update list of artifacts - - } - } - - if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.RESOURCE) { - StorageOperationStatus resultDerived = updateDerived(toscaElementToUpdate, updateElementV); - if (resultDerived != StorageOperationStatus.OK) { - log.debug("Failed to update from derived data for element {} error {}", toscaElementId, resultDerived); - return Either.right(resultDerived); - } - } - - Either updatedResource = getToscaElement(updateElementV, filterResult); - if (updatedResource.isRight()) { - log.error("Failed to fetch tosca element {} after update , error {}", toscaElementId, updatedResource.right().value()); - result = Either.right(StorageOperationStatus.BAD_REQUEST); - return result; - } - - T updatedResourceValue = updatedResource.left().value(); - result = Either.left(updatedResourceValue); - - return result; - } - - protected StorageOperationStatus moveLastModifierEdge(GraphVertex elementV, GraphVertex modifierV) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(titanDao.moveEdge(elementV, modifierV, EdgeLabelEnum.LAST_MODIFIER, Direction.IN)); - } - - protected StorageOperationStatus moveCategoryEdge(GraphVertex elementV, GraphVertex categoryV) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(titanDao.moveEdge(elementV, categoryV, EdgeLabelEnum.CATEGORY, Direction.OUT)); - } - - private void generateNewToscaFileName(String componentType, String componentName, ArtifactDataDefinition artifactInfo) { - Map 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")); - } - - protected StorageOperationStatus validateResourceCategory(T toscaElementToUpdate, GraphVertex elementV) { - StorageOperationStatus status = StorageOperationStatus.OK; - List newCategoryList = toscaElementToUpdate.getCategories(); - CategoryDefinition newCategory = newCategoryList.get(0); - - Either childVertex = titanDao.getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); - if (childVertex.isRight()) { - log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value()); - } - GraphVertex subCategoryV = childVertex.left().value(); - Map metadataProperties = subCategoryV.getMetadataProperties(); - String subCategoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); - - Either parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); - if (parentVertex.isRight()) { - log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value()); - } - GraphVertex categoryV = parentVertex.left().value(); - metadataProperties = categoryV.getMetadataProperties(); - String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); - - boolean categoryWasChanged = false; - - String newCategoryName = newCategory.getName(); - SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0); - String newSubCategoryName = newSubcategory.getName(); - if (newCategoryName != null && !newCategoryName.equals(categoryNameCurrent)) { - // the category was changed - categoryWasChanged = true; - } else { - // the sub-category was changed - if (newSubCategoryName != null && !newSubCategoryName.equals(subCategoryNameCurrent)) { - log.debug("Going to update the category of the resource from {} to {}", categoryNameCurrent, newCategory); - categoryWasChanged = true; - } - } - if (categoryWasChanged) { - Either getCategoryVertex = getResourceCategoryVertex(elementV.getUniqueId(), newSubCategoryName, newCategoryName); - - if (getCategoryVertex.isRight()) { - return getCategoryVertex.right().value(); - } - GraphVertex newCategoryV = getCategoryVertex.left().value(); - status = moveCategoryEdge(elementV, newCategoryV); - log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status); - } - return status; - } - - public Either, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType, List excludeTypes, boolean isHighestVersions) { - Either, TitanOperationStatus> listOfComponents; - if (isHighestVersions) { - listOfComponents = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.NoParse); - } else { - listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes); - } - - if (listOfComponents.isRight() && listOfComponents.right().value() != TitanOperationStatus.NOT_FOUND) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfComponents.right().value())); - } - List result = new ArrayList<>(); - if (listOfComponents.isLeft()) { - List highestAndAllCertified = listOfComponents.left().value(); - if (highestAndAllCertified != null && !highestAndAllCertified.isEmpty()) { - for (GraphVertex vertexComponent : highestAndAllCertified) { - Either component = getLightComponent(vertexComponent, componentType, new ComponentParametersView(true)); - if (component.isRight()) { - log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), component.right().value()); - return Either.right(component.right().value()); - } else { - result.add(component.left().value()); - } - } - } - } - return Either.left(result); - } - - public Either, StorageOperationStatus> getElementCatalogData(boolean isCatalog, List excludeTypes) { - StopWatch stopWatch = new StopWatch(); - stopWatch.start(); - - Map existInCatalog = new HashMap<>(); - Either, TitanOperationStatus> verticesEither = titanDao.getCatalogOrArchiveVerticies(isCatalog); - if (verticesEither.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(verticesEither.right().value())); - } - Iterator vertices = verticesEither.left().value(); - while (vertices.hasNext()) { - handleCatalogComponent(existInCatalog, vertices.next(), excludeTypes); - } - stopWatch.stop(); - String timeToFetchElements = stopWatch.prettyPrint(); - log.info("time to fetch all catalog elements: {}", timeToFetchElements); - return Either.left(existInCatalog.values().stream().collect(Collectors.toList())); - } - - private void handleCatalogComponent(Map existInCatalog, Vertex vertex, List excludeTypes) { - VertexProperty property = vertex.property(GraphPropertiesDictionary.METADATA.getProperty()); - String json = (String) property.value(); - Map metadatObj = JsonParserUtils.toMap(json); - - String uniqueId = (String) metadatObj.get(JsonPresentationFields.UNIQUE_ID.getPresentation()); - Boolean isDeleted = (Boolean) metadatObj.get(JsonPresentationFields.IS_DELETED.getPresentation()); - - - if (isAddToCatalog(excludeTypes, metadatObj) && (existInCatalog.get(uniqueId) == null && (isDeleted == null || !isDeleted.booleanValue()))) { - CatalogComponent catalogComponent = new CatalogComponent(); - catalogComponent.setUniqueId(uniqueId); - - catalogComponent.setComponentType(ComponentTypeEnum.valueOf((String) metadatObj.get(JsonPresentationFields.COMPONENT_TYPE.getPresentation()))); - catalogComponent.setVersion((String) metadatObj.get(JsonPresentationFields.VERSION.getPresentation())); - catalogComponent.setName((String) metadatObj.get(JsonPresentationFields.NAME.getPresentation())); - catalogComponent.setIcon((String) metadatObj.get(JsonPresentationFields.ICON.getPresentation())); - catalogComponent.setLifecycleState((String) metadatObj.get(JsonPresentationFields.LIFECYCLE_STATE.getPresentation())); - catalogComponent.setLastUpdateDate((Long) metadatObj.get(JsonPresentationFields.LAST_UPDATE_DATE.getPresentation())); - catalogComponent.setDistributionStatus((String) metadatObj.get(JsonPresentationFields.DISTRIBUTION_STATUS.getPresentation())); - Object resourceType = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation()); - if (resourceType != null) { - catalogComponent.setResourceType((String) resourceType); - } - - if (catalogComponent.getComponentType() == ComponentTypeEnum.SERVICE) { - setServiceCategoryFromGraphV(vertex, catalogComponent); - - } else { - setResourceCategoryFromGraphV(vertex, catalogComponent); - } - List tags = (List) metadatObj.get(JsonPresentationFields.TAGS.getPresentation()); - if (tags != null) { - catalogComponent.setTags(tags); - } - existInCatalog.put(uniqueId, catalogComponent); - } - } - - private boolean isAddToCatalog(List excludeTypes, Map metadatObj) { - boolean isAddToCatalog = true; - Object resourceTypeStr = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation()); - if (resourceTypeStr != null) { - ResourceTypeEnum resourceType = ResourceTypeEnum.getType((String) resourceTypeStr); - if (!CollectionUtils.isEmpty(excludeTypes)) { - Optional op = excludeTypes.stream().filter(rt -> rt == resourceType).findAny(); - if (op.isPresent()) - isAddToCatalog = false; - } - } - return isAddToCatalog; - } - - public Either, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum - componentType, List excludeTypes, JsonParseFlagEnum parseFlag) { - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map propertiesHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - if (componentType == ComponentTypeEnum.RESOURCE) { - propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, false); - propertiesHasNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes); - } - propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - propertiesHasNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683 - - return titanDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, parseFlag); - } - - // highest + (certified && !highest) - public Either, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents - (ComponentTypeEnum componentType, List excludeTypes) { - long startFetchAllStates = System.currentTimeMillis(); - Either, TitanOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.ParseMetadata); - - Map propertiesToMatchCertified = new EnumMap<>(GraphPropertyEnum.class); - Map propertiesHasNotToMatchCertified = new EnumMap<>(GraphPropertyEnum.class); - propertiesToMatchCertified.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - propertiesToMatchCertified.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - if (componentType == ComponentTypeEnum.RESOURCE) { - propertiesToMatchCertified.put(GraphPropertyEnum.IS_ABSTRACT, false); - propertiesHasNotToMatchCertified.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes); - } - - propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true); - propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683 - propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - Either, TitanOperationStatus> certifiedNotHighestNodes = titanDao.getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified, JsonParseFlagEnum.ParseMetadata); - if (certifiedNotHighestNodes.isRight() && certifiedNotHighestNodes.right().value() != TitanOperationStatus.NOT_FOUND) { - return Either.right(certifiedNotHighestNodes.right().value()); - } - - long endFetchAllStates = System.currentTimeMillis(); - - List allNodes = new ArrayList<>(); - - if (certifiedNotHighestNodes.isLeft()) { - allNodes.addAll(certifiedNotHighestNodes.left().value()); - } - if (highestNodes.isLeft()) { - allNodes.addAll(highestNodes.left().value()); - } - - log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates); - return Either.left(allNodes); - } - - protected Either, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum - componentType) { - - // get all components marked for delete - Map props = new EnumMap<>(GraphPropertyEnum.class); - props.put(GraphPropertyEnum.IS_DELETED, true); - props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - - Either, TitanOperationStatus> componentsToDelete = titanDao.getByCriteria(null, props, JsonParseFlagEnum.NoParse); - - if (componentsToDelete.isRight()) { - TitanOperationStatus error = componentsToDelete.right().value(); - if (error.equals(TitanOperationStatus.NOT_FOUND)) { - log.trace("no components to delete"); - return Either.left(new ArrayList<>()); - } else { - log.info("failed to find components to delete. error : {}", error.name()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - } - } - return Either.left(componentsToDelete.left().value()); - } - - protected TitanOperationStatus setAdditionalInformationFromGraph(GraphVertex componentV, ToscaElement - toscaElement) { - Either, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ADDITIONAL_INFORMATION); - if (result.isLeft()) { - toscaElement.setAdditionalInformation(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - // -------------------------------------------- - public abstract Either getToscaElement(String uniqueId, ComponentParametersView componentParametersView); - - public abstract Either getToscaElement(GraphVertex toscaElementVertex, ComponentParametersView componentParametersView); - - public abstract Either deleteToscaElement(GraphVertex toscaElementVertex); - - public abstract Either createToscaElement(ToscaElement toscaElement); - - protected abstract TitanOperationStatus - setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement); - - protected abstract TitanOperationStatus - setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement); - - protected abstract TitanOperationStatus - setRequirementsFromGraph(GraphVertex componentV, T toscaElement); - - protected abstract StorageOperationStatus - validateCategories(T toscaElementToUpdate, GraphVertex elementV); - - protected abstract StorageOperationStatus - updateDerived(T toscaElementToUpdate, GraphVertex updateElementV); - - public abstract void fillToscaElementVertexData(GraphVertex elementV, T - toscaElementToUpdate, JsonParseFlagEnum flag); - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java deleted file mode 100644 index dd9c3ca29e..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java +++ /dev/null @@ -1,2743 +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.jsontitan.operations; - -import fj.data.Either; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.HealingTitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.*; -import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.*; -import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.catalog.CatalogComponent; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; -import org.openecomp.sdc.be.model.operations.StorageException; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.be.resources.data.ComponentMetadataData; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility; -import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.common.util.ValidationUtils; -import org.springframework.beans.factory.annotation.Autowired; - -import java.util.*; -import java.util.Map.Entry; -import java.util.function.BiPredicate; -import java.util.stream.Collectors; - -import static java.util.Objects.requireNonNull; -import static org.apache.commons.collections.CollectionUtils.isEmpty; -import static org.apache.commons.collections.CollectionUtils.isNotEmpty; - - -@org.springframework.stereotype.Component("tosca-operation-facade") -public class ToscaOperationFacade { - - // region - Fields - - private static final String COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch a component with and UniqueId {}, error: {}"; - private static final String FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS = "Failed to find recently added property {} on the resource {}. Status is {}. "; - private static final String FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS = "Failed to get updated resource {}. Status is {}. "; - private static final String FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS = "Failed to add the property {} to the resource {}. Status is {}. "; - private static final String SERVICE = "service"; - private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}"; - private static final String COMPONENT_CREATED_SUCCESSFULLY = "Component created successfully!!!"; - private static final String COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch component with and unique id {}, error: {}"; - @Autowired - private NodeTypeOperation nodeTypeOperation; - @Autowired - private TopologyTemplateOperation topologyTemplateOperation; - @Autowired - private NodeTemplateOperation nodeTemplateOperation; - @Autowired - private GroupsOperation groupsOperation; - @Autowired - private HealingTitanDao titanDao; - - private static final Logger log = Logger.getLogger(ToscaOperationFacade.class.getName()); - // endregion - - // region - ToscaElement - GetById - public static final String PROXY_SUFFIX = "_proxy"; - - public Either getToscaFullElement(String componentId) { - ComponentParametersView filters = new ComponentParametersView(); - filters.setIgnoreCapabiltyProperties(false); - filters.setIgnoreForwardingPath(false); - return getToscaElement(componentId, filters); - } - - public Either getToscaElement(String componentId) { - - return getToscaElement(componentId, JsonParseFlagEnum.ParseAll); - - } - - public Either getToscaElement(String componentId, ComponentParametersView filters) { - - Either getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag()); - if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - return getToscaElementByOperation(getVertexEither.left().value(), filters); - } - - public Either getToscaElement(String componentId, JsonParseFlagEnum parseFlag) { - - Either getVertexEither = titanDao.getVertexById(componentId, parseFlag); - if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - return getToscaElementByOperation(getVertexEither.left().value()); - } - - public Either getToscaElement(GraphVertex componentVertex) { - return getToscaElementByOperation(componentVertex); - } - - public Either validateComponentExists(String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - TitanOperationStatus status = getVertexEither.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - return Either.left(false); - } else { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - } - } - return Either.left(true); - } - - public Either findLastCertifiedToscaElementByUUID(T component) { - Map props = new EnumMap<>(GraphPropertyEnum.class); - props.put(GraphPropertyEnum.UUID, component.getUUID()); - props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - Either, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props); - if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - return getToscaElementByOperation(getVertexEither.left().value().get(0)); - } - - // endregion - // region - ToscaElement - GetByOperation - private Either getToscaElementByOperation(GraphVertex componentV) { - return getToscaElementByOperation(componentV, new ComponentParametersView()); - } - - private Either getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) { - VertexTypeEnum label = componentV.getLabel(); - - ToscaElementOperation toscaOperation = getToscaElementOperation(componentV); - log.debug("getToscaElementByOperation: toscaOperation={}", toscaOperation.getClass()); - Either toscaElement; - String componentId = componentV.getUniqueId(); - if (toscaOperation != null) { - log.debug("Need to fetch tosca element for id {}", componentId); - toscaElement = toscaOperation.getToscaElement(componentV, filters); - } else { - log.debug("not supported tosca type {} for id {}", label, componentId); - toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST); - } - if (toscaElement.isRight()) { - return Either.right(toscaElement.right().value()); - } - return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value())); - } - - // endregion - private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) { - VertexTypeEnum label = componentV.getLabel(); - switch (label) { - case NODE_TYPE: - return nodeTypeOperation; - case TOPOLOGY_TEMPLATE: - return topologyTemplateOperation; - default: - return null; - } - } - - public Either createToscaComponent(T resource) { - ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource); - - ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource); - Either createToscaElement = toscaElementOperation.createToscaElement(toscaElement); - if (createToscaElement.isLeft()) { - log.debug(COMPONENT_CREATED_SUCCESSFULLY); - T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value()); - return Either.left(dataModel); - } - return Either.right(createToscaElement.right().value()); - } - - // region - ToscaElement Delete - public StorageOperationStatus markComponentToDelete(Component componentToDelete) { - - if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) { - // component already marked for delete - return StorageOperationStatus.OK; - } else { - - Either getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll); - if (getResponse.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentToDelete.getUniqueId(), getResponse.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value()); - - } - GraphVertex componentV = getResponse.left().value(); - - // same operation for node type and topology template operations - Either result = nodeTypeOperation.markComponentToDelete(componentV); - if (result.isRight()) { - return result.right().value(); - } - return StorageOperationStatus.OK; - } - } - - public Either deleteToscaComponent(String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - Either deleteElement = deleteToscaElement(getVertexEither.left().value()); - if (deleteElement.isRight()) { - log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value()); - return Either.right(deleteElement.right().value()); - } - T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value()); - - return Either.left(dataModel); - } - - private Either deleteToscaElement(GraphVertex componentV) { - VertexTypeEnum label = componentV.getLabel(); - Either toscaElement; - Object componentId = componentV.getUniqueId(); - switch (label) { - case NODE_TYPE: - log.debug("Need to fetch node type for id {}", componentId); - toscaElement = nodeTypeOperation.deleteToscaElement(componentV); - break; - case TOPOLOGY_TEMPLATE: - log.debug("Need to fetch topology template for id {}", componentId); - toscaElement = topologyTemplateOperation.deleteToscaElement(componentV); - break; - default: - log.debug("not supported tosca type {} for id {}", label, componentId); - toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST); - break; - } - return toscaElement; - } - // endregion - - private ToscaElementOperation getToscaElementOperation(Component component) { - return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation; - } - - public Either getLatestByToscaResourceName(String toscaResourceName) { - return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); - } - - public Either getFullLatestComponentByToscaResourceName(String toscaResourceName) { - ComponentParametersView fetchAllFilter = new ComponentParametersView(); - fetchAllFilter.setIgnoreForwardingPath(true); - fetchAllFilter.setIgnoreCapabiltyProperties(false); - return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter); - } - - public Either getLatestByName(String resourceName) { - return getLatestByName(GraphPropertyEnum.NAME, resourceName); - - } - - public StorageOperationStatus validateCsarUuidUniqueness(String csarUUID) { - - Map properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID); - - Either, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata); - - if (resources.isRight()) { - if (resources.right().value() == TitanOperationStatus.NOT_FOUND) { - return StorageOperationStatus.OK; - } else { - log.debug("failed to get resources from graph with property name: {}", csarUUID); - return DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()); - } - } - return StorageOperationStatus.ENTITY_ALREADY_EXISTS; - - } - - public Either, StorageOperationStatus> getFollowed(String userId, Set lifecycleStates, Set lastStateStates, ComponentTypeEnum componentType) { - Either, StorageOperationStatus> followedResources; - if (componentType == ComponentTypeEnum.RESOURCE) { - followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); - } else { - followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); - } - - Set components = new HashSet<>(); - if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) { - return Either.right(followedResources.right().value()); - } - if (followedResources.isLeft()) { - List toscaElements = followedResources.left().value(); - toscaElements.forEach(te -> { - T component = ModelConverter.convertFromToscaElement(te); - components.add(component); - }); - } - return Either.left(components); - } - - public Either getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) { - - return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata); - } - - public Either getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) { - - Either result = null; - Map props = new EnumMap<>(GraphPropertyEnum.class); - props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - Either, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag); - - if (getLatestRes.isRight()) { - TitanOperationStatus status = getLatestRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - List resources = getLatestRes.left().value(); - double version = 0.0; - GraphVertex highestResource = null; - for (GraphVertex resource : resources) { - double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION)); - if (resourceVersion > version) { - version = resourceVersion; - highestResource = resource; - } - } - result = getToscaFullElement(highestResource.getUniqueId()); - } - return result; - } - - public Either validateToscaResourceNameExists(String templateName) { - Either validateUniquenessRes = validateToscaResourceNameUniqueness(templateName); - if (validateUniquenessRes.isLeft()) { - return Either.left(!validateUniquenessRes.left().value()); - } - return validateUniquenessRes; - } - - public Either dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { - return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef); - } - - /** - * Allows to get fulfilled requirement by relation and received predicate - */ - public Either getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate predicate) { - return nodeTemplateOperation.getFulfilledRequirementByRelation(componentId, instanceId, relation, predicate); - } - - /** - * Allows to get fulfilled capability by relation and received predicate - */ - public Either getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate predicate) { - return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate); - } - - public StorageOperationStatus associateResourceInstances(String componentId, List relations) { - Either, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations); - if (status.isRight()) { - return status.right().value(); - } - return StorageOperationStatus.OK; - } - - protected Either validateToscaResourceNameUniqueness(String name) { - - Map properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name); - - Either, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata); - - if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("failed to get resources from graph with property name: {}", name); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value())); - } - List resourceList = (resources.isLeft() ? resources.left().value() : null); - if (isNotEmpty(resourceList)) { - if (log.isDebugEnabled()) { - StringBuilder builder = new StringBuilder(); - for (GraphVertex resourceData : resourceList) { - builder.append(resourceData.getUniqueId() + "|"); - } - log.debug("resources with property name:{} exists in graph. found {}", name, builder); - } - return Either.left(false); - } else { - log.debug("resources with property name:{} does not exists in graph", name); - return Either.left(true); - } - - } - - // region - Component Update - - public Either overrideComponent(Resource newComponent, Resource oldComponent) { - - copyArtifactsToNewComponent(newComponent, oldComponent); - - Either componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse); - if (componentVEither.isRight()) { - log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value())); - } - GraphVertex componentv = componentVEither.left().value(); - Either parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); - if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value())); - } - - Either deleteToscaComponent = deleteToscaElement(componentv); - if (deleteToscaComponent.isRight()) { - log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value()); - return Either.right(deleteToscaComponent.right().value()); - } - Either createToscaComponent = createToscaComponent(newComponent); - if (createToscaComponent.isRight()) { - log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value()); - return Either.right(createToscaComponent.right().value()); - } - Resource newElement = createToscaComponent.left().value(); - Either newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse); - if (newVersionEither.isRight()) { - log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value())); - } - if (parentVertexEither.isLeft()) { - GraphVertex previousVersionV = parentVertexEither.left().value(); - TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null); - if (createEdge != TitanOperationStatus.OK) { - log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge)); - } - } - return Either.left(newElement); - } - - void copyArtifactsToNewComponent(Resource newComponent, Resource oldComponent) { - // TODO - check if required - Map toscaArtifacts = oldComponent.getToscaArtifacts(); - if (toscaArtifacts != null && !toscaArtifacts.isEmpty()) { - toscaArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE)); - } - newComponent.setToscaArtifacts(toscaArtifacts); - - Map artifacts = oldComponent.getArtifacts(); - if (artifacts != null && !artifacts.isEmpty()) { - artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE)); - } - newComponent.setArtifacts(artifacts); - - Map depArtifacts = oldComponent.getDeploymentArtifacts(); - if (depArtifacts != null && !depArtifacts.isEmpty()) { - depArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE)); - } - newComponent.setDeploymentArtifacts(depArtifacts); - - newComponent.setGroups(oldComponent.getGroups()); - newComponent.setLastUpdateDate(null); - newComponent.setHighestVersion(true); - } - - public Either updateToscaElement(T componentToUpdate) { - return updateToscaElement(componentToUpdate, new ComponentParametersView()); - } - - public Either updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) { - String componentId = componentToUpdate.getUniqueId(); - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - } - GraphVertex elementV = getVertexEither.left().value(); - ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV); - - ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate); - Either updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult); - if (updateToscaElement.isRight()) { - log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value()); - return Either.right(updateToscaElement.right().value()); - } - return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value())); - } - - private Either getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag) { - return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView()); - } - - private Either getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag, ComponentParametersView filter) { - Either result; - - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - - propertiesToMatch.put(property, nodeName); - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - Either, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag); - if (highestResources.isRight()) { - TitanOperationStatus status = highestResources.right().value(); - log.debug("failed to find resource with name {}. status={} ", nodeName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - List resources = highestResources.left().value(); - double version = 0.0; - GraphVertex highestResource = null; - for (GraphVertex vertex : resources) { - Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION); - double resourceVersion = Double.parseDouble((String) versionObj); - if (resourceVersion > version) { - version = resourceVersion; - highestResource = vertex; - } - } - return getToscaElementByOperation(highestResource, filter); - } - - // endregion - // region - Component Get By .. - private Either getLatestByName(GraphPropertyEnum property, String nodeName) { - return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata); - } - - public Either, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) { - - Either, StorageOperationStatus> result = null; - Either getComponentRes; - List components = new ArrayList<>(); - List componentVertices; - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - - propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName); - if (componentType != null) - propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - Either, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); - if (getComponentsRes.isRight()) { - TitanOperationStatus status = getComponentsRes.right().value(); - log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - componentVertices = getComponentsRes.left().value(); - for (GraphVertex componentVertex : componentVertices) { - getComponentRes = getToscaElementByOperation(componentVertex); - if (getComponentRes.isRight()) { - log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value()); - result = Either.right(getComponentRes.right().value()); - break; - } - T componentBySystemName = getComponentRes.left().value(); - log.debug("Found component, id: {}", componentBySystemName.getUniqueId()); - components.add(componentBySystemName); - } - } - if (result == null) { - result = Either.left(components); - } - return result; - } - - public Either getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) { - return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll); - } - - public Either getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) { - Either result; - - Map hasProperties = new EnumMap<>(GraphPropertyEnum.class); - Map hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); - - hasProperties.put(GraphPropertyEnum.NAME, name); - hasProperties.put(GraphPropertyEnum.VERSION, version); - hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); - if (componentType != null) { - hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - } - Either, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag); - if (getResourceRes.isRight()) { - TitanOperationStatus status = getResourceRes.right().value(); - log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - return getToscaElementByOperation(getResourceRes.left().value().get(0)); - } - - public Either, StorageOperationStatus> getCatalogOrArchiveComponents(boolean isCatalog, List excludeTypes) { - List excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name())) - .collect(Collectors.toList()); - return topologyTemplateOperation.getElementCatalogData(isCatalog, excludedResourceTypes); - } - - // endregion - public Either, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List excludeTypes, boolean isHighestVersions) { - List components = new ArrayList<>(); - Either, StorageOperationStatus> catalogDataResult; - List toscaElements = new ArrayList<>(); - List excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name())) - .collect(Collectors.toList()); - - switch (componentType) { - case RESOURCE: - catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions); - if (catalogDataResult.isRight()) { - return Either.right(catalogDataResult.right().value()); - } - toscaElements = catalogDataResult.left().value(); - break; - case SERVICE: - if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) { - break; - } - catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions); - if (catalogDataResult.isRight()) { - return Either.right(catalogDataResult.right().value()); - } - toscaElements = catalogDataResult.left().value(); - break; - default: - log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType); - return Either.right(StorageOperationStatus.BAD_REQUEST); - } - toscaElements.forEach(te -> { - T component = ModelConverter.convertFromToscaElement(te); - components.add(component); - }); - return Either.left(components); - } - - public Either, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) { - Either, StorageOperationStatus> allComponentsMarkedForDeletion; - switch (componentType) { - case RESOURCE: - allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType); - break; - case SERVICE: - case PRODUCT: - allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType); - break; - default: - log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType); - return Either.right(StorageOperationStatus.BAD_REQUEST); - } - if (allComponentsMarkedForDeletion.isRight()) { - return Either.right(allComponentsMarkedForDeletion.right().value()); - } - List allMarked = allComponentsMarkedForDeletion.left().value(); - return Either.left(checkIfInUseAndDelete(allMarked)); - } - - private List checkIfInUseAndDelete(List allMarked) { - final List forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF); - List deleted = new ArrayList<>(); - - for (GraphVertex elementV : allMarked) { - boolean isAllowedToDelete = true; - - for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) { - Either belongingEdgeByCriteria = titanDao.getBelongingEdgeByCriteria(elementV, edgeLabelEnum, null); - if (belongingEdgeByCriteria.isLeft()){ - log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId()); - isAllowedToDelete = false; - break; - } - } - - if (isAllowedToDelete) { - Either deleteToscaElement = deleteToscaElement(elementV); - if (deleteToscaElement.isRight()) { - log.debug("Failed to delete marked element UniqueID {}, Name {}, error {}", elementV.getUniqueId(), elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value()); - continue; - } - deleted.add(elementV.getUniqueId()); - } - } - return deleted; - } - - public Either, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) { - Either, StorageOperationStatus> allComponentsMarkedForDeletion; - switch (componentType) { - case RESOURCE: - allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType); - break; - case SERVICE: - case PRODUCT: - allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType); - break; - default: - log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType); - return Either.right(StorageOperationStatus.BAD_REQUEST); - } - if (allComponentsMarkedForDeletion.isRight()) { - return Either.right(allComponentsMarkedForDeletion.right().value()); - } - return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(GraphVertex::getUniqueId).collect(Collectors.toList())); - } - - // region - Component Update - public Either, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) { - - Either, StorageOperationStatus> result = null; - Either updateContainerComponentRes = null; - if (StringUtils.isEmpty(componentInstance.getIcon())) { - componentInstance.setIcon(origComponent.getIcon()); - } - String nameToFindForCounter = componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy ? componentInstance.getSourceModelName() + PROXY_SUFFIX : origComponent.getName(); - String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter); - Either, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), - ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user); - - if (addResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName()); - result = Either.right(addResult.right().value()); - } - if (result == null) { - updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId()); - if (updateContainerComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName()); - result = Either.right(updateContainerComponentRes.right().value()); - } - } - if (result == null) { - Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value()); - String createdInstanceId = addResult.left().value().getRight(); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName()); - result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId)); - } - return result; - } - - public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map resourcesInstancesMap, boolean allowDeleted) { - - StorageOperationStatus result = null; - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId()); - - Either metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (result == null) { - result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted); - } - return result; - } - - public Either, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) { - - Either, StorageOperationStatus> result = null; - - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName()); - componentInstance.setIcon(origComponent.getIcon()); - Either, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), - ModelConverter.convertToToscaElement(origComponent), componentInstance); - if (updateResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName()); - result = Either.right(updateResult.right().value()); - } - if (result == null) { - Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft()); - String createdInstanceId = updateResult.left().value().getRight(); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName()); - result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId)); - } - return result; - } - - public Either updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) { - return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView()); - } - - public Either updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, ComponentParametersView filter) { - - Either result = null; - - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName()); - - Either updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter); - if (updateResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName()); - result = Either.right(updateResult.right().value()); - } - if (result == null) { - Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value()); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName()); - result = Either.left(updatedComponent); - } - return result; - } - // endregion - - public Either, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) { - - Either, StorageOperationStatus> result = null; - - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); - - Either, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId); - if (updateResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); - result = Either.right(updateResult.right().value()); - } - if (result == null) { - Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft()); - String deletedInstanceId = updateResult.left().value().getRight(); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName()); - result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId)); - } - return result; - } - - private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) { - Integer nextCounter = 0; - if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) { - String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName); - Integer maxCounter = getMaxCounterFromNamesAndIds(containerComponent, normalizedName); - if (maxCounter != null) { - nextCounter = maxCounter + 1; - } - } - return nextCounter.toString(); - } - - /** - * @return max counter of component instance Id's, null if not found - */ - private Integer getMaxCounterFromNamesAndIds(Component containerComponent, String normalizedName) { - List countersInNames = containerComponent.getComponentInstances().stream() - .filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)) - .map(ci -> ci.getNormalizedName().split(normalizedName)[1]) - .collect(Collectors.toList()); - List countersInIds = containerComponent.getComponentInstances().stream() - .filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)) - .map(ci -> ci.getUniqueId().split(normalizedName)[1]) - .collect(Collectors.toList()); - List namesAndIdsList = new ArrayList<>(countersInNames); - namesAndIdsList.addAll(countersInIds); - return getMaxInteger(namesAndIdsList); - } - - private Integer getMaxInteger(List counters) { - Integer maxCounter = 0; - Integer currCounter = null; - for (String counter : counters) { - try { - currCounter = Integer.parseInt(counter); - if (maxCounter < currCounter) { - maxCounter = currCounter; - } - } catch (NumberFormatException e) { - continue; - } - } - return currCounter == null ? null : maxCounter; - } - - public Either associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { - return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef); - - } - - public Either, StorageOperationStatus> createAndAssociateInputs(Map inputs, String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue()))); - - StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId); - - if (StorageOperationStatus.OK == status) { - log.debug(COMPONENT_CREATED_SUCCESSFULLY); - List inputsResList = null; - if (inputsMap != null && !inputsMap.isEmpty()) { - inputsResList = inputsMap.values().stream() - .map(InputDefinition::new) - .collect(Collectors.toList()); - } - return Either.left(inputsResList); - } - return Either.right(status); - - } - - public Either, StorageOperationStatus> addInputsToComponent(Map inputs, String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDefinition(e.getValue()))); - - StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME); - - if (StorageOperationStatus.OK == status) { - log.debug(COMPONENT_CREATED_SUCCESSFULLY); - List inputsResList = null; - if (inputsMap != null && !inputsMap.isEmpty()) { - inputsResList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList()); - } - return Either.left(inputsResList); - } - return Either.right(status); - - } - - /** - * Add data types into a Component. - * - * @param dataTypes datatypes to be added. the key should be each name of data type. - * @param componentId unique ID of Component. - * @return list of data types. - */ - public Either, StorageOperationStatus> addDataTypesToComponent(Map dataTypes, String componentId) { - - log.trace("#addDataTypesToComponent - enter, componentId={}", componentId); - - /* get component vertex */ - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - /* not found / error */ - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - } - GraphVertex vertex = getVertexEither.left().value(); - log.trace("#addDataTypesToComponent - get vertex ok"); - - // convert DataTypeDefinition to DataTypeDataDefinition - Map dataTypeDataMap = dataTypes.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, e -> convertDataTypeToDataTypeData(e.getValue()))); - - // add datatype(s) to the Component. - // if child vertex does not exist, it will be created. - StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, - EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeDataMap, JsonPresentationFields.NAME); - - if (StorageOperationStatus.OK == status) { - log.debug(COMPONENT_CREATED_SUCCESSFULLY); - List inputsResList = null; - if (!dataTypes.isEmpty()) { - inputsResList = new ArrayList<>(dataTypes.values()); - } - return Either.left(inputsResList); - } - - log.trace("#addDataTypesToComponent - leave"); - return Either.right(status); - } - - private DataTypeDataDefinition convertDataTypeToDataTypeData(DataTypeDefinition dataType) { - DataTypeDataDefinition dataTypeData = new DataTypeDataDefinition(dataType); - if (CollectionUtils.isNotEmpty(dataType.getProperties())) { - List propertyDataList = dataType.getProperties().stream() - .map(PropertyDataDefinition::new).collect(Collectors.toList()); - dataTypeData.setPropertiesData(propertyDataList); - } - - // if "derivedFrom" data_type exists, copy the name to "derivedFromName" - if (dataType.getDerivedFrom() != null && StringUtils.isNotEmpty(dataType.getDerivedFrom().getName())) { - // if names are different, log it - if (!StringUtils.equals(dataTypeData.getDerivedFromName(), dataType.getDerivedFrom().getName())) { - log.debug("#convertDataTypeToDataTypeData - derivedFromName(={}) overwritten by derivedFrom.name(={})", - dataType.getDerivedFromName(), dataType.getDerivedFrom().getName()); - } - dataTypeData.setDerivedFromName(dataType.getDerivedFrom().getName()); - } - - // supply "name" field to toscaPresentationValue in each datatype object for DAO operations - dataTypeData.setToscaPresentationValue(JsonPresentationFields.NAME, dataType.getName()); - return dataTypeData; - } - - - public Either, StorageOperationStatus> getComponentInputs(String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - - Either toscaElement = - topologyTemplateOperation.getToscaElement(componentId); - if(toscaElement.isRight()) { - return Either.right(toscaElement.right().value()); - } - - TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement.left().value(); - - Map inputsMap = topologyTemplate.getInputs(); - - List inputs = new ArrayList<>(); - if(MapUtils.isNotEmpty(inputsMap)) { - inputs = - inputsMap.values().stream().map(p -> new InputDefinition(p)).collect(Collectors.toList()); - } - - return Either.left(inputs); - } - - public Either, StorageOperationStatus> updateInputsToComponent(List inputs, String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - - GraphVertex vertex = getVertexEither.left().value(); - List inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList()); - - StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME); - - if (StorageOperationStatus.OK == status) { - log.debug(COMPONENT_CREATED_SUCCESSFULLY); - List inputsResList = null; - if (inputsAsDataDef != null && !inputsAsDataDef.isEmpty()) { - inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList()); - } - return Either.left(inputsResList); - } - return Either.right(status); - - } - - // region - ComponentInstance - public Either>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map> instProperties, String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map instPropsMap = new HashMap<>(); - if (instProperties != null) { - - MapPropertiesDataDefinition propertiesMap; - for (Entry> entry : instProperties.entrySet()) { - propertiesMap = new MapPropertiesDataDefinition(); - - propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e))); - - instPropsMap.put(entry.getKey(), propertiesMap); - } - } - - StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap); - - if (StorageOperationStatus.OK == status) { - log.debug(COMPONENT_CREATED_SUCCESSFULLY); - return Either.left(instProperties); - } - return Either.right(status); - - } - - /** - * saves the instInputs as the updated instance inputs of the component container in DB - */ - public Either>, StorageOperationStatus> updateComponentInstanceInputsToComponent(Map> instInputs, String componentId) { - if (instInputs == null || instInputs.isEmpty()) { - return Either.left(instInputs); - } - StorageOperationStatus status; - for (Entry> inputsPerIntance : instInputs.entrySet()) { - List toscaDataListPerInst = inputsPerIntance.getValue(); - List pathKeysPerInst = new ArrayList<>(); - pathKeysPerInst.add(inputsPerIntance.getKey()); - status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status); - return Either.right(status); - } - } - - return Either.left(instInputs); - } - - /** - * saves the instProps as the updated instance properties of the component container in DB - */ - public Either>, StorageOperationStatus> updateComponentInstancePropsToComponent(Map> instProps, String componentId) { - if (instProps == null || instProps.isEmpty()) { - return Either.left(instProps); - } - StorageOperationStatus status; - for (Entry> propsPerIntance : instProps.entrySet()) { - List toscaDataListPerInst = propsPerIntance.getValue(); - List pathKeysPerInst = new ArrayList<>(); - pathKeysPerInst.add(propsPerIntance.getKey()); - status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status); - return Either.right(status); - } - } - - return Either.left(instProps); - } - - public Either>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map> instInputs, String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - GraphVertex vertex = getVertexEither.left().value(); - Map instPropsMap = new HashMap<>(); - if (instInputs != null) { - - MapPropertiesDataDefinition propertiesMap; - for (Entry> entry : instInputs.entrySet()) { - propertiesMap = new MapPropertiesDataDefinition(); - - propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e))); - - instPropsMap.put(entry.getKey(), propertiesMap); - } - } - - StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap); - - if (StorageOperationStatus.OK == status) { - log.debug(COMPONENT_CREATED_SUCCESSFULLY); - return Either.left(instInputs); - } - return Either.right(status); - - } - - public Either>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map> instProperties) { - requireNonNull(instProperties); - StorageOperationStatus status; - for (Entry> entry : instProperties.entrySet()) { - List props = entry.getValue(); - String componentInstanceId = entry.getKey(); - if (!isEmpty(props)) { - for (ComponentInstanceInput property : props) { - List componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanceId); - Optional instanceProperty = componentInstancesInputs.stream() - .filter(p -> p.getName().equals(property.getName())) - .findAny(); - if (instanceProperty.isPresent()) { - status = updateComponentInstanceInput(containerComponent, componentInstanceId, property); - } else { - status = addComponentInstanceInput(containerComponent, componentInstanceId, property); - } - if (status != StorageOperationStatus.OK) { - log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanceId, status); - return Either.right(status); - } else { - log.trace("instance input {} for instance {} updated", property, componentInstanceId); - } - } - } - } - return Either.left(instProperties); - } - - public Either>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map> instProperties) { - requireNonNull(instProperties); - for (Entry> entry : instProperties.entrySet()) { - List props = entry.getValue(); - String componentInstanceId = entry.getKey(); - List originalComponentInstProps = - containerComponent.getComponentInstancesProperties().get(componentInstanceId); - Map> containerComponentCapabilities = containerComponent.getCapabilities(); - - if(isEmpty(props)) { - continue; - } - for (ComponentInstanceProperty property : props) { - StorageOperationStatus status = null; - String propertyParentUniqueId = property.getParentUniqueId(); - Optional - capPropDefinition = getPropertyCapability(propertyParentUniqueId, containerComponent); - if(capPropDefinition.isPresent() && MapUtils.isNotEmpty(containerComponentCapabilities)) { - status = populateAndUpdateInstanceCapProperty(containerComponent, componentInstanceId, - containerComponentCapabilities, property, capPropDefinition.get()); - } - if(status == null) { - status = updateOrAddComponentInstanceProperty(containerComponent, componentInstanceId, - originalComponentInstProps, property); - } - if(status != StorageOperationStatus.OK) { - return Either.right(status); - } - } - } - return Either.left(instProperties); - } - - private StorageOperationStatus populateAndUpdateInstanceCapProperty(Component containerComponent, String componentInstanceId, - Map> containerComponentCapabilities, - ComponentInstanceProperty property, - CapabilityDefinition capabilityDefinition) { - List capabilityDefinitions = containerComponentCapabilities.get(capabilityDefinition.getType()); - if(CollectionUtils.isEmpty(capabilityDefinitions)) { - return null; - } - Optional capDefToGetProp = capabilityDefinitions.stream() - .filter(cap -> cap.getUniqueId().equals(capabilityDefinition.getUniqueId()) && cap.getPath().size() == 1).findAny(); - if(capDefToGetProp.isPresent()) { - return updateInstanceCapabilityProperty(containerComponent, componentInstanceId, property, capDefToGetProp.get()); - } - return null; - } - - private static Optional getPropertyCapability(String propertyParentUniqueId, - Component containerComponent) { - - Map> componentCapabilities = containerComponent.getCapabilities(); - if(MapUtils.isEmpty(componentCapabilities)){ - return Optional.empty(); - } - List capabilityDefinitionList = componentCapabilities.values() - .stream().flatMap(Collection::stream).collect(Collectors.toList()); - if(CollectionUtils.isEmpty(capabilityDefinitionList)){ - return Optional.empty(); - } - return capabilityDefinitionList.stream() - .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId)) - .findAny(); - } - - private StorageOperationStatus updateOrAddComponentInstanceProperty(Component containerComponent, - String componentInstanceId, List originalComponentInstProps, - ComponentInstanceProperty property) - { - StorageOperationStatus status; - // check if the property already exists or not - Optional instanceProperty = originalComponentInstProps.stream() - .filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); - if (instanceProperty.isPresent()) { - status = updateComponentInstanceProperty(containerComponent, componentInstanceId, property); - } else { - status = addComponentInstanceProperty(containerComponent, componentInstanceId, property); - } - if (status != StorageOperationStatus.OK) { - log.debug("Failed to update instance property {} for instance {} error {} ", - property, componentInstanceId, status); - } - return status; - } - - public StorageOperationStatus updateInstanceCapabilityProperty(Component containerComponent, String componentInstanceId, - ComponentInstanceProperty property, - CapabilityDefinition capabilityDefinition) { - Optional fetchedCIOptional = containerComponent.getComponentInstanceById(componentInstanceId); - if(!fetchedCIOptional.isPresent()) { - return StorageOperationStatus.GENERAL_ERROR; - } - Either getComponentRes = - getToscaFullElement(fetchedCIOptional.get().getComponentUid()); - if(getComponentRes.isRight()) { - return StorageOperationStatus.GENERAL_ERROR; - } - Optional componentOptional = isNodeServiceProxy(getComponentRes.left().value()); - String propOwner; - if(!componentOptional.isPresent()) { - propOwner = componentInstanceId; - } else { - propOwner = fetchedCIOptional.get().getSourceModelUid(); - } - StorageOperationStatus status; - StringBuffer sb = new StringBuffer(componentInstanceId); - sb.append(ModelConverter.CAP_PROP_DELIM).append(propOwner).append(ModelConverter.CAP_PROP_DELIM) - .append(capabilityDefinition.getType()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getName()); - String capKey = sb.toString(); - status = updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceId, capKey, property); - if (status != StorageOperationStatus.OK) { - log.debug("Failed to update instance capability property {} for instance {} error {} ", property, - componentInstanceId, status); - return status; - } - return StorageOperationStatus.OK; - } - - private Optional isNodeServiceProxy(Component component) { - if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) { - return Optional.empty(); - } - Resource resource = (Resource) component; - ResourceTypeEnum resType = resource.getResourceType(); - if(resType.equals(ResourceTypeEnum.ServiceProxy)) { - return Optional.of(component); - } - return Optional.empty(); - } - - public StorageOperationStatus associateDeploymentArtifactsToInstances(Map> instDeploymentArtifacts, String componentId, User user) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map instArtMap = new HashMap<>(); - if (instDeploymentArtifacts != null) { - - MapArtifactDataDefinition artifactsMap; - for (Entry> entry : instDeploymentArtifacts.entrySet()) { - Map artList = entry.getValue(); - Map artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME); - - instArtMap.put(entry.getKey(), artifactsMap); - } - } - - return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap); - - } - - public StorageOperationStatus associateArtifactsToInstances(Map> instArtifacts, String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map instArtMap = new HashMap<>(); - if (instArtifacts != null) { - - MapArtifactDataDefinition artifactsMap; - for (Entry> entry : instArtifacts.entrySet()) { - Map artList = entry.getValue(); - Map artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - artifactsMap = new MapArtifactDataDefinition(artifacts); - - instArtMap.put(entry.getKey(), artifactsMap); - } - } - - return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap); - - } - - public StorageOperationStatus associateInstAttributeToComponentToInstances(Map> instArttributes, String componentId) { - - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map instAttr = new HashMap<>(); - if (instArttributes != null) { - - MapPropertiesDataDefinition attributesMap; - for (Entry> entry : instArttributes.entrySet()) { - attributesMap = new MapPropertiesDataDefinition(); - attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e))); - instAttr.put(entry.getKey(), attributesMap); - } - } - - return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr); - - } - // endregion - - public StorageOperationStatus associateOrAddCalculatedCapReq(Map>> instCapabilties, Map>> instReg, String componentId) { - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - - } - - GraphVertex vertex = getVertexEither.left().value(); - - Map calcRequirements = new HashMap<>(); - - Map calcCapabilty = new HashMap<>(); - Map calculatedCapabilitiesProperties = new HashMap<>(); - if (instCapabilties != null) { - for (Entry>> entry : instCapabilties.entrySet()) { - - Map> caps = entry.getValue(); - Map mapToscaDataDefinition = new HashMap<>(); - for (Entry> instCapability : caps.entrySet()) { - mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()))); - } - - ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey()); - MapListCapabilityDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance); - - MapCapabilityProperty mapCapabilityProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true); - - calcCapabilty.put(entry.getKey().getUniqueId(), capMap); - calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabilityProperty); - } - } - - if (instReg != null) { - for (Entry>> entry : instReg.entrySet()) { - - Map> req = entry.getValue(); - Map mapToscaDataDefinition = new HashMap<>(); - for (Entry> instReq : req.entrySet()) { - mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList()))); - } - - MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey())); - - calcRequirements.put(entry.getKey().getUniqueId(), capMap); - } - } - - return topologyTemplateOperation.associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties); - } - - private Either, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map hasProps, Map hasNotProps) { - List services = new ArrayList<>(); - List states = new ArrayList<>(); - // include props - hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - // exclude props - states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - hasNotProps.put(GraphPropertyEnum.STATE, states); - hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); - hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true); - return fetchServicesByCriteria(services, hasProps, hasNotProps); - } - - private Either, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) { - List services = null; - Map hasProps = new EnumMap<>(GraphPropertyEnum.class); - Map hasNotProps = new EnumMap<>(GraphPropertyEnum.class); - fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType); - Either, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata); - if (getRes.isRight()) { - if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - return Either.left(new ArrayList<>()); - } else { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); - } - } - // region -> Fetch non checked-out services - if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals(SERVICE) && VertexTypeEnum.NODE_TYPE == vertexType) { - Either, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class)); - if (result.isRight()) { - log.debug("Failed to fetch services for"); - return Either.right(result.right().value()); - } - services = result.left().value(); - if (log.isTraceEnabled() && isEmpty(services)) - log.trace("No relevant services available"); - } - // endregion - List nonAbstractLatestComponents = new ArrayList<>(); - ComponentParametersView params = new ComponentParametersView(true); - params.setIgnoreAllVersions(false); - for (GraphVertex vertexComponent : getRes.left().value()) { - Either componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params); - if (componentRes.isRight()) { - log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value()); - return Either.right(componentRes.right().value()); - } else { - Component component = ModelConverter.convertFromToscaElement(componentRes.left().value()); - nonAbstractLatestComponents.add(component); - } - } - if (CollectionUtils.isNotEmpty(services)) { - nonAbstractLatestComponents.addAll(services); - } - return Either.left(nonAbstractLatestComponents); - } - - public Either getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) { - - Either result; - Map hasProperties = new EnumMap<>(GraphPropertyEnum.class); - hasProperties.put(GraphPropertyEnum.UUID, componentUuid); - if (isHighest != null) { - hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest); - } - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683 - - Either, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag); - if (getRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); - } else { - List latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList()); - ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0) - : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get(); - result = Either.left(latestVersion); - } - return result; - } - - public Either getComponentMetadata(String componentId) { - Either result; - Either getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); - if (getRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); - } else { - ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value()); - result = Either.left(componentMetadata); - } - return result; - } - - public Either, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, ComponentTypeEnum componentTypeEnum, - String internalComponentType, List componentUids) { - - List components = new ArrayList<>(); - if (componentUids == null) { - Either, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, componentTypeEnum, internalComponentType); - if (componentUidsRes.isRight()) { - return Either.right(componentUidsRes.right().value()); - } - componentUids = componentUidsRes.left().value(); - } - if (!isEmpty(componentUids)) { - for (String componentUid : componentUids) { - ComponentParametersView componentParametersView = buildComponentViewForNotAbstract(); - if ("vl".equalsIgnoreCase(internalComponentType)) { - componentParametersView.setIgnoreCapabilities(false); - componentParametersView.setIgnoreRequirements(false); - } - Either getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView); - if (getToscaElementRes.isRight()) { - log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value()); - return Either.right(getToscaElementRes.right().value()); - } - Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value()); - nullifySomeComponentProperties(component); - components.add(component); - } - } - return Either.left(components); - } - - public void nullifySomeComponentProperties(Component component) { - component.setContactId(null); - component.setCreationDate(null); - component.setCreatorUserId(null); - component.setCreatorFullName(null); - component.setLastUpdateDate(null); - component.setLastUpdaterUserId(null); - component.setLastUpdaterFullName(null); - component.setNormalizedName(null); - } - - private Either, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) { - - Either, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum, internalComponentType); - if (getToscaElementsRes.isRight()) { - return Either.right(getToscaElementsRes.right().value()); - } - List collection = getToscaElementsRes.left().value(); - List componentUids; - if (collection == null) { - componentUids = new ArrayList<>(); - } else { - componentUids = collection.stream() - .map(Component::getUniqueId) - .collect(Collectors.toList()); - } - return Either.left(componentUids); - } - - private ComponentParametersView buildComponentViewForNotAbstract() { - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreCategories(false); - componentParametersView.setIgnoreAllVersions(false); - return componentParametersView; - } - - public Either validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { - Either result = validateComponentNameUniqueness(name, resourceType, componentType); - if (result.isLeft()) { - result = Either.left(!result.left().value()); - } - return result; - } - - public Either validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { - VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE; - String normalizedName = ValidationUtils.normaliseComponentName(name); - Map properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName); - properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - - Either, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse); - if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value())); - } - List vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; - if (vertexList != null && !vertexList.isEmpty()) { - return Either.left(false); - } else { - return Either.left(true); - } - } - - private void fillNodeTypePropsMap(Map hasProps, Map hasNotProps, String internalComponentType) { - switch (internalComponentType.toLowerCase()) { - case "vf": - case "cvfc": - hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFCMT.name(), ResourceTypeEnum.Configuration.name())); - break; - case SERVICE: - case "pnf": - case "cr": - hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name())); - break; - case "vl": - hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name()); - break; - default: - break; - } - } - - private void fillTopologyTemplatePropsMap(Map hasProps, Map hasNotProps, ComponentTypeEnum componentTypeEnum) { - switch (componentTypeEnum) { - case RESOURCE: - hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - break; - case SERVICE: - hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - break; - default: - break; - } - hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name()); - } - - private void fillPropsMap(Map hasProps, Map hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) { - hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - - hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); - hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true); - hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - if (VertexTypeEnum.NODE_TYPE == internalVertexType) { - hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract); - if (internalComponentType != null) { - fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType); - } - } else { - fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum); - } - } - - private List getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) { - List internalVertexTypes = new ArrayList<>(); - if (ComponentTypeEnum.RESOURCE == componentTypeEnum) { - internalVertexTypes.add(VertexTypeEnum.NODE_TYPE); - } - if (ComponentTypeEnum.SERVICE == componentTypeEnum || SERVICE.equalsIgnoreCase(internalComponentType)) { - internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE); - } - return internalVertexTypes; - } - - public Either, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) { - List internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType); - List result = new ArrayList<>(); - for (VertexTypeEnum vertexType : internalVertexTypes) { - Either, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, componentTypeEnum, internalComponentType, vertexType); - if (listByVertexType.isRight()) { - return listByVertexType; - } - result.addAll(listByVertexType.left().value()); - } - return Either.left(result); - - } - - private Either, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid, Map additionalPropertiesToMatch) { - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - if (additionalPropertiesToMatch != null) { - propertiesToMatch.putAll(additionalPropertiesToMatch); - } - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - return getComponentListByUuid(componentUuid, propertiesToMatch); - } - - public Either getComponentByUuidAndVersion(String componentUuid, String version) { - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - - propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid); - propertiesToMatch.put(GraphPropertyEnum.VERSION, version); - - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - Either, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); - if (vertexEither.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value())); - } - - List vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; - if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) { - return Either.right(StorageOperationStatus.NOT_FOUND); - } - - return getToscaElementByOperation(vertexList.get(0)); - } - - public Either, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map additionalPropertiesToMatch) { - - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - - if (additionalPropertiesToMatch != null) { - propertiesToMatch.putAll(additionalPropertiesToMatch); - } - - propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid); - - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683 - - Either, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); - - if (vertexEither.isRight()) { - log.debug("Couldn't fetch metadata for component with uuid {}, error: {}", componentUuid, vertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value())); - } - List vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; - - if (vertexList == null || vertexList.isEmpty()) { - log.debug("Component with uuid {} was not found", componentUuid); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - - ArrayList latestComponents = new ArrayList<>(); - for (GraphVertex vertex : vertexList) { - Either toscaElementByOperation = getToscaElementByOperation(vertex); - - if (toscaElementByOperation.isRight()) { - log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId()); - return Either.right(toscaElementByOperation.right().value()); - } - - latestComponents.add(toscaElementByOperation.left().value()); - } - - if (latestComponents.size() > 1) { - for (Component component : latestComponents) { - if (component.isHighestVersion()) { - LinkedList highestComponent = new LinkedList<>(); - highestComponent.add(component); - return Either.left(highestComponent); - } - } - } - - return Either.left(latestComponents); - } - - public Either getLatestServiceByUuid(String serviceUuid) { - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - return getLatestComponentByUuid(serviceUuid, propertiesToMatch); - } - - public Either getLatestComponentByUuid(String componentUuid) { - return getLatestComponentByUuid(componentUuid, null); - } - - public Either getLatestComponentByUuid(String componentUuid, Map propertiesToMatch) { - - Either, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch); - - if (latestVersionListEither.isRight()) { - return Either.right(latestVersionListEither.right().value()); - } - - List latestVersionList = latestVersionListEither.left().value(); - - if (latestVersionList.isEmpty()) { - return Either.right(StorageOperationStatus.NOT_FOUND); - } - Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get(); - - return Either.left(component); - } - - public Either, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) { - - List resources = new ArrayList<>(); - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - - propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract); - if (isHighest != null) { - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest); - } - propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - Either, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); - - if (getResourcesRes.isRight()) { - log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value())); - } - List resourceVerticies = getResourcesRes.left().value(); - for (GraphVertex resourceV : resourceVerticies) { - Either getResourceRes = getToscaElement(resourceV); - if (getResourceRes.isRight()) { - return Either.right(getResourceRes.right().value()); - } - resources.add(getResourceRes.left().value()); - } - return Either.left(resources); - } - - public Either getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) { - Either result; - - Map hasProperties = new EnumMap<>(GraphPropertyEnum.class); - Map hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); - - hasProperties.put(GraphPropertyEnum.NAME, name); - hasProperties.put(GraphPropertyEnum.VERSION, version); - hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); - - Either, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag); - if (getResourceRes.isRight()) { - TitanOperationStatus status = getResourceRes.right().value(); - log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - return getToscaElementByOperation(getResourceRes.left().value().get(0)); - } - - public Either getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) { - return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, JsonParseFlagEnum.ParseAll); - } - - public Either getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, JsonParseFlagEnum parseFlag) { - Map props = new EnumMap<>(GraphPropertyEnum.class); - Map propsHasNot = new EnumMap<>(GraphPropertyEnum.class); - props.put(GraphPropertyEnum.CSAR_UUID, csarUUID); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - if (componentType != null) { - props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - } - propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); - - GraphVertex resourceMetadataData = null; - List resourceMetadataDataList = null; - Either, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata); - if (byCsar.isRight()) { - if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) { - // Fix Defect DE256036 - if (StringUtils.isEmpty(systemName)) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND)); - } - - props.clear(); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - props.put(GraphPropertyEnum.SYSTEM_NAME, systemName); - Either, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata); - if (bySystemname.isRight()) { - log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value())); - } - if (bySystemname.left().value().size() > 2) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - resourceMetadataDataList = bySystemname.left().value(); - if (resourceMetadataDataList.size() == 1) { - resourceMetadataData = resourceMetadataDataList.get(0); - } else { - for (GraphVertex curResource : resourceMetadataDataList) { - if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) { - resourceMetadataData = curResource; - break; - } - } - } - if (resourceMetadataData == null) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions"); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) { - log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID); - // correct error will be returned from create flow. with all - // correct audit records!!!!! - return Either.right(StorageOperationStatus.NOT_FOUND); - } - return getToscaElement((String) resourceMetadataData.getUniqueId()); - } - } else { - resourceMetadataDataList = byCsar.left().value(); - if (resourceMetadataDataList.size() > 2) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - if (resourceMetadataDataList.size() == 1) { - resourceMetadataData = resourceMetadataDataList.get(0); - } else { - for (GraphVertex curResource : resourceMetadataDataList) { - if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) { - resourceMetadataData = curResource; - break; - } - } - } - if (resourceMetadataData == null) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions"); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - return getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag); - } - return null; - } - - public Either validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) { - - String currentTemplateNameChecked = templateNameExtends; - - while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) { - Either latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked); - - if (latestByToscaResourceName.isRight()) { - return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value()); - } - - Resource value = latestByToscaResourceName.left().value(); - - if (value.getDerivedFrom() != null) { - currentTemplateNameChecked = value.getDerivedFrom().get(0); - } else { - currentTemplateNameChecked = null; - } - } - - return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false); - } - - public Either, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) { - Map props = new EnumMap<>(GraphPropertyEnum.class); - props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - Map propsHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - Either, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata); - - if (resourcesByTypeEither.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value())); - } - - List vertexList = resourcesByTypeEither.left().value(); - List components = new ArrayList<>(); - - for (GraphVertex vertex : vertexList) { - components.add(getToscaElementByOperation(vertex, filterBy).left().value()); - } - - return Either.left(components); - } - - public void commit() { - titanDao.commit(); - } - - public Either updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) { - Either updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus); - if (updateDistributionStatus.isRight()) { - return Either.right(updateDistributionStatus.right().value()); - } - GraphVertex serviceV = updateDistributionStatus.left().value(); - service.setDistributionStatus(distributionStatus); - service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE)); - return Either.left(service); - } - - public Either updateComponentLastUpdateDateOnGraph(Component component) { - - Either result = null; - GraphVertex serviceVertex; - Either updateRes = null; - Either getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata); - if (getRes.isRight()) { - TitanOperationStatus status = getRes.right().value(); - log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - serviceVertex = getRes.left().value(); - long lastUpdateDate = System.currentTimeMillis(); - serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate); - component.setLastUpdateDate(lastUpdateDate); - updateRes = titanDao.updateVertex(serviceVertex); - if (updateRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value())); - } - } - if (result == null) { - result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value())); - } - return result; - } - - public HealingTitanDao getTitanDao() { - return titanDao; - } - - public Either, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set distStatus) { - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - - return getServicesWithDistStatus(distStatus, propertiesToMatch); - } - - public Either, StorageOperationStatus> getServicesWithDistStatus(Set distStatus, Map additionalPropertiesToMatch) { - - List servicesAll = new ArrayList<>(); - - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - - if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) { - propertiesToMatch.putAll(additionalPropertiesToMatch); - } - - propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - if (distStatus != null && !distStatus.isEmpty()) { - for (DistributionStatusEnum state : distStatus) { - propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name()); - Either, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch); - if (fetchServicesByCriteria.isRight()) { - return fetchServicesByCriteria; - } else { - servicesAll = fetchServicesByCriteria.left().value(); - } - } - return Either.left(servicesAll); - } else { - return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch); - } - } - - private Either, StorageOperationStatus> fetchServicesByCriteria(List servicesAll, Map propertiesToMatch, Map propertiesNotToMatch) { - Either, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); - if (getRes.isRight()) { - if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); - } - } else { - for (GraphVertex vertex : getRes.left().value()) { - Either getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true)); - - if (getServiceRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value()); - return Either.right(getServiceRes.right().value()); - } else { - servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value())); - } - } - } - return Either.left(servicesAll); - } - - public void rollback() { - titanDao.rollback(); - } - - public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map finalDeploymentArtifacts) { - Map instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - - return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts); - } - - public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map artifacts) { - StorageOperationStatus status = StorageOperationStatus.OK; - if (MapUtils.isNotEmpty(artifacts)) { - Map instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts); - } - return status; - } - - public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) { - return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId); - } - - public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List groupInstances) { - return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances); - } - - public Either addPropertyToComponent(String propertyName, - PropertyDefinition newPropertyDefinition, - Component component) { - - Either result = null; - Either getUpdatedComponentRes = null; - newPropertyDefinition.setName(propertyName); - - StorageOperationStatus status = getToscaElementOperation(component) - .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the component {}. Status is {}. ", propertyName, component.getName(), status); - result = Either.right(status); - } - if (result == null) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreProperties(false); - filter.setIgnoreInputs(false); - getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); - if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } - } - if (result == null) { - PropertyDefinition newProperty = null; - List properties = - (getUpdatedComponentRes.left().value()).getProperties(); - if (CollectionUtils.isNotEmpty(properties)) { - Optional propertyOptional = properties.stream().filter( - propertyEntry -> propertyEntry.getName().equals(propertyName)).findAny(); - if (propertyOptional.isPresent()) { - newProperty = propertyOptional.get(); - } - } - if (newProperty == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the component {}. Status is {}. ", propertyName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } else { - result = Either.left(newProperty); - } - } - return result; - } - public StorageOperationStatus deletePropertyOfComponent(Component component, String propertyName) { - return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME); - } - - public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) { - return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME); - } - - public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) { - return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME); - } - - /** - * Deletes a data type from a component. - * @param component the container which has the data type - * @param dataTypeName the data type name to be deleted - * @return Operation result. - */ - public StorageOperationStatus deleteDataTypeOfComponent(Component component, String dataTypeName) { - return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeName, JsonPresentationFields.NAME); - } - - public Either updatePropertyOfComponent(Component component, - PropertyDefinition newPropertyDefinition) { - - Either getUpdatedComponentRes = null; - Either result = null; - StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getName(), status); - result = Either.right(status); - } - if (result == null) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreProperties(false); - getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); - if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } - } - if (result == null) { - Optional newProperty = (getUpdatedComponentRes.left().value()) - .getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny(); - if (newProperty.isPresent()) { - result = Either.left(newProperty.get()); - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - return result; - } - - - - public Either addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { - - Either getUpdatedComponentRes = null; - Either result = null; - if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) { - String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName()); - newAttributeDef.setUniqueId(attUniqueId); - } - - StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status); - result = Either.right(status); - } - if (result == null) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreAttributesFrom(false); - getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); - if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } - } - if (result == null) { - Optional newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); - if (newAttribute.isPresent()) { - result = Either.left(newAttribute.get()); - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - return result; - } - - public Either updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { - - Either getUpdatedComponentRes = null; - Either result = null; - StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status); - result = Either.right(status); - } - if (result == null) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreAttributesFrom(false); - getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); - if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } - } - if (result == null) { - Optional newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); - if (newProperty.isPresent()) { - result = Either.left(newProperty.get()); - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - return result; - } - - public Either updateInputOfComponent(Component component, InputDefinition newInputDefinition) { - - Either getUpdatedComponentRes = null; - Either result = null; - StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status); - result = Either.right(status); - } - if (result == null) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreInputs(false); - getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); - if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } - } - if (result == null) { - Optional updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny(); - if (updatedInput.isPresent()) { - result = Either.left(updatedInput.get()); - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - return result; - } - - /** - * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename - * - * @param containerComponent - container such as service - * @param componentInstance - context component - * @param componentInstanceId - id - * @return - successfull/failed status - **/ - public Either cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId) { - String uniqueId = componentInstance.getUniqueId(); - StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status); - return Either.right(status); - } - if (componentInstance.getGroupInstances() != null) { - status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances()); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status); - return Either.right(status); - } - } - return Either.left(status); - } - - public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List groups, Map> groupInstancesArtifacts) { - return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts); - } - - public Either, StorageOperationStatus> updateGroupsOnComponent(Component component, List updatedGroups) { - return groupsOperation.updateGroups(component, updatedGroups, true); - } - - public Either, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, String instanceId, List updatedGroupInstances) { - return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances); - } - - public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List groupInstances) { - return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances); - } - - public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map deploymentArtifacts) { - return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts); - } - - public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { - return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property); - } - - public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List properties) { - return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties); - } - - - public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { - return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property); - } - - public StorageOperationStatus updateComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property){ - return nodeTemplateOperation.updateComponentInstanceAttribute(containerComponent, componentInstanceId, property); - } - - public StorageOperationStatus addComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property){ - return nodeTemplateOperation.addComponentInstanceAttribute(containerComponent, componentInstanceId, property); - } - - public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { - return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property); - } - - public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List instanceInputs) { - return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs); - } - - public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { - return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property); - } - - public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) { - this.nodeTypeOperation = nodeTypeOperation; - } - - public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) { - this.topologyTemplateOperation = topologyTemplateOperation; - } - - public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, List inputsToDelete) { - return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList())); - } - - public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityUniqueId, ComponentInstanceProperty property) { - return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityUniqueId, property); - } - - public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) { - return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId) - .map(instanceCapProps -> topologyTemplateOperation.updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps)) - .orElse(StorageOperationStatus.NOT_FOUND); - } - - public StorageOperationStatus updateComponentInstanceInterfaces(Component containerComponent, String componentInstanceUniqueId) { - MapInterfaceDataDefinition mapInterfaceDataDefinition = - convertComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId); - return topologyTemplateOperation - .updateComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId, mapInterfaceDataDefinition); - } - - public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) { - Map mapCapabiltyPropertyMap = - convertComponentCapabilitiesProperties(containerComponent); - return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap); - } - - public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) { - StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES); - if (status == StorageOperationStatus.OK) { - status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS); - } - if (status == StorageOperationStatus.OK) { - status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES); - } - return status; - } - - public Either shouldUpgradeToLatestDerived(Resource clonedResource) { - String componentId = clonedResource.getUniqueId(); - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - GraphVertex nodeTypeV = getVertexEither.left().value(); - - ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource); - - Either shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV); - if (shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value()) { - log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - } - if (shouldUpdateDerivedVersion.isLeft()) { - return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value())); - } - return Either.left(clonedResource); - } - - /** - * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId - */ - public Either, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) { - return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId); - } - - private MapInterfaceDataDefinition convertComponentInstanceInterfaces(Component currComponent, - String componentInstanceId) { - MapInterfaceDataDefinition mapInterfaceDataDefinition = new MapInterfaceDataDefinition(); - List componentInterface = currComponent.getComponentInstancesInterfaces().get(componentInstanceId); - - if(CollectionUtils.isNotEmpty(componentInterface)) { - componentInterface.stream().forEach(interfaceDef -> mapInterfaceDataDefinition.put - (interfaceDef.getUniqueId(), interfaceDef)); - } - - return mapInterfaceDataDefinition; - } - - private Map convertComponentCapabilitiesProperties(Component currComponent) { - Map map = ModelConverter.extractCapabilityPropertiesFromGroups(currComponent.getGroups(), true); - map.putAll(ModelConverter.extractCapabilityProperteisFromInstances(currComponent.getComponentInstances(), true)); - return map; - } - - private Optional convertComponentInstanceProperties(Component component, String instanceId) { - return component.fetchInstanceById(instanceId) - .map(ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), instanceId)); - } - - public Either associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) { - Either result = null; - Either getVertexEither; - getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); - if (getVertexEither.isRight()) { - log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - } else { - if (getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE) { - log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel()); - result = Either.right(StorageOperationStatus.BAD_REQUEST); - } - } - if (result == null) { - StorageOperationStatus status = topologyTemplateOperation.addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - } - if (result == null) { - result = Either.left(policyDefinition); - } - return result; - } - - public StorageOperationStatus associatePoliciesToComponent(String componentId, List policies) { - log.debug("#associatePoliciesToComponent - associating policies for component {}.", componentId); - return titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata) - .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies), - DaoStatusConverter::convertTitanStatusToStorageStatus); - } - - public Either updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition) { - Either result = null; - Either getVertexEither; - getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - } - if (result == null) { - StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - } - if (result == null) { - result = Either.left(policyDefinition); - } - return result; - } - - public StorageOperationStatus updatePoliciesOfComponent(String componentId, List policyDefinition) { - log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId); - return titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse) - .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus) - .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition), - err -> err); - } - - public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) { - StorageOperationStatus status = null; - Either getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); - status = DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - } - if (status == null) { - status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId); - } - return status; - } - - public boolean canAddGroups(String componentId) { - GraphVertex vertex = titanDao.getVertexById(componentId) - .left() - .on(this::onTitanError); - return topologyTemplateOperation.hasEdgeOfType(vertex, EdgeLabelEnum.GROUPS); - } - - GraphVertex onTitanError(TitanOperationStatus toe) { - throw new StorageException( - DaoStatusConverter.convertTitanStatusToStorageStatus(toe)); - } - - public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId){ - topologyTemplateOperation - .updateNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId)); - } - - public void revertNamesOfCalculatedCapabilitiesRequirements(String componentId) { - topologyTemplateOperation - .revertNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId)); - } - - private TopologyTemplate getTopologyTemplate(String componentId) { - return (TopologyTemplate)topologyTemplateOperation - .getToscaElement(componentId, getFilterComponentWithCapProperties()) - .left() - .on(this::throwStorageException); - } - - private ComponentParametersView getFilterComponentWithCapProperties() { - ComponentParametersView filter = new ComponentParametersView(); - filter.setIgnoreCapabiltyProperties(false); - return filter; - } - - private ToscaElement throwStorageException(StorageOperationStatus status) { - throw new StorageException(status); - } - - public Either isComponentInUse(String componentId) { - final List forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF); - Either vertexById = titanDao.getVertexById(componentId); - if (vertexById.isLeft()) { - for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) { - Iterator edgeItr = vertexById.left().value().getVertex().edges(Direction.IN, edgeLabelEnum.name()); - if(edgeItr != null && edgeItr.hasNext()){ - return Either.left(true); - } - } - } - return Either.left(false); - } - - public Either, StorageOperationStatus> getComponentListByInvariantUuid - (String componentInvariantUuid, Map additionalPropertiesToMatch) { - - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - if (MapUtils.isNotEmpty(additionalPropertiesToMatch)) { - propertiesToMatch.putAll(additionalPropertiesToMatch); - } - propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, componentInvariantUuid); - - Either, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, JsonParseFlagEnum.ParseMetadata); - - if (vertexEither.isRight()) { - log.debug("Couldn't fetch metadata for component with type {} and invariantUUId {}, error: {}", componentInvariantUuid, vertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value())); - } - List vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; - - if (vertexList == null || vertexList.isEmpty()) { - log.debug("Component with invariantUUId {} was not found", componentInvariantUuid); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - - ArrayList components = new ArrayList<>(); - for (GraphVertex vertex : vertexList) { - Either toscaElementByOperation = getToscaElementByOperation(vertex); - if (toscaElementByOperation.isRight()) { - log.debug("Could not fetch the following Component by Invariant UUID {}", vertex.getUniqueId()); - return Either.right(toscaElementByOperation.right().value()); - } - components.add(toscaElementByOperation.left().value()); - } - - return Either.left(components); - } - - public Either, StorageOperationStatus> getParentComponents(String componentId) { - List parentComponents = new ArrayList<>(); - final List relationEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF); - Either vertexById = titanDao.getVertexById(componentId); - if (vertexById.isLeft()) { - for (EdgeLabelEnum edgeLabelEnum : relationEdgeLabelEnums) { - Either parentVertexEither = titanDao.getParentVertex(vertexById.left().value(), edgeLabelEnum, JsonParseFlagEnum.ParseJson); - if(parentVertexEither.isLeft()){ - Either componentEither = getToscaElement(parentVertexEither.left().value().getUniqueId()); - if(componentEither.isLeft()){ - parentComponents.add(componentEither.left().value()); - } - } - } - } - return Either.left(parentComponents); - } - public void updateCapReqPropertiesOwnerId(String componentId) { - topologyTemplateOperation - .updateCapReqPropertiesOwnerId(componentId, getTopologyTemplate(componentId)); - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/UpgradeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/UpgradeOperation.java deleted file mode 100644 index 5faa6bb8ad..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/UpgradeOperation.java +++ /dev/null @@ -1,225 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import com.thinkaurelius.titan.core.TitanVertex; -import fj.data.Either; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.model.ComponentDependency; -import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.springframework.stereotype.Component; - -import java.util.*; -import java.util.function.Function; -import java.util.stream.Collectors; - -@Component -public class UpgradeOperation extends BaseOperation { - private static final Logger log = Logger.getLogger(UpgradeOperation.class.getName()); - - public Either, StorageOperationStatus> getComponentDependencies(String componentId) { - Either vertexById = titanDao.getVertexById(componentId); - if (vertexById.isRight()) { - log.debug("Failed to fetch vertex with id {} error {}", componentId, vertexById.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexById.right().value())); - } - List dependencies = new ArrayList<>(); - - GraphVertex vertex = vertexById.left().value(); - - StorageOperationStatus status = fillDependenciesByVertex(componentId, dependencies, vertex); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - - GraphVertex vertexToStart = vertex; - Function> getNextElement = vertexP -> titanDao.getParentVertex(vertexP, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll); - status = handleVersionChain(componentId, dependencies, vertex, getNextElement); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - vertex = vertexToStart; - getNextElement = vertexP -> titanDao.getChildVertex(vertexP, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll); - status = handleVersionChain(componentId, dependencies, vertex, getNextElement); - - return status == StorageOperationStatus.OK ? Either.left(dependencies) : Either.right(status); - } - - private StorageOperationStatus handleVersionChain(String componentId, List dependencies, GraphVertex vertexToStart, Function> getNextElement) { - - StorageOperationStatus status; - boolean nextInChain = true; - GraphVertex vertex = vertexToStart; - Either nextInChainV; - while (nextInChain) { - nextInChainV = getNextElement.apply(vertex); - if (nextInChainV.isRight()) { - nextInChain = false; - } else { - vertex = nextInChainV.left().value(); - status = fillDependenciesByVertex(componentId, dependencies, vertex); - if (status != StorageOperationStatus.OK) { - return status; - } - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus fillDependenciesByVertex(String componentId, List dependencies, GraphVertex vertex) { - StorageOperationStatus status = StorageOperationStatus.OK; - if ( needToAddToDepenedency(vertex) ) { - ComponentDependency dependency = fillDataFromVertex(vertex, null, null); - - List dependList = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF); - for (EdgeLabelEnum label : dependList) { - status = fillDependenciesByLabel(componentId, vertex, dependency, label); - if (status != StorageOperationStatus.OK) { - log.debug("Failed to create dependencies for component {} and label {} status {}", componentId, label, status); - break; - } - } - if (status == StorageOperationStatus.OK) { - dependencies.add(dependency); - } - } - return status; - } - private boolean needToAddToDepenedency(GraphVertex vertex){ - Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED); - Boolean isArchived = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED); - return ( isDeleted == Boolean.TRUE || isArchived == Boolean.TRUE) ? false : true; - } - - private StorageOperationStatus fillDependenciesByLabel(String componentId, GraphVertex vertex, ComponentDependency dependency, EdgeLabelEnum label) { - Either, TitanOperationStatus> parentVertecies = titanDao.getParentVertecies(vertex, label, JsonParseFlagEnum.ParseAll); - if (parentVertecies.isRight() && parentVertecies.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to fetch parent verticies by label INSTANCE_OF for vertex with id {} error {}", componentId, parentVertecies.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertecies.right().value()); - } - if (parentVertecies.isLeft()) { - List existIn = new ArrayList<>( ); - parentVertecies.left().value().forEach(v -> handleHighestVersion(vertex, label, existIn, v) ); - dependency.addDependencies(existIn); - } - return StorageOperationStatus.OK; - } - - private void handleHighestVersion(GraphVertex vertexOrigin, EdgeLabelEnum label, List exisIn, GraphVertex containerVertex) { - Boolean isHighest = (Boolean) containerVertex.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); - if ( isHighest && needToAddToDepenedency(containerVertex) ) { - TitanVertex titanVertex = containerVertex.getVertex(); - Iterator edges = titanVertex.edges(Direction.OUT, EdgeLabelEnum.VERSION.name()); - //verify that it is a last version - highest by version number - if ( edges == null || !edges.hasNext() ){ - ComponentDependency container = fillDataFromVertex(containerVertex, vertexOrigin.getUniqueId(), label); - boolean addToDependency = true; - if (label == EdgeLabelEnum.ALLOTTED_OF) { - //in case of not full allotted chain not add to dependency list - addToDependency = findAllottedChain(containerVertex, container); - } - if ( addToDependency ){ - exisIn.add(container); - } - } - } - } - - private boolean findAllottedChain(GraphVertex vertex, ComponentDependency container) { - Either, TitanOperationStatus> parentVertecies = titanDao.getParentVertecies(vertex, EdgeLabelEnum.INSTANCE_OF, JsonParseFlagEnum.ParseAll); - if (parentVertecies.isLeft()) { - List existIn = new ArrayList<>(); - parentVertecies.left().value().forEach(v -> { - Boolean isHighest = (Boolean) v.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); - if ( isHighest && needToAddToDepenedency(v) ) { - TitanVertex titanVertex = v.getVertex(); - Iterator edges = titanVertex.edges(Direction.OUT, EdgeLabelEnum.VERSION.name()); - //verify that it is a last version - highest by version number - if ( edges == null || !edges.hasNext() ){ - ComponentDependency parentContainer = fillDataFromVertex(v, vertex.getUniqueId(), EdgeLabelEnum.INSTANCE_OF); - existIn.add(parentContainer); - } - } - }); - if ( !existIn.isEmpty() ){ - container.setDependencies(existIn); - return true; - } - } - return false; - } - - private ComponentDependency fillDataFromVertex(GraphVertex v, String originId, EdgeLabelEnum edgeLabel) { - ComponentDependency container = new ComponentDependency(); - container.setName((String) v.getMetadataProperty(GraphPropertyEnum.NAME)); - container.setVersion((String) v.getMetadataProperty(GraphPropertyEnum.VERSION)); - container.setUniqueId(v.getUniqueId()); - container.setType((String) v.getMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE)); - container.setIcon((String) v.getJsonMetadataField(JsonPresentationFields.ICON)); - container.setState((String) v.getMetadataProperty(GraphPropertyEnum.STATE)); - - if (edgeLabel == EdgeLabelEnum.PROXY_OF || edgeLabel == EdgeLabelEnum.ALLOTTED_OF) { - findInstanceNames(v, originId, edgeLabel, container); - } - return container; - } - - private void findInstanceNames(GraphVertex v, String originId, EdgeLabelEnum edgeLabel, ComponentDependency container) { - Map jsonComposition = (Map) v.getJson(); - CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - TitanVertex vertex = v.getVertex(); - Iterator edges = vertex.edges(Direction.OUT, edgeLabel.name()); - while (edges != null && edges.hasNext()) { - Edge edge = edges.next(); - TitanVertex inVertex = (TitanVertex) edge.inVertex(); - String id = (String) titanDao.getProperty(inVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()); - if (id.equals(originId)) { - List instanceOnEdge = (List) titanDao.getProperty(edge, EdgePropertyEnum.INSTANCES); - Map componentInstances = compositionDataDefinition.getComponentInstances(); - - if (componentInstances != null) { - List ciNames = componentInstances - .values() - .stream() - .filter(ci -> instanceOnEdge.contains(ci.getUniqueId())) - .map(ComponentInstanceDataDefinition::getName) - .collect(Collectors.toList()); - if (ciNames != null && !ciNames.isEmpty()) { - container.setInstanceNames(ciNames); - break; - } - } - } - } - } - - public List getInstanceIdFromAllottedEdge(String resourceId, String serviceInvariantUUID) { - Either vertexById = titanDao.getVertexById(resourceId); - if ( vertexById.isLeft() ){ - GraphVertex vertexG = vertexById.left().value(); - TitanVertex vertex = vertexG.getVertex(); - Iterator edges = vertex.edges(Direction.OUT, EdgeLabelEnum.ALLOTTED_OF.name()); - while ( edges != null && edges.hasNext() ){ - Edge edge = edges.next(); - TitanVertex inVertex = (TitanVertex)edge.inVertex(); - String vertexInInvUUID = (String) titanDao.getProperty(inVertex, GraphPropertyEnum.INVARIANT_UUID.getProperty()); - if ( vertexInInvUUID.equals(serviceInvariantUUID) ){ - return (List) titanDao.getProperty(edge, EdgePropertyEnum.INSTANCES) ; - } - } - } - return new ArrayList<>(); - } - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/CapabilityRequirementNameResolver.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/CapabilityRequirementNameResolver.java deleted file mode 100644 index 6bdce99d95..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/CapabilityRequirementNameResolver.java +++ /dev/null @@ -1,394 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.utils; - -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.datatypes.elements.*; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; -import org.openecomp.sdc.be.model.utils.ComponentUtilities; -import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.*; -import java.util.function.Function; -import java.util.stream.Collectors; -import static org.apache.commons.collections.CollectionUtils.isNotEmpty; -import static org.apache.commons.lang3.StringUtils.isBlank; - -public class CapabilityRequirementNameResolver { - - private static final Logger log = Logger.getLogger(CapabilityRequirementNameResolver.class); - private static final String PATH_DELIMITER = "."; - - private CapabilityRequirementNameResolver() { - } - - public static void updateNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId, String ownerName, Function originGetter) { - Map componentCacheToRepair = new HashMap<>(); - log.debug("#updateNamesOfCalculatedCapabilitiesRequirements"); - updateCalculatedCapabilitiesNames(componentCacheToRepair, toscaElement, ownerId, ownerName, originGetter); - updateCalculatedRequirementsNames(componentCacheToRepair, toscaElement, ownerId, ownerName, originGetter); - updateCalculatedCapabilitiesPropertiesKeys(toscaElement, ownerId); - } - - private static void updateCalculatedCapabilitiesPropertiesKeys(TopologyTemplate toscaElement, String ownerId) { - if (calCapPropertiesExist(toscaElement, ownerId)) { - MapCapabilityProperty newProps = new MapCapabilityProperty(); - toscaElement.getCalculatedCapabilitiesProperties().get(ownerId) - .getMapToscaDataDefinition() - .forEach((k, v) -> updateAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps)); - if (MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) { - toscaElement.getCalculatedCapabilitiesProperties().put(ownerId, newProps); - } - } - } - - private static boolean calCapPropertiesExist(TopologyTemplate toscaElement, String ownerId) { - return toscaElement.getCalculatedCapabilitiesProperties() != null - && toscaElement.getCalculatedCapabilitiesProperties().get(ownerId) != null - && MapUtils.isNotEmpty(toscaElement.getCalculatedCapabilitiesProperties().get(ownerId).getMapToscaDataDefinition()) - && capabilitiesExist(toscaElement, ownerId); - } - - private static void updateCalculatedRequirementsNames(Map componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, String ownerName, Function originGetter) { - if (requirementsExist(toscaElement, ownerId)) { - String prefix = ownerName + PATH_DELIMITER; - repairReqNames(componentCacheToRepair, toscaElement, ownerId, originGetter); - toscaElement.getCalculatedRequirements().get(ownerId) - .getMapToscaDataDefinition().values().stream() - .flatMap(l -> l.getListToscaDataDefinition().stream()) - .forEach(r -> { - if (isRequiredToRepair(r.getName())) { - BeEcompErrorManager.getInstance() - .logBeComponentMissingError("The empty name of the requirement was found. Id: " + r.getUniqueId() + ", ownerId: " + ownerId + ", ownerName: " + ownerName, - toscaElement.getComponentType().getValue(), toscaElement.getName()); - } - if (ComponentUtilities.isNotUpdatedCapReqName(prefix, r.getName(), r.getPreviousName())) { - if (StringUtils.isNotEmpty(r.getPreviousName())) { - r.setParentName(r.getPreviousName()); - } - r.setPreviousName(r.getName()); - } - r.setName(prefix + r.getPreviousName()); - }); - } - } - - private static boolean requirementsExist(TopologyTemplate toscaElement, String ownerId) { - return toscaElement.getCalculatedRequirements() != null - && toscaElement.getCalculatedRequirements().get(ownerId) != null - && MapUtils.isNotEmpty(toscaElement.getCalculatedRequirements().get(ownerId).getMapToscaDataDefinition()); - } - - private static void updateCalculatedCapabilitiesNames(Map componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, String ownerName, Function originGetter) { - if (capabilitiesExist(toscaElement, ownerId)) { - String prefix = ownerName + PATH_DELIMITER; - repairCapNames(componentCacheToRepair, toscaElement, ownerId, originGetter); - toscaElement.getCalculatedCapabilities().get(ownerId) - .getMapToscaDataDefinition().values().stream() - .flatMap(l -> l.getListToscaDataDefinition().stream()) - .forEach(c -> { - if (isRequiredToRepair(c.getName())) { - BeEcompErrorManager.getInstance() - .logBeComponentMissingError("The empty name of the capability was found. Id: " + c.getUniqueId() + ", ownerId: " + ownerId + ", ownerName: " + ownerName, - toscaElement.getComponentType().getValue(), toscaElement.getName()); - } - if (ComponentUtilities.isNotUpdatedCapReqName(prefix, c.getName(), c.getPreviousName())) { - if (StringUtils.isNotEmpty(c.getPreviousName())) { - c.setParentName(c.getPreviousName()); - } - c.setPreviousName(c.getName()); - } - c.setName(prefix + c.getPreviousName()); - }); - } - } - - private static boolean capabilitiesExist(TopologyTemplate toscaElement, String ownerId) { - return toscaElement.getCalculatedCapabilities() != null - && toscaElement.getCalculatedCapabilities().get(ownerId) != null - && MapUtils.isNotEmpty(toscaElement.getCalculatedCapabilities().get(ownerId).getMapToscaDataDefinition()); - } - - private static void repairCapNames(Map componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, Function originGetter) { - log.debug("#repairCapNames"); - boolean emptyNameFound = toscaElement.getCalculatedCapabilities() != null - && toscaElement.getCalculatedCapabilities().get(ownerId) != null - && toscaElement.getCalculatedCapabilities().get(ownerId).getMapToscaDataDefinition() != null - && toscaElement.getCalculatedCapabilities().get(ownerId).getMapToscaDataDefinition().values() - .stream() - .filter(Objects::nonNull) - .flatMap(l -> l.getListToscaDataDefinition().stream()) - .filter(Objects::nonNull) - .anyMatch(c -> isRequiredToRepair(c.getName())); - - ComponentInstanceDataDefinition instance = toscaElement.getComponentInstances() != null ? - toscaElement.getComponentInstances().get(ownerId) : null; - if (instance != null && emptyNameFound) { - log.debug("#repairCapNames - Going to repair the name of the capability for the owner {}. ", ownerId); - toscaElement.getCalculatedCapabilities().get(ownerId) - .getMapToscaDataDefinition().values() - .stream() - .flatMap(l -> l.getListToscaDataDefinition().stream()) - .forEach(c -> repairCapName(componentCacheToRepair, instance, c, originGetter)); - } - } - - private static void repairReqNames(Map componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, Function originGetter) { - log.debug("#repairReqNames"); - boolean emptyNameFound = toscaElement.getCalculatedRequirements() != null - && toscaElement.getCalculatedRequirements().get(ownerId) != null - && toscaElement.getCalculatedRequirements().get(ownerId).getMapToscaDataDefinition() != null - && toscaElement.getCalculatedRequirements().get(ownerId).getMapToscaDataDefinition().values() - .stream() - .filter(Objects::nonNull) - .flatMap(l -> l.getListToscaDataDefinition().stream()) - .filter(Objects::nonNull) - .anyMatch(r -> isRequiredToRepair(r.getName())); - - ComponentInstanceDataDefinition instance = toscaElement.getComponentInstances() != null ? - toscaElement.getComponentInstances().get(ownerId) : null; - if (instance != null && emptyNameFound) { - log.debug("#repairReqNames - Going to repair the name of the requirement for the owner {}. ", ownerId); - toscaElement.getCalculatedRequirements().get(ownerId) - .getMapToscaDataDefinition().values() - .stream() - .flatMap(l -> l.getListToscaDataDefinition().stream()) - .forEach(r -> repairReqName(componentCacheToRepair, instance, r, originGetter)); - } - } - - private static void repairCapName(Map componentCacheToRepair, ComponentInstanceDataDefinition instance, CapabilityDataDefinition capability, Function originGetter) { - if (isRequiredToRepair(capability.getName())) { - log.debug("#repairTopologyTemplateCapName - Going to build the name for the capability: ", capability.getUniqueId()); - buildSetCapName(componentCacheToRepair, capability, instance, originGetter); - } - } - - private static boolean isRequiredToRepair(String name) { - boolean isRequiredToRepair = StringUtils.isEmpty(name) || name.endsWith(".null") || name.contains(".null."); - if (isRequiredToRepair) { - log.debug("#isRequiredToRepair - The name {} should be repaired. ", name); - } else { - log.debug("#isRequiredToRepair - The name {} should not be repaired. ", name); - } - return isRequiredToRepair; - } - - private static void repairReqName(Map componentCacheToRepair, ComponentInstanceDataDefinition instance, RequirementDataDefinition requirement, Function originGetter) { - if (isRequiredToRepair(requirement.getName())) { - log.debug("#repairTopologyTemplateCapName - Going to build the name for the requirement: ", requirement.getUniqueId()); - buildSetReqName(componentCacheToRepair, requirement, instance, originGetter); - } - } - - private static void updateAndAddCalculatedCapabilitiesProperties(String stringKey, MapPropertiesDataDefinition properties, MapListCapabilityDataDefinition calculatedCapabilities, MapCapabilityProperty newProps) { - String[] key = stringKey.split(ModelConverter.CAP_PROP_DELIM); - String capType = key[key.length - 2]; - String capName = key[key.length - 1]; - Optional foundCapOpt = calculatedCapabilities.getMapToscaDataDefinition().get(capType) - .getListToscaDataDefinition().stream() - .filter(c -> StringUtils.isNotEmpty(c.getPreviousName()) && c.getPreviousName().equals(capName)) - .findFirst(); - foundCapOpt.ifPresent(capabilityDataDefinition -> key[key.length - 1] = capabilityDataDefinition.getName()); - newProps.put(buildCaLCapPropKey(key), properties); - } - - public static void revertNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId, Function originGetter) { - Map componentCacheToRepair = new HashMap<>(); - log.debug("#revertNamesOfCalculatedCapabilitiesRequirements"); - revertCalculatedCapabilitiesPropertiesKeys(componentCacheToRepair, toscaElement, ownerId, originGetter); - revertCalculatedCapabilitiesNames(toscaElement, ownerId); - revertCalculatedRequirementsNames(componentCacheToRepair, toscaElement, ownerId, originGetter); - } - - private static void revertCalculatedCapabilitiesPropertiesKeys(Map componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, Function originGetter) { - repairCapNames(componentCacheToRepair, toscaElement, ownerId, originGetter); - if (calCapPropertiesExist(toscaElement, ownerId)) { - MapCapabilityProperty newProps = new MapCapabilityProperty(); - toscaElement.getCalculatedCapabilitiesProperties().get(ownerId) - .getMapToscaDataDefinition() - .forEach((k, v) -> revertAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps)); - if (MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) { - toscaElement.getCalculatedCapabilitiesProperties().put(ownerId, newProps); - } - } - } - - private static void revertCalculatedRequirementsNames(Map componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, Function originGetter) { - repairReqNames(componentCacheToRepair, toscaElement, ownerId, originGetter); - if (requirementsExist(toscaElement, ownerId)) { - toscaElement.getCalculatedRequirements().get(ownerId) - .getMapToscaDataDefinition().values().stream() - .flatMap(l -> l.getListToscaDataDefinition().stream()) - .forEach(CapabilityRequirementNameResolver::revertReqNames); - } - } - - private static void revertReqNames(RequirementDataDefinition requirement) { - if (StringUtils.isNotEmpty(requirement.getPreviousName())) { - requirement.setName(requirement.getPreviousName()); - requirement.setPreviousName(requirement.getParentName()); - } - } - - private static void revertCalculatedCapabilitiesNames(TopologyTemplate toscaElement, String ownerId) { - if (capabilitiesExist(toscaElement, ownerId)) { - toscaElement.getCalculatedCapabilities().get(ownerId) - .getMapToscaDataDefinition().values().stream() - .flatMap(l -> l.getListToscaDataDefinition().stream()) - .forEach(CapabilityRequirementNameResolver::revertCapNames); - } - } - - private static void revertCapNames(CapabilityDataDefinition capability) { - if (StringUtils.isNotEmpty(capability.getPreviousName())) { - capability.setName(capability.getPreviousName()); - capability.setPreviousName(capability.getParentName()); - } - } - - private static void revertAndAddCalculatedCapabilitiesProperties(String stringKey, MapPropertiesDataDefinition properties, MapListCapabilityDataDefinition calculatedCapabilities, MapCapabilityProperty newProps) { - String[] key = stringKey.split(ModelConverter.CAP_PROP_DELIM); - String capType = key[key.length - 2]; - String capName = key[key.length - 1]; - Optional foundCapOpt = calculatedCapabilities.getMapToscaDataDefinition().get(capType) - .getListToscaDataDefinition().stream() - .filter(c -> c.getName().equals(capName) && StringUtils.isNotEmpty(c.getPreviousName())) - .findFirst(); - foundCapOpt.ifPresent(capabilityDataDefinition -> key[key.length - 1] = capabilityDataDefinition.getPreviousName()); - newProps.put(buildCaLCapPropKey(key), properties); - } - - private static String buildCaLCapPropKey(String[] keyArray) { - StringBuilder key = new StringBuilder(); - for (int i = 0; i < keyArray.length; ++i) { - key.append(keyArray[i]); - if (i < keyArray.length - 1) { - key.append(ModelConverter.CAP_PROP_DELIM); - } - } - return key.toString(); - } - - private static void buildSetCapName(Map componentsCache, CapabilityDataDefinition capability, ComponentInstanceDataDefinition instance, Function originGetter) { - List reducedPath = capability.getOwnerId() != null ? getReducedPathByOwner(capability.getPath(), capability.getOwnerId()) : getReducedPath(capability.getPath()); - log.debug("reducedPath for ownerId {}, reducedPath {} ", capability.getOwnerId(), reducedPath); - reducedPath.remove(reducedPath.size() - 1); - ToscaElement originComponent = getOriginComponent(componentsCache, instance, originGetter); - String name = isRequiredToRepair(capability.getParentName()) ? - extractNameFromUniqueId(capability.getUniqueId()) : capability.getParentName(); - StringBuilder repairedName = buildSubstitutedName(componentsCache, originComponent, reducedPath, originGetter); - log.debug("#buildSetCapName - The name for the capability was built: {}", repairedName); - - capability.setName(repairedName.append(name).toString()); - if (isRequiredToRepair(capability.getPreviousName())) { - capability.setPreviousName(capability.getName().substring(capability.getName().indexOf(PATH_DELIMITER) + 1)); - } - if (isRequiredToRepair(capability.getParentName())) { - capability.setParentName(name); - } - } - - private static void buildSetReqName(Map componentsCache, RequirementDataDefinition requirement, ComponentInstanceDataDefinition instance, Function originGetter) { - List reducedPath = requirement.getOwnerId() != null ? getReducedPathByOwner(requirement.getPath(), requirement.getOwnerId()) : getReducedPath(requirement.getPath()); - log.debug("reducedPath for ownerId {}, reducedPath {} ", requirement.getOwnerId(), reducedPath); - reducedPath.remove(reducedPath.size() - 1); - ToscaElement originComponent = getOriginComponent(componentsCache, instance, originGetter); - String name = isRequiredToRepair(requirement.getParentName()) ? - extractNameFromUniqueId(requirement.getUniqueId()) : requirement.getParentName(); - - StringBuilder repairedName = buildSubstitutedName(componentsCache, originComponent, reducedPath, originGetter); - log.debug("#buildSetReqName - The name for the capability was built: ", repairedName); - requirement.setName(repairedName.append(name).toString()); - if (isRequiredToRepair(requirement.getPreviousName())) { - requirement.setPreviousName(requirement.getName().substring(requirement.getName().indexOf(PATH_DELIMITER) + 1)); - } - if (isRequiredToRepair(requirement.getParentName())) { - requirement.setParentName(name); - } - } - - private static String extractNameFromUniqueId(String uniqueId) { - String[] uid = uniqueId.split("\\."); - return uid[uid.length - 1]; - } - - private static StringBuilder buildSubstitutedName(Map componentsCache, ToscaElement originComponent, List path, Function originGetter) { - StringBuilder substitutedName = new StringBuilder(); - log.debug("#buildSubstitutedName"); - if (isNotEmpty(path) && isTopologyTemplateNotCvfc(originComponent)) { - log.debug("#buildSubstitutedName"); - List reducedPath = getReducedPath(path); - Collections.reverse(reducedPath); - appendNameRecursively(componentsCache, originComponent, reducedPath.iterator(), substitutedName, originGetter); - } - return substitutedName; - } - - private static boolean isTopologyTemplateNotCvfc(ToscaElement originComponent) { - return originComponent.getToscaType() == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE && originComponent.getResourceType() != ResourceTypeEnum.CVFC; - } - - private static ToscaElement getOriginComponent(Map componentsCache, ComponentInstanceDataDefinition instance, Function originGetter) { - if (componentsCache.containsKey(getActualComponentUid(instance))) { - return componentsCache.get(getActualComponentUid(instance)); - } - ToscaElement origin = originGetter.apply(instance); - componentsCache.put(origin.getUniqueId(), origin); - return origin; - } - - public static String getActualComponentUid(ComponentInstanceDataDefinition instance) { - return instance.getIsProxy() ? instance.getSourceModelUid() : instance.getComponentUid(); - } - - private static List getReducedPath(List path) { - return path.stream().distinct().collect(Collectors.toList()); - } - - private static void appendNameRecursively(Map componentsCache, ToscaElement originComponent, Iterator instanceIdIter, StringBuilder substitutedName, Function originGetter) { - log.debug("#appendNameRecursively"); - if (isTopologyTemplateNotCvfc(originComponent) - && MapUtils.isNotEmpty(((TopologyTemplate) originComponent).getComponentInstances()) && instanceIdIter.hasNext()) { - - String ownerId = instanceIdIter.next(); - Optional instanceOpt = ((TopologyTemplate) originComponent).getComponentInstances().values().stream().filter(i -> i.getUniqueId().equals(ownerId)).findFirst(); - if (instanceOpt.isPresent()) { - substitutedName.append(instanceOpt.get().getNormalizedName()).append(PATH_DELIMITER); - ToscaElement getOriginRes = getOriginComponent(componentsCache, instanceOpt.get(), originGetter); - appendNameRecursively(componentsCache, getOriginRes, instanceIdIter, substitutedName, originGetter); - } else if (MapUtils.isNotEmpty(((TopologyTemplate) originComponent).getGroups())) { - Optional groupOpt = ((TopologyTemplate) originComponent).getGroups().values().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst(); - groupOpt.ifPresent(groupDataDefinition -> substitutedName.append(groupDataDefinition.getName()).append(PATH_DELIMITER)); - } else { - log.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId, originComponent.getUniqueId()); - } - } - } - - private static List getReducedPathByOwner(List path, String ownerId) { - log.debug("ownerId {}, path {} ", ownerId, path); - if (CollectionUtils.isEmpty(path)) { - log.debug("cannot perform reduce by owner, path to component is empty"); - return path; - } - if (isBlank(ownerId)) { - log.debug("cannot perform reduce by owner, component owner is empty"); - return path; - } - //reduce by owner - Map map = path.stream().collect(Collectors.toMap(it -> dropLast(it, PATH_DELIMITER), Function.identity(), (a, b) -> a.endsWith(ownerId) ? a : b)); - //reduce list&duplicates and preserve order - return path.stream().distinct().filter(it -> map.values().contains(it)).collect(Collectors.toList()); - } - - private static String dropLast(String path, String delimiter) { - if (isBlank(path) || isBlank(delimiter)) { - return path; - } - return path.substring(0, path.lastIndexOf(delimiter)); - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapper.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapper.java deleted file mode 100644 index 2c3c98e133..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapper.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.utils; - -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; -import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; -import org.openecomp.sdc.be.model.jsontitan.operations.ExternalReferencesOperation; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.springframework.stereotype.Component; - -import java.util.Map; -import java.util.Optional; - -/** - * Created by yavivi on 12/02/2018. - */ -@Component -public class IdMapper { - - private static final Logger log = Logger.getLogger(ExternalReferencesOperation.class.getName()); - - public String mapComponentNameToUniqueId(String componentInstanceName, GraphVertex serviceVertex) { - return map(componentInstanceName, serviceVertex, true); - } - - public String mapUniqueIdToComponentNameTo(String compUniqueId, GraphVertex serviceVertex) { - return map(compUniqueId, serviceVertex, false); - } - - private String map(String componentUniqueIdOrName, GraphVertex serviceVertex, boolean fromCompName) { - String result = null; - try { - Map jsonComposition = (Map) serviceVertex.getJson(); - CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - - Optional componentInstanceDataDefinitionOptional = null; - if (fromCompName) { - componentInstanceDataDefinitionOptional = compositionDataDefinition.getComponentInstances().values().stream().filter(c -> c.getNormalizedName().equals(componentUniqueIdOrName)).findAny(); - result = componentInstanceDataDefinitionOptional.get().getUniqueId(); - log.debug("Compponent Instance Unique Id = {}", result); - } else { - componentInstanceDataDefinitionOptional = compositionDataDefinition.getComponentInstances().values().stream().filter(c -> c.getUniqueId().equals(componentUniqueIdOrName)).findAny(); - result = componentInstanceDataDefinitionOptional.get().getNormalizedName(); - log.debug("Compponent Instance Normalized Name = {}", result); - } - - } catch (Exception e) { - log.error("Failed to map UUID or Normalized name of " + componentUniqueIdOrName, e); - } - return result; - } - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java deleted file mode 100644 index 9412c5c70b..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java +++ /dev/null @@ -1,1731 +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.T - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model.jsontitan.utils; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.ListUtils; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.builder.ReflectionToStringBuilder; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.datatypes.elements.*; -import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; -import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; -import org.openecomp.sdc.be.resources.data.ComponentMetadataData; -import org.openecomp.sdc.be.resources.data.ProductMetadataData; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import org.openecomp.sdc.be.resources.data.ServiceMetadataData; -import org.openecomp.sdc.common.log.wrappers.Logger; - -import java.util.*; -import java.util.Map.Entry; -import java.util.function.Function; -import java.util.stream.Collectors; - -public class ModelConverter { - public static final String CAP_PROP_DELIM = "#"; - private static final Logger log = Logger.getLogger(ModelConverter.class); - - @SuppressWarnings("unchecked") - public static T convertToToscaElement(Component component) { - if (isAtomicComponent(component)) { - return (T) convertToNodeType(component); - } - return (T) convertToTopologyTemplate(component); - } - - @SuppressWarnings("unchecked") - public static T convertFromToscaElement(ToscaElement toscaElement) { - switch (toscaElement.getComponentType()) { - case RESOURCE: - return (T) convertToResource(toscaElement); - case SERVICE: - case PRODUCT: - return (T) convertToService(toscaElement); - default: - return null; - } - } - - public static boolean isAtomicComponent(Component component) { - ComponentTypeEnum componentType = component.getComponentType(); - if (!componentType.equals(ComponentTypeEnum.RESOURCE)) { - return false; - } - Resource resource = (Resource) component; - ResourceTypeEnum resType = resource.getResourceType(); - return isAtomicComponent(resType); - } - - public static boolean isAtomicComponent(ResourceTypeEnum resourceType) { - if (resourceType == null) { - return false; - } - return resourceType.isAtomicType(); - } - - // ********************************************************** - public static VertexTypeEnum getVertexType(Component component) { - VertexTypeEnum vertexType; - if (isAtomicComponent(component)) { - vertexType = VertexTypeEnum.NODE_TYPE; - } else { - vertexType = VertexTypeEnum.TOPOLOGY_TEMPLATE; - } - return vertexType; - } - - public static VertexTypeEnum getVertexType(String resourceTypeName) { - VertexTypeEnum vertexType = null; - ResourceTypeEnum resourceType = ResourceTypeEnum.getTypeByName(resourceTypeName); - if (isAtomicComponent(resourceType)) { - vertexType = VertexTypeEnum.NODE_TYPE; - } else { - vertexType = VertexTypeEnum.TOPOLOGY_TEMPLATE; - } - return vertexType; - } - - - - private static Service convertToService(ToscaElement toscaElement) { - Service service = new Service(); - convertComponentFields(service, toscaElement); - - convertServiceSpecificFields(toscaElement, service); - - TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; - - convertComponentInstances(topologyTemplate, service); - - convertInputs(topologyTemplate, service); - - convertProperties(topologyTemplate, service); - - convertPolicies(topologyTemplate, service); - - convertProperties(topologyTemplate, service); - - convertPolicies(topologyTemplate, service); - - convertGroups(topologyTemplate, service); - - setCapabilitiesToComponentAndGroups(topologyTemplate, service); - - convertPolicies(topologyTemplate, service); - - convertRelations(topologyTemplate, service); - - convertArtifacts(topologyTemplate, service); - - convertServiceApiArtifacts(topologyTemplate, service); - - convertServicePaths(topologyTemplate, service); - - convertServiceInterfaces(topologyTemplate, service); - - convertDataTypes(topologyTemplate, service); - - convertNodeFiltersComponents(topologyTemplate, service); - setCapabilitiesToComponent(topologyTemplate, service); - setRequirementsToComponent(topologyTemplate, service); - return service; - } - - private static void convertServiceSpecificFields(ToscaElement toscaElement, Service service) { - service.setProjectCode((String) toscaElement.getMetadataValue(JsonPresentationFields.PROJECT_CODE)); - service.setDistributionStatus(DistributionStatusEnum - .findState((String) toscaElement.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS))); - service.setEcompGeneratedNaming( - (Boolean) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.ECOMP_GENERATED_NAMING, true)); - service.setNamingPolicy((String) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.NAMING_POLICY, - StringUtils.EMPTY)); - service.setEnvironmentContext( - (String) toscaElement.getMetadataValue(JsonPresentationFields.ENVIRONMENT_CONTEXT)); - service.setInstantiationType((String) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.INSTANTIATION_TYPE, StringUtils.EMPTY)); - } - - private static Resource convertToResource(ToscaElement toscaElement) { - Resource resource = new Resource(); - convertComponentFields(resource, toscaElement); - - resource.setResourceType(toscaElement.getResourceType()); - if (toscaElement.getToscaType() == ToscaElementTypeEnum.NODE_TYPE) { - NodeType nodeType = (NodeType) toscaElement; - resource.setDerivedFrom(nodeType.getDerivedFrom()); - resource.setDerivedList(nodeType.getDerivedList()); - resource.setAbstract((Boolean) nodeType.getMetadataValue(JsonPresentationFields.IS_ABSTRACT)); - convertAttributes(nodeType, resource); - convertCapabilities(nodeType, resource); - convertRequirements(nodeType, resource); - convertInterfaces(nodeType, resource); - - } else { - TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; - if (resource.getResourceType() == ResourceTypeEnum.VF || resource.getResourceType() == ResourceTypeEnum.PNF) { - resource.setCsarUUID((String) topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID)); - resource.setCsarVersion((String) topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_VERSION)); - resource.setImportedToscaChecksum((String) topologyTemplate.getMetadataValue(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM)); - convertInterfaces(topologyTemplate, resource); - - } - convertComponentInstances(topologyTemplate, resource); - convertRelations(topologyTemplate, resource); - convertInputs(topologyTemplate, resource); - convertGroups(topologyTemplate, resource); - setCapabilitiesToComponentAndGroups(topologyTemplate, resource); - convertPolicies(topologyTemplate, resource); - convertNodeFiltersComponents(topologyTemplate, resource); - convertProperties(topologyTemplate, resource); - setCapabilitiesToComponent(topologyTemplate, resource); - setRequirementsToComponent(topologyTemplate, resource); - convertDataTypes(topologyTemplate, resource); - } - convertArtifacts(toscaElement, resource); - convertAdditionalInformation(toscaElement, resource); - - return resource; - } - - private static void convertInterfaces(TopologyTemplate toscaElement, Resource resource) { - Map interfaces = toscaElement.getInterfaces(); - Map copy; - if (interfaces != null) { - copy = interfaces.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDefinition(e.getValue()))); - } else { - copy = new HashMap<>(); - } - resource.setInterfaces(copy); - } - - private static void convertServiceInterfaces(TopologyTemplate toscaElement, Service service) { - Map interfaces = toscaElement.getInterfaces(); - Map copy; - if (interfaces != null) { - copy = interfaces.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDefinition(e.getValue()))); - } else { - copy = new HashMap<>(); - } - service.setInterfaces(copy); - } - - private static void convertAttributes(NodeType nodeType, Resource resource) { - Map attributes = nodeType.getAttributes(); - if (attributes != null) { - List attrs = attributes.values().stream().map(dataDef -> ModelConverter.fromDataDefinition(resource.getUniqueId(), dataDef)).collect(Collectors.toList()); - resource.setAttributes(attrs); - } - } - - private static PropertyDefinition fromDataDefinition(String resourceId, PropertyDataDefinition dataDefinition) { - PropertyDefinition attributeDefinition = new PropertyDefinition(dataDefinition); - attributeDefinition.setParentUniqueId(resourceId); - return attributeDefinition; - } - - private static void convertInterfaces(NodeType nodeType, Resource resource) { - Map interfaceArtifacts = nodeType.getInterfaceArtifacts(); - if (interfaceArtifacts != null) { - Map interfaces = interfaceArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new InterfaceDefinition(en.getValue()))); - resource.setInterfaces(interfaces); - } - } - - /** - * Converts component instances of topology template to component instances of resource - * - * @param topologyTemplate - * @param component - */ - public static void convertComponentInstances(TopologyTemplate topologyTemplate, Component component) { - - if (MapUtils.isNotEmpty(topologyTemplate.getComponentInstances())) { - - setComponentInstancesAttributesToComponent(topologyTemplate, component); - - setComponentInstancesPropertiesToComponent(topologyTemplate, component); - - setComponentInstancesInputsToComponent(topologyTemplate, component); - - setComponentInstancesToComponent(topologyTemplate, component); - - setComponentInstancesCapabilitiesToComponentAndCI(topologyTemplate, component); - - setComponentInstancesRequirementsToComponent(topologyTemplate, component); - - setComponentInstancesArtifactsToComponent(topologyTemplate, component); - - setComponentInstancesInterfacesToComponent(topologyTemplate, component); - - } - } - - private static void setComponentInstancesArtifactsToComponent(TopologyTemplate topologyTemplate, Component component) { - Map instDeploymentArtifacts = topologyTemplate.getInstDeploymentArtifacts(); - Map instanceArtifacts = topologyTemplate.getInstanceArtifacts(); - - List instances = component.getComponentInstances(); - if (instDeploymentArtifacts != null && instances != null) { - instDeploymentArtifacts.entrySet().forEach(e -> { - Optional ci = instances.stream().filter(i -> i.getUniqueId().equals(e.getKey())).findFirst(); - if (ci.isPresent()) { - Map mapToscaDataDefinition = e.getValue().getMapToscaDataDefinition(); - Map deplArt = mapToscaDataDefinition.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue()))); - - ci.get().setDeploymentArtifacts(deplArt); - } - }); - } - if (instanceArtifacts != null && instances != null) { - instanceArtifacts.entrySet().forEach(e -> { - Optional ci = instances.stream().filter(i -> i.getUniqueId().equals(e.getKey())).findFirst(); - if (ci.isPresent()) { - Map mapToscaDataDefinition = e.getValue().getMapToscaDataDefinition(); - Map deplArt = mapToscaDataDefinition.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue()))); - - ci.get().setArtifacts(deplArt); - } - }); - } - - } - - public static void convertComponentInstances(Component component, TopologyTemplate topologyTemplate) { - - if (!CollectionUtils.isEmpty(component.getComponentInstances())) { - - setComponentInstancesAttributesToTopologyTemplate(component, topologyTemplate); - - setComponentInstancesPropertiesToTopologyTemplate(component, topologyTemplate); - - setComponentInstancesInputsToTopologyTemplate(component, topologyTemplate); - - setComponentInstancesToTopologyTemplate(component, topologyTemplate); - - setComponentInstancesArtifactsToTopologyTemplate(component, topologyTemplate); - } - } - - public static void convertRelations(TopologyTemplate topologyTemplate, Component component) { - Map relations = topologyTemplate.getRelations(); - List componentRelations; - if (relations != null && !relations.isEmpty()) { - componentRelations = relations.values().stream().map(ModelConverter::convertRelation).collect(Collectors.toList()); - - } else { - componentRelations = new ArrayList<>(); - } - component.setComponentInstancesRelations(componentRelations); - - } - - public static RequirementCapabilityRelDef convertRelation(RelationshipInstDataDefinition relation) { - RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef(); - requirementCapabilityRelDef.setFromNode(relation.getFromId()); - requirementCapabilityRelDef.setToNode(relation.getToId()); - requirementCapabilityRelDef.setOriginUI(BooleanUtils.isTrue(relation.isOriginUI())); - - CapabilityRequirementRelationship rel = new CapabilityRequirementRelationship(); - RelationshipInfo relationshipPair = getRelationshipInfo(relation); - rel.setRelation(relationshipPair); - requirementCapabilityRelDef.setRelationships(Arrays.asList(rel)); - - return requirementCapabilityRelDef; - } - - /** - * @param relation - * @return - */ - private static RelationshipInfo getRelationshipInfo(RelationshipInstDataDefinition relation) { - RelationshipInfo relationshipPair = new RelationshipInfo(); - - relationshipPair.setId(relation.getUniqueId()); - - relationshipPair.setCapabilityOwnerId(relation.getCapabilityOwnerId()); - relationshipPair.setCapabilityUid(relation.getCapabilityId()); - relationshipPair.setCapability(relation.getCapability()); - - relationshipPair.setRequirementOwnerId(relation.getRequirementOwnerId()); - relationshipPair.setRequirementUid(relation.getRequirementId()); - relationshipPair.setRequirement(relation.getRequirement()); - - RelationshipImpl relationship = new RelationshipImpl(); - relationship.setType(relation.getType()); - relationshipPair.setRelationships(relationship); - - return relationshipPair; - } - - - public static List convertRelationToToscaRelation(RequirementCapabilityRelDef relation) { - - List relationsList = new ArrayList<>(); - - List relationship = relation.getRelationships(); - relationship.forEach(p -> { - RelationshipInstDataDefinition requirementCapabilityRelDef = new RelationshipInstDataDefinition(); - requirementCapabilityRelDef.setFromId(relation.getFromNode()); - requirementCapabilityRelDef.setToId(relation.getToNode()); - requirementCapabilityRelDef.setUniqueId(p.getRelation().getId()); - requirementCapabilityRelDef.setCapabilityOwnerId(p.getRelation().getCapabilityOwnerId()); - requirementCapabilityRelDef.setCapabilityId(p.getRelation().getCapabilityUid()); - requirementCapabilityRelDef.setRequirementOwnerId(p.getRelation().getRequirementOwnerId()); - requirementCapabilityRelDef.setRequirementId(p.getRelation().getRequirementUid()); - requirementCapabilityRelDef.setRequirement(p.getRelation().getRequirement()); - requirementCapabilityRelDef.setType(p.getRelation().getRelationship().getType()); - requirementCapabilityRelDef.setCapability(p.getRelation().getCapability()); - - relationsList.add(requirementCapabilityRelDef); - }); - - return relationsList; - } - - private static void convertCapabilities(Component component, TopologyTemplate topologyTemplate) { - convertTopologyTemplateCapabilities(component, topologyTemplate); - if(componentInstancesCapabilitiesExist(component) || groupsCapabilitiesExist(component)){ - topologyTemplate.setCalculatedCapabilities(new HashMap<>()); - topologyTemplate.setCalculatedCapabilitiesProperties(new HashMap<>()); - } - convertComponentInstancesCapabilities(component, topologyTemplate); - convertGroupsCapabilities(component, topologyTemplate); - } - - private static void convertGroupsCapabilities(Component component, TopologyTemplate topologyTemplate) { - if(groupsCapabilitiesExist(component)){ - component.getGroups() - .stream() - .filter(g -> MapUtils.isNotEmpty(g.getCapabilities())) - .forEach(g -> addCapabilities(topologyTemplate, g.getCapabilities(), g.getUniqueId())); - } - } - - private static void convertTopologyTemplateCapabilities(Component component, ToscaElement toscaElement) { - Map> capabilities = component.getCapabilities(); - - Map toscaCapMap = new HashMap<>(); - Map toscaCapPropMap = new HashMap<>(); - - if (MapUtils.isNotEmpty(capabilities )) { - capabilities.forEach((s, caps) -> { - if (CollectionUtils.isNotEmpty(caps)) { - List capList = caps.stream().filter(capabilityDefinition -> capabilityDefinition.getOwnerId() - .equals(component.getUniqueId())).map(CapabilityDataDefinition::new).collect(Collectors.toList()); - - populateCapabilityMap(toscaCapMap, toscaCapPropMap, s, caps, capList); - } - } - ); - - toscaElement.setCapabilities(toscaCapMap); - toscaElement.setCapabilitiesProperties(toscaCapPropMap); - } - } - private static void populateCapabilityMap(Map toscaCapMap, - Map toscaCapPropMap, - String s, List caps, - List capList) { - ListCapabilityDataDefinition listCapabilityDataDefinition = new ListCapabilityDataDefinition(capList); - toscaCapMap.put(s, listCapabilityDataDefinition); - - for (CapabilityDefinition cap : caps) { - List capPrps = cap.getProperties(); - if (CollectionUtils.isNotEmpty(capPrps)) { - MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); - for (ComponentInstanceProperty cip : capPrps) { - PropertyDataDefinition propertyDataDefinition = new PropertyDataDefinition(cip); - propertyDataDefinition.setParentUniqueId(cap.getUniqueId()); - dataToCreate.put(cip.getName(), propertyDataDefinition); - } - toscaCapPropMap.put(s + CAP_PROP_DELIM + cap.getName(), dataToCreate); - } - } - } - - private static void convertTopologyTemplateRequirements(Component component, ToscaElement toscaElement) { - Map> requirements = component.getRequirements(); - - Map toscaReqMap = new HashMap<>(); - - if (MapUtils.isNotEmpty(requirements )) { - requirements.forEach((s, reqs)-> { - if (CollectionUtils.isNotEmpty(reqs)) { - List reqList = reqs.stream().filter(requirementDefinition -> requirementDefinition.getOwnerId() - .equals(component.getUniqueId())).map(RequirementDataDefinition::new).collect(Collectors.toList()); - - ListRequirementDataDefinition listRequirementDataDefinition = new ListRequirementDataDefinition(reqList); - toscaReqMap.put(s, listRequirementDataDefinition); - } - } - ); - toscaElement.setRequirements(toscaReqMap); - } - } - private static void convertComponentInstancesCapabilities(Component component, TopologyTemplate topologyTemplate) { - if (componentInstancesCapabilitiesExist(component)) { - component.getComponentInstances() - .stream() - .filter(i -> MapUtils.isNotEmpty(i.getCapabilities())) - .forEach(i -> addCapabilities(topologyTemplate, i.getCapabilities(), i.getUniqueId())); - } - } - - private static void addCapabilities(TopologyTemplate topologyTemplate, Map> capabilities, String ownerId) { - if (MapUtils.isNotEmpty(capabilities)) { - if (topologyTemplate.getCalculatedCapabilities() == null) { - topologyTemplate.setCalculatedCapabilities(new HashMap<>()); - } - topologyTemplate.getCalculatedCapabilities().put(ownerId, convertToMapListCapabiltyDataDefinition(capabilities)); - if (topologyTemplate.getCalculatedCapabilitiesProperties() == null) { - topologyTemplate.setCalculatedCapabilitiesProperties(new HashMap<>()); - } - topologyTemplate.getCalculatedCapabilitiesProperties().put(ownerId, convertToMapOfMapCapabiltyProperties(capabilities, ownerId)); - } - } - - private static boolean componentInstancesCapabilitiesExist(Component component) { - return component.getCapabilities() != null && component.getComponentInstances() != null - && component.getComponentInstances() - .stream() - .filter(ci->MapUtils.isNotEmpty(ci.getCapabilities())) - .findFirst() - .isPresent(); - } - private static boolean groupsCapabilitiesExist(Component component) { - return component.getCapabilities() != null && component.getGroups() != null - && component.getGroups() - .stream() - .filter(g->MapUtils.isNotEmpty(g.getCapabilities())) - .findFirst() - .isPresent(); - } - public static MapCapabilityProperty convertToMapOfMapCapabiltyProperties(Map> instCapabilities, String ownerId) { - return convertToMapOfMapCapabiltyProperties(instCapabilities, ownerId, false); - } - - public static MapCapabilityProperty convertToMapOfMapCapabiltyProperties(Map> capabilities, String ownerId, boolean fromCsar) { - - Map toscaCapPropMap = new HashMap<>(); - if(MapUtils.isNotEmpty(capabilities)) - capabilities.forEach((s, caps)-> { - - if (caps != null && !caps.isEmpty()) { - - MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); - - for (CapabilityDefinition cap : caps) { - List capPrps = cap.getProperties(); - if (capPrps != null) { - - for (ComponentInstanceProperty cip : capPrps) { - dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip)); - } - // format key of capability properties : - // VF instance in service : instanceId#ownerId#type#capName - // VFC instance ion VF : instanceId#ownerId#type#capName -> instanceId=ownerId - - StringBuilder sb = new StringBuilder(ownerId); - sb.append(CAP_PROP_DELIM); - if (fromCsar) { - sb.append(ownerId); - } else { - sb.append(cap.getOwnerId()); - } - sb.append(CAP_PROP_DELIM).append(s).append(CAP_PROP_DELIM).append(cap.getName()); - toscaCapPropMap.put(sb.toString(), new MapPropertiesDataDefinition(dataToCreate)); - } - } - } - } - ); - return new MapCapabilityProperty(toscaCapPropMap); - } - - private static MapListCapabilityDataDefinition convertToMapListCapabiltyDataDefinition(Map> instCapabilities) { - - Map mapToscaDataDefinition = new HashMap<>(); - for (Entry> instCapability : instCapabilities.entrySet()) { - mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()))); - } - - return new MapListCapabilityDataDefinition(mapToscaDataDefinition); - } - - private static void convertRequirements(Component component, TopologyTemplate topologyTemplate) { - - convertTopologyTemplateRequirements(component, topologyTemplate); - if (component.getRequirements() != null && component.getComponentInstances() != null) { - topologyTemplate.setCalculatedRequirements(new HashMap<>()); - for (ComponentInstance instance : component.getComponentInstances()) { - Map> instRequirements = instance.getRequirements(); - if (MapUtils.isNotEmpty(instRequirements)) { - if (topologyTemplate.getCalculatedRequirements() == null) { - topologyTemplate.setCalculatedRequirements(new HashMap<>()); - } - topologyTemplate.getCalculatedRequirements().put(instance.getUniqueId(), convertToMapListRequirementDataDefinition(instRequirements)); - } - } - } - } - - private static MapListRequirementDataDefinition convertToMapListRequirementDataDefinition(Map> instRequirements) { - - Map mapToscaDataDefinition = new HashMap<>(); - for (Entry> instRequirement : instRequirements.entrySet()) { - mapToscaDataDefinition.put(instRequirement.getKey(), new ListRequirementDataDefinition(instRequirement.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList()))); - } - - return new MapListRequirementDataDefinition(mapToscaDataDefinition); - } - - @SuppressWarnings("unchecked") - private static void convertComponentFields(Component component, ToscaElement toscaElement) { - component.setName(toscaElement.getName()); - component.setAllVersions(toscaElement.getAllVersions()); - component.setCategories(toscaElement.getCategories()); - component.setComponentType(toscaElement.getComponentType()); - component.setCreationDate(toscaElement.getCreationDate()); - component.setCreatorUserId(toscaElement.getCreatorUserId()); - component.setCreatorFullName(toscaElement.getCreatorFullName()); - component.setLastUpdateDate(toscaElement.getLastUpdateDate()); - component.setLastUpdaterFullName(toscaElement.getLastUpdaterFullName()); - component.setLastUpdaterUserId(toscaElement.getLastUpdaterUserId()); - component.setNormalizedName(toscaElement.getNormalizedName()); - - component.setLifecycleState(toscaElement.getLifecycleState()); - component.setVersion(toscaElement.getVersion()); - component.setHighestVersion(toscaElement.isHighestVersion()); - component.setUniqueId(toscaElement.getUniqueId()); - component.setSystemName((String) toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME)); - component.setDerivedFromGenericType(toscaElement.getDerivedFromGenericType()); - component.setDerivedFromGenericVersion(toscaElement.getDerivedFromGenericVersion()); - - Map properties = toscaElement.getProperties(); - if(MapUtils.isNotEmpty(properties)) { - List propertiesMap = properties.values().stream().map(x -> new PropertyDefinition(x)).collect(Collectors.toList()); - component.setProperties(propertiesMap); - } - - //archive - component.setArchived(toscaElement.isArchived() == null ? false : toscaElement.isArchived()); - - - //component.setArchiveTime(toscaElement.getArchiveTime() == null ? 0L : toscaElement.getArchiveTime()); - component.setArchiveTime(toscaElement.getArchiveTime()); - component.setVspArchived(toscaElement.isVspArchived() == null ? false : toscaElement.isVspArchived()); - - if (component.getComponentType() == ComponentTypeEnum.RESOURCE) { - Resource resource = (Resource) component; - resource.setAbstract((Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT)); - resource.setToscaResourceName((String) toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); - resource.setVendorName((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_NAME)); - resource.setVendorRelease((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_RELEASE)); - // field isn't mandatory , but shouldn't be null(should be an empty string instead) - if (((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)) != null){ - resource.setResourceVendorModelNumber((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)); - } else { - resource.setResourceVendorModelNumber(""); - } - } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) { - Service service = (Service) component; - if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)) != null){ - service.setServiceType((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)); - } else { - service.setServiceType(""); - } - if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)) != null){ - service.setServiceRole((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)); - } else { - service.setServiceRole(""); - } - } - component.setConformanceLevel((String) toscaElement.getMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL)); - component.setIcon((String) toscaElement.getMetadataValue(JsonPresentationFields.ICON)); - component.setDescription((String) toscaElement.getMetadataValue(JsonPresentationFields.DESCRIPTION)); - component.setTags((List) toscaElement.getMetadataValue(JsonPresentationFields.TAGS)); - component.setInvariantUUID((String) toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID)); - component.setContactId((String) toscaElement.getMetadataValue(JsonPresentationFields.CONTACT_ID)); - component.setUUID((String) toscaElement.getMetadataValue(JsonPresentationFields.UUID)); - component.setIsDeleted((Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED)); - component.setToscaType(toscaElement.getToscaType().getValue()); - } - - private static NodeType convertToNodeType(Component component) { - Resource resource = (Resource) component; - NodeType nodeType = new NodeType(); - nodeType.setDerivedFrom(resource.getDerivedFrom()); - nodeType.setDerivedList(resource.getDerivedList()); - nodeType.setResourceType(resource.getResourceType()); - convertCommonToscaData(component, nodeType); - convertAdditionalInformation(component, nodeType); - convertArtifacts(resource, nodeType); - convertCapabilities(resource, nodeType); - convertRequirements(resource, nodeType); - convertAttributes(resource, nodeType); - convertProperties(resource, nodeType); - convertInterfaces(resource, nodeType); - return nodeType; - } - - private static void convertProperties(Resource resource, NodeType nodeType) { - List properties = resource.getProperties(); - if (properties != null && !properties.isEmpty()) { - Map propertiesMap = properties.stream().collect(Collectors.toMap(PropertyDefinition::getName, PropertyDataDefinition::new)); - nodeType.setProperties(propertiesMap); - } - } - - private static void convertInterfaces(Resource resource, NodeType nodeType) { - Map interfaces = resource.getInterfaces(); - if (interfaces != null) { - Map interfaceArtifacts = interfaces.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, x -> new InterfaceDataDefinition(x.getValue()))); - nodeType.setInterfaceArtifacts(interfaceArtifacts); - } - } - - private static void convertAdditionalInformation(Component component, ToscaElement toscaElement) { - List additionalInformation = component.getAdditionalInformation(); - if (additionalInformation != null) { - Map addInfo = additionalInformation.stream().collect(Collectors.toMap(AdditionalInformationDefinition::getUniqueId, AdditionalInfoParameterDataDefinition::new)); - toscaElement.setAdditionalInformation(addInfo); - } - } - - private static void convertAdditionalInformation(ToscaElement toscaElement, Component resource) { - Map additionalInformation = toscaElement.getAdditionalInformation(); - if (additionalInformation != null) { - List addInfo = additionalInformation.values().stream().map(AdditionalInformationDefinition::new).collect(Collectors.toList()); - resource.setAdditionalInformation(addInfo); - } - } - - private static void convertArtifacts(ToscaElement toscaElement, Component component) { - Map artifacts = toscaElement.getArtifacts(); - Map copy; - if (artifacts != null) { - copy = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); - - } else { - copy = new HashMap<>(); - } - component.setArtifacts(copy); - - Map toscaArtifacts = toscaElement.getToscaArtifacts(); - if (toscaArtifacts != null) { - copy = toscaArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); - - } else { - copy = new HashMap<>(); - } - component.setToscaArtifacts(copy); - - Map deploymentArtifacts = toscaElement.getDeploymentArtifacts(); - if (deploymentArtifacts != null) { - copy = deploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); - - } else { - copy = new HashMap<>(); - } - component.setDeploymentArtifacts(copy); - } - - private static void convertNodeFiltersComponents(TopologyTemplate topologyTemplate, Component component) { - Map filters = topologyTemplate.getNodeFilterComponents(); - Map copy; - if (filters != null) { - copy = filters.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new CINodeFilterDataDefinition(e.getValue()))); - } else { - copy = new HashMap<>(); - } - component.setNodeFilterComponents(copy); - } - - private static void convertServiceApiArtifacts(TopologyTemplate topologyTemplate, Service service) { - Map serviceApiArtifacts = topologyTemplate.getServiceApiArtifacts(); - Map copy; - if (serviceApiArtifacts != null) { - copy = serviceApiArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); - - } else { - copy = new HashMap<>(); - } - service.setServiceApiArtifacts(copy); - } - private static void convertServicePaths(TopologyTemplate topologyTemplate, Service service) { - Map servicePaths = topologyTemplate.getForwardingPaths(); - Map copy; - if (servicePaths != null) { - copy = servicePaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ForwardingPathDataDefinition(e.getValue()))); - - } else { - copy = new HashMap<>(); - } - service.setForwardingPaths(copy); - } - - private static void convertArtifacts(Component component, ToscaElement toscaElement) { - Map artifacts = component.getArtifacts(); - if (artifacts != null) { - Map copy = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - toscaElement.setArtifacts(copy); - } - - Map toscaArtifacts = component.getToscaArtifacts(); - if (toscaArtifacts != null) { - Map copy = toscaArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - toscaElement.setToscaArtifacts(copy); - } - - Map deploymentArtifacts = component.getDeploymentArtifacts(); - if (deploymentArtifacts != null) { - Map copy = deploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - toscaElement.setDeploymentArtifacts(copy); - } - } - - private static void convertServiceApiArtifacts(Service service, TopologyTemplate topologyTemplate) { - Map serviceApiArtifacts = service.getServiceApiArtifacts(); - if (serviceApiArtifacts != null) { - Map copy = serviceApiArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - topologyTemplate.setServiceApiArtifacts(copy); - } - } - - private static void convertCapabilities(Component component, NodeType toscaElement) { - Map> capabilities = component.getCapabilities(); - - Map toscaCapMap = new HashMap<>(); - Map toscaCapPropMap = new HashMap<>(); - - if (capabilities != null && !capabilities.isEmpty()) { - capabilities.forEach((s, caps) -> { - - if (caps != null && !caps.isEmpty()) { - List capList = caps.stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()); - - populateCapabilityMap(toscaCapMap, toscaCapPropMap, s, caps, capList); - } - } - ); - - toscaElement.setCapabilities(toscaCapMap); - toscaElement.setCapabilitiesProperties(toscaCapPropMap); - } - } - - private static void convertAttributes(Resource component, NodeType nodeType) { - List attributes = component.getAttributes(); - if (attributes != null) { - Map attrsByName = attributes.stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity())); - nodeType.setAttributes(attrsByName); - } - } - - private static void convertRequirements(Resource component, NodeType nodeType) { - Map> requirements = component.getRequirements(); - - Map toscaReqMap = new HashMap<>(); - - if (requirements != null && !requirements.isEmpty()) { - requirements.forEach((s, reqs)-> { - - if (reqs != null && !reqs.isEmpty()) { - List reqList = reqs.stream().map(RequirementDataDefinition::new).collect(Collectors.toList()); - - ListRequirementDataDefinition listRequirementDataDefinition = new ListRequirementDataDefinition(reqList); - toscaReqMap.put(s, listRequirementDataDefinition); - } - } - ); - nodeType.setRequirements(toscaReqMap); - } - } - - private static void convertCapabilities(NodeType toscaElement, Component component) { - Map toscaCapabilities = toscaElement.getCapabilities(); - Map toscaCapPropMap = toscaElement.getCapabilitiesProperties(); - - Map> compCap = new HashMap<>(); - if (toscaCapabilities == null || toscaCapabilities.isEmpty()) - return; - toscaCapabilities.forEach((s, cap)-> { - - if (cap != null) { - List capDataList = cap.getListToscaDataDefinition(); - - if (capDataList != null && !capDataList.isEmpty()) { - List capList = capDataList.stream().map(CapabilityDefinition::new).collect(Collectors.toList()); - compCap.put(s, capList); - } - } - - } - ); - if (toscaCapPropMap != null && !toscaCapPropMap.isEmpty()) { - toscaCapPropMap.forEach((s, capProp)-> { - String[] result = s.split(CAP_PROP_DELIM); - if (capProp != null) { - Map capMap = capProp.getMapToscaDataDefinition(); - - if (capMap != null && !capMap.isEmpty()) { - List capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList()); - - List cap = compCap.get(result[0]); - Optional op = cap.stream().filter(c -> c.getName().equals(result[1])).findFirst(); - if (op.isPresent()) { - op.get().setProperties(capPropsList); - } - } - } - } - ); - } - - component.setCapabilities(compCap); - - } - - private static void convertGroups(TopologyTemplate toscaElement, Component component) { - Map toscaGroups = toscaElement.getGroups(); - List groupDefinitions = null; - if (MapUtils.isNotEmpty(toscaGroups)) { - groupDefinitions = toscaGroups.values().stream().map(GroupDefinition::new).collect(Collectors.toList()); - } - component.setGroups(groupDefinitions); - } - - private static void convertPolicies(TopologyTemplate toscaElement, Component component) { - Map policies = toscaElement.getPolicies(); - Map policyDefinitions = null; - if (MapUtils.isNotEmpty(policies)) { - policyDefinitions = policies.values().stream().map(PolicyDefinition::new).collect(Collectors.toMap(PolicyDefinition::getUniqueId, Function.identity())); - } - component.setPolicies(policyDefinitions); - } - - private static void convertGroups(Component component, TopologyTemplate toscaElement) { - List groupDefinitions = component.getGroups(); - Map groups = new HashMap<>(); - - if (groupDefinitions != null && groups.isEmpty()) { - groups = groupDefinitions.stream().collect(Collectors.toMap(GroupDefinition::getName, GroupDefinition::new)); - } - toscaElement.setGroups(groups); - } - - private static void convertPolicies(Component component, TopologyTemplate toscaElement) { - Map policyDefinitions = component.getPolicies(); - Map policies = new HashMap<>(); - if (MapUtils.isNotEmpty(policyDefinitions)) { - policies = policyDefinitions.values().stream().collect((Collectors.toMap(PolicyDefinition::getUniqueId, PolicyDataDefinition::new))); - } - toscaElement.setPolicies(policies); - } - - private static void convertRequirements(NodeType toscaElement, Component component) { - Map toscaRequirements = toscaElement.getRequirements(); - - Map> compReqs = new HashMap<>(); - if (toscaRequirements == null || toscaRequirements.isEmpty()) - return; - toscaRequirements.forEach((s, req) -> { - - if (req != null) { - List reqDataList = req.getListToscaDataDefinition(); - - if (reqDataList != null && !reqDataList.isEmpty()) { - List reqList = reqDataList.stream().map(RequirementDefinition::new).collect(Collectors.toList()); - compReqs.put(s, reqList); - } - } - } - ); - component.setRequirements(compReqs); - } - - private static TopologyTemplate convertToTopologyTemplate(Component component) { - TopologyTemplate topologyTemplate; - ComponentTypeEnum componentType = component.getComponentType(); - topologyTemplate = new TopologyTemplate(); - - if (componentType == ComponentTypeEnum.RESOURCE) { - Resource resource = (Resource) component; - topologyTemplate.setResourceType(resource.getResourceType()); - topologyTemplate.setMetadataValue(JsonPresentationFields.CSAR_UUID, resource.getCsarUUID()); - topologyTemplate.setMetadataValue(JsonPresentationFields.CSAR_VERSION, resource.getCsarVersion()); - topologyTemplate.setMetadataValue(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM, resource.getImportedToscaChecksum()); - convertTopologyTemplateInterfaces(resource, topologyTemplate); - } - if (componentType == ComponentTypeEnum.SERVICE) { - convertServiceSpecificEntities((Service) component, topologyTemplate); - } - convertCommonToscaData(component, topologyTemplate); - convertArtifacts(component, topologyTemplate); - - convertAdditionalInformation(component, topologyTemplate); - convertComponentInstances(component, topologyTemplate); - - convertInputs(component, topologyTemplate); - convertProperties(component, topologyTemplate); - convertCapabilities(component, topologyTemplate); - convertGroups(component, topologyTemplate); - convertPolicies(component, topologyTemplate); - convertRequirements(component, topologyTemplate); - convertRelationsToComposition(component, topologyTemplate); - - return topologyTemplate; - } - - private static void convertTopologyTemplateInterfaces(Resource resource, TopologyTemplate topologyTemplate) { - Map interfaces = resource.getInterfaces(); - if (interfaces != null && !interfaces.isEmpty()) { - Map copy = interfaces.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDataDefinition(e.getValue()))); - topologyTemplate.setInterfaces(copy); - } - } - - private static void convertServiceInterfaces(Service service, TopologyTemplate topologyTemplate) { - Map interfaces = service.getInterfaces(); - if (interfaces != null && !interfaces.isEmpty()) { - Map copy = interfaces.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDataDefinition(e.getValue()))); - topologyTemplate.setInterfaces(copy); - } - } - - private static void convertServiceSpecificEntities(Service service, TopologyTemplate topologyTemplate) { - convertServiceMetaData(service, topologyTemplate); - convertServiceApiArtifacts(service, topologyTemplate); - convertServicePaths(service,topologyTemplate); - convertServiceInterfaces(service, topologyTemplate); - } - - private static void convertServicePaths(Service service, TopologyTemplate topologyTemplate) { - Map servicePaths = service.getForwardingPaths(); - if (servicePaths != null && !servicePaths.isEmpty()) { - Map copy = servicePaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ForwardingPathDataDefinition(e.getValue()))); - topologyTemplate.setForwardingPaths(copy); - } - } - - private static void convertServiceMetaData(Service service, TopologyTemplate topologyTemplate) { - if (service.getDistributionStatus() != null) { - topologyTemplate.setMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS, - service.getDistributionStatus().name()); - } - topologyTemplate.setMetadataValue(JsonPresentationFields.PROJECT_CODE, service.getProjectCode()); - topologyTemplate.setMetadataValue(JsonPresentationFields.ECOMP_GENERATED_NAMING, - service.isEcompGeneratedNaming()); - topologyTemplate.setMetadataValue(JsonPresentationFields.NAMING_POLICY, service.getNamingPolicy()); - topologyTemplate.setMetadataValue(JsonPresentationFields.ENVIRONMENT_CONTEXT, service.getEnvironmentContext()); - topologyTemplate.setMetadataValue(JsonPresentationFields.INSTANTIATION_TYPE, service.getInstantiationType()); - - } - - private static void convertRelationsToComposition(Component component, TopologyTemplate topologyTemplate) { - List componentInstancesRelations = component.getComponentInstancesRelations(); - if (componentInstancesRelations != null) { - Map compositions = topologyTemplate.getCompositions(); - if (compositions == null) { - compositions = new HashMap<>(); - } - CompositionDataDefinition compositionDataDefinition = compositions.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - if (compositionDataDefinition == null) { - compositionDataDefinition = new CompositionDataDefinition(); - compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), compositionDataDefinition); - } - - Map relations = componentInstancesRelations.stream().flatMap(x -> convertRelationToToscaRelation(x).stream()).filter(i -> i.getUniqueId() != null) - .collect(Collectors.toMap(RelationshipInstDataDefinition::getUniqueId, Function.identity())); - compositionDataDefinition.setRelations(relations); - } - } - - private static void convertInputs(Component component, TopologyTemplate topologyTemplate) { - List inputsList = component.getInputs(); - if (inputsList != null && !inputsList.isEmpty()) { - - Map inputsMap = inputsList.stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity())); - topologyTemplate.setInputs(inputsMap); - } - - } - - private static void convertInputs(TopologyTemplate topologyTemplate, Component component) { - Map inputsMap = topologyTemplate.getInputs(); - if (inputsMap != null && !inputsMap.isEmpty()) { - List inputsList = inputsMap.values() - .stream() - .map(InputDefinition::new) - .collect(Collectors.toList()); - component.setInputs(inputsList); - } - } - - private static void convertProperties(Component component, TopologyTemplate topologyTemplate) { - List propertiesList = component.getProperties(); - if (propertiesList != null && !propertiesList.isEmpty()) { - Map propertiesMap = propertiesList.stream().map(i -> new PropertyDataDefinition(i)).collect(Collectors.toMap(i -> i.getName(), i -> i)); - topologyTemplate.setProperties(propertiesMap); - } - - } - - private static void convertProperties(TopologyTemplate topologyTemplate, Component component) { - Map proeprtiesMap = topologyTemplate.getProperties(); - if (proeprtiesMap != null && !proeprtiesMap.isEmpty()) { - Map copy = proeprtiesMap.entrySet().stream() - .collect(Collectors.toMap(entry -> entry.getKey(), entry -> new PropertyDefinition - (entry.getValue()))); - component.setProperties(new ArrayList<>(copy.values())); - } - } - - private static void convertDataTypes(TopologyTemplate topologyTemplate, Component component) { - Map dataTypeDataMap = topologyTemplate.getDataTypes(); - if (MapUtils.isNotEmpty(dataTypeDataMap)) { - List dataTypeMap = dataTypeDataMap.values().stream().map(e -> { - DataTypeDefinition dataType = new DataTypeDefinition(e); - - if(CollectionUtils.isNotEmpty(e.getPropertiesData())) { - log.debug("#convertDataTypes - propertiesData is not null. {}", - ReflectionToStringBuilder.toString(e.getPropertiesData())); - dataType.setProperties(e.getPropertiesData().stream() - .map(PropertyDefinition::new).collect(Collectors.toList())); - } else { - log.debug("#convertDataTypes - propertiesData is null. ignore."); - } - return dataType; - }).collect(Collectors.toList()); - component.setDataTypes(dataTypeMap); - } - } - - - private static void convertCommonToscaData(Component component, ToscaElement toscaElement) { - toscaElement.setUUID(component.getUUID()); - toscaElement.setUniqueId(component.getUniqueId()); - toscaElement.setSystemName(component.getSystemName()); - toscaElement.setLifecycleState(component.getLifecycleState()); - toscaElement.setComponentType(component.getComponentType()); - toscaElement.setNormalizedName(component.getNormalizedName()); - toscaElement.setMetadataValue(JsonPresentationFields.NAME, component.getName()); - toscaElement.setCategories(component.getCategories()); - toscaElement.setCreatorUserId(component.getCreatorUserId()); - toscaElement.setCreationDate(component.getCreationDate()); - toscaElement.setCreatorFullName(component.getCreatorFullName()); - toscaElement.setHighestVersion(component.isHighestVersion()); - toscaElement.setLastUpdateDate(component.getLastUpdateDate()); - toscaElement.setLastUpdaterFullName(component.getLastUpdaterFullName()); - toscaElement.setLastUpdaterUserId(component.getLastUpdaterUserId()); - toscaElement.setDerivedFromGenericType(component.getDerivedFromGenericType()); - toscaElement.setDerivedFromGenericVersion(component.getDerivedFromGenericVersion()); - - //Archive - toscaElement.setArchived(component.isArchived() == null ? false : component.isArchived()); - toscaElement.setArchiveTime(component.getArchiveTime() == null ? 0L : component.getArchiveTime()); - toscaElement.setVspArchived(component.isVspArchived() == null ? false : component.isVspArchived()); - - toscaElement.setLifecycleState(component.getLifecycleState()); - toscaElement.setMetadataValue(JsonPresentationFields.VERSION, component.getVersion()); - if (component.getComponentType() == ComponentTypeEnum.RESOURCE) { - toscaElement.setMetadataValue(JsonPresentationFields.IS_ABSTRACT, ((Resource) component).isAbstract()); - toscaElement.setMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME, ((Resource) component).getToscaResourceName()); - toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_NAME, ((Resource) component).getVendorName()); - toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_RELEASE, ((Resource) component).getVendorRelease()); - // field isn't mandatory , but shouldn't be null(should be an empty string instead) - if (((Resource) component).getResourceVendorModelNumber() != null){ - toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, ((Resource) component).getResourceVendorModelNumber()); - } else { - toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, ""); - } - } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) { - // field isn't mandatory , but shouldn't be null(should be an empty string instead) - if (((Service) component).getServiceType() != null){ - toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, ((Service) component).getServiceType()); - } else { - toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, ""); - } - if (((Service) component).getServiceRole() != null){ - toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, ((Service) component).getServiceRole()); - } else { - toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, ""); - } - } - toscaElement.setMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL, component.getConformanceLevel()); - toscaElement.setMetadataValue(JsonPresentationFields.IS_DELETED, component.getIsDeleted()); - toscaElement.setMetadataValue(JsonPresentationFields.ICON, component.getIcon()); - toscaElement.setMetadataValue(JsonPresentationFields.DESCRIPTION, component.getDescription()); - toscaElement.setMetadataValue(JsonPresentationFields.TAGS, component.getTags()); - toscaElement.setMetadataValue(JsonPresentationFields.INVARIANT_UUID, component.getInvariantUUID()); - toscaElement.setMetadataValue(JsonPresentationFields.CONTACT_ID, component.getContactId()); - } - - - - - private static void setComponentInstancesToComponent(TopologyTemplate topologyTemplate, Component component) { - - List componentInstances = new ArrayList<>(); - ComponentInstance currComponentInstance; - Map nodeFilterComponents = topologyTemplate.getNodeFilterComponents(); - - for (Map.Entry entry : topologyTemplate.getComponentInstances().entrySet()) { - String key = entry.getKey(); - currComponentInstance = new ComponentInstance(topologyTemplate.getComponentInstances().get(key)); - if (topologyTemplate.getInstGroups() != null && topologyTemplate.getInstGroups().containsKey(key)) { - List groupInstances = topologyTemplate.getInstGroups().get(key).getMapToscaDataDefinition().entrySet().stream().map(e -> new GroupInstance(e.getValue())).collect(Collectors.toList()); - currComponentInstance.setGroupInstances(groupInstances); - } - if(nodeFilterComponents != null && nodeFilterComponents.containsKey(key)){ - currComponentInstance.setNodeFilter(nodeFilterComponents.get(key)); - } - if(topologyTemplate.getInstProperties() != null && topologyTemplate.getInstProperties().containsKey(key) && topologyTemplate.getInstProperties().get(key) != null ){ - List instanceProps = topologyTemplate.getInstProperties().get(key).getMapToscaDataDefinition().entrySet().stream().map(e -> new PropertyDefinition(e.getValue())).collect(Collectors.toList()); - currComponentInstance.setProperties(instanceProps); - } - if(topologyTemplate.getInstInputs() != null && topologyTemplate.getInstInputs().containsKey(key) && topologyTemplate.getInstInputs().get(key) != null ){ - List instanceInputs = topologyTemplate.getInstInputs().get(key).getMapToscaDataDefinition().entrySet().stream().map(e -> new InputDefinition(e.getValue())).collect(Collectors.toList()); - currComponentInstance.setInputs(instanceInputs); - } - if(topologyTemplate.getComponentInstInterfaces() != null && topologyTemplate.getComponentInstInterfaces().containsKey(key) && topologyTemplate.getComponentInstInterfaces().get(key) != null ){ - Map interfacesMap = topologyTemplate.getComponentInstInterfaces().get(key).getMapToscaDataDefinition().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - currComponentInstance.setInterfaces(interfacesMap); - } - componentInstances.add(currComponentInstance); - - } - component.setComponentInstances(componentInstances); - } - - private static void setComponentInstancesInputsToComponent(TopologyTemplate topologyTemplate, Component component) { - if (topologyTemplate.getInstInputs() != null) { - Map> inputs = new HashMap<>(); - for (Entry entry : topologyTemplate.getInstInputs().entrySet()) { - if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { - String key = entry.getKey(); - List componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceInput(e.getValue())).collect(Collectors.toList()); - inputs.put(key, componentInstanceAttributes); - } - } - component.setComponentInstancesInputs(inputs); - } - } - - private static void setComponentInstancesPropertiesToComponent(TopologyTemplate topologyTemplate, Component component) { - if (topologyTemplate.getInstProperties() != null) { - Map> properties = new HashMap<>(); - for (Entry entry : topologyTemplate.getInstProperties().entrySet()) { - if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { - String key = entry.getKey(); - List componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceProperty(new PropertyDefinition(e.getValue()))) - .collect(Collectors.toList()); - properties.put(key, componentInstanceAttributes); - } - } - component.setComponentInstancesProperties(properties); - } - } - - private static void setComponentInstancesInterfacesToComponent(TopologyTemplate topologyTemplate, Component component) { - if (topologyTemplate.getInstInterfaces() != null) { - Map> interfaces = new HashMap<>(); - for (Entry entry : topologyTemplate.getInstInterfaces().entrySet()) { - if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { - String key = entry.getKey(); - List componentInstanceInterfaces = entry.getValue() - .getMapToscaDataDefinition().entrySet().stream().map(e -> new - ComponentInstanceInterface(e.getKey(), e.getValue())) - .collect(Collectors.toList()); - interfaces.put(key, componentInstanceInterfaces); - } - } - component.setComponentInstancesInterfaces(interfaces); - } - else if (topologyTemplate.getComponentInstInterfaces() != null) { - Map> interfaces = new HashMap<>(); - for (Entry entry : topologyTemplate.getComponentInstInterfaces().entrySet()) { - if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { - String key = entry.getKey(); - List componentInstanceInterfaces = entry.getValue() - .getMapToscaDataDefinition().entrySet().stream().map(e -> new - ComponentInstanceInterface(e.getKey(), e.getValue())) - .collect(Collectors.toList()); - interfaces.put(key, componentInstanceInterfaces); - } - } - component.setComponentInstancesInterfaces(interfaces); - } - - } - - private static void setComponentInstancesAttributesToComponent(TopologyTemplate topologyTemplate, Component component) { - if (topologyTemplate.getInstAttributes() != null) { - Map> attributes = new HashMap<>(); - for (Map.Entry entry : topologyTemplate.getInstAttributes().entrySet()) { - if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { - String key = entry.getKey(); - List componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceProperty(new ComponentInstanceProperty(e.getValue()))) - .collect(Collectors.toList()); - attributes.put(key, componentInstanceAttributes); - } - } - component.setComponentInstancesAttributes(attributes); - } - } - - private static void setComponentInstancesRequirementsToComponent(TopologyTemplate topologyTemplate, Component component) { - - if (topologyTemplate.getCalculatedRequirements() != null) { - // Requirements of component organized by capability - Map> instancesRequirements = new HashMap<>(); - - Map instancesMap = new HashMap<>(); - for (ComponentInstance currInstance : component.getComponentInstances()) { - instancesMap.put(currInstance.getUniqueId(), currInstance); - } - for (Map.Entry entry : topologyTemplate.getCalculatedRequirements().entrySet()) { - - String instanceId = entry.getKey(); - // Requirements of instance organized by capability - Map capsMapList = entry.getValue().getMapToscaDataDefinition(); - - if(capsMapList != null) { - for (Entry entryTypeList : capsMapList.entrySet()) { - String capabilityType = entryTypeList.getKey(); - List caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(RequirementDefinition::new).collect(Collectors.toList()); - if (instancesRequirements.containsKey(capabilityType)) { - instancesRequirements.get(capabilityType).addAll(caps); - } else { - instancesRequirements.put(capabilityType, caps); - } - if (MapUtils.isEmpty(instancesMap.get(instanceId).getRequirements())) { - instancesMap.get(instanceId).setRequirements(new HashMap<>()); - } - instancesMap.get(instanceId).getRequirements().put(capabilityType, new ArrayList<>(caps)); - } - } - } - component.setRequirements(instancesRequirements); - } - } - - private static void setComponentInstancesCapabilitiesToComponentAndCI(TopologyTemplate topologyTemplate, Component component) { - Map calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties(); - - if (topologyTemplate.getCalculatedCapabilities() != null) { - // capabilities of component organized by type - Map> instancesCapabilities = new HashMap<>(); - - Map instancesMap = new HashMap<>(); - for (ComponentInstance currInstance : component.getComponentInstances()) { - instancesMap.put(currInstance.getUniqueId(), currInstance); - } - for (Map.Entry entry : topologyTemplate.getCalculatedCapabilities().entrySet()) { - - String instanceId = entry.getKey(); - // capabilities of instance organized by type - Map capsMapList = entry.getValue().getMapToscaDataDefinition(); - - if(capsMapList != null) { - for (Entry entryTypeList : capsMapList.entrySet()) { - String capabilityType = entryTypeList.getKey(); - List caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(cap -> mergeInstCapabiltyWithProperty(cap, instanceId, calculatedCapProperties)).collect(Collectors.toList()); - if (instancesCapabilities.containsKey(capabilityType)) { - instancesCapabilities.get(capabilityType).addAll(caps); - } else { - instancesCapabilities.put(capabilityType, caps); - } - ComponentInstance instance = instancesMap.get(instanceId); - if (instance == null) { - log.error("instance is null for id {} entry {}", instanceId, entry.getValue().getToscaPresentationValue(JsonPresentationFields.NAME)); - } else { - if (MapUtils.isEmpty(instance.getCapabilities())) { - instance.setCapabilities(new HashMap<>()); - } - instance.getCapabilities().put(capabilityType, new ArrayList<>(caps)); - } - } - } - } - component.setCapabilities(instancesCapabilities); - } - } - - private static void setCapabilitiesToComponent(TopologyTemplate topologyTemplate, Component component) { - Map capabilities = topologyTemplate.getCapabilities(); - Map capabilitiesProperties = topologyTemplate.getCapabilitiesProperties(); - Map> allCapabilities = new HashMap<>(); - - if(MapUtils.isNotEmpty(capabilities)) { - allCapabilities.putAll(groupCapabilityByType(capabilities)); - } - - if(MapUtils.isNotEmpty(capabilitiesProperties)) { - capabilitiesProperties.forEach((s, capProp)-> { - String[] result = s.split(CAP_PROP_DELIM); - if (capProp != null) { - Map capMap = capProp.getMapToscaDataDefinition(); - - if (MapUtils.isNotEmpty(capMap)) { - List capPropsList = capMap.values().stream() - .map(ComponentInstanceProperty::new).collect(Collectors.toList()); - - List cap = allCapabilities.get(result[0]); - if (cap !=null) { - Optional op = cap.stream().filter(c -> c.getName() - .equals(result[1])).findFirst(); - op.ifPresent(capabilityDefinition -> capabilityDefinition.setProperties(capPropsList)); - } - } - } - } - ); - } - Map> componentCapabilities = component.getCapabilities(); - if(MapUtils.isNotEmpty(componentCapabilities)) { - mergeCapabilityMap(allCapabilities, componentCapabilities); - } - component.setCapabilities(allCapabilities); - } - - private static void mergeCapabilityMap(Map> map1, - Map> map2) { - map1.forEach((key1, val1) -> map2.forEach((key2, val2) -> { - if(key1.equals(key2)) { - val2.addAll(val1); - } - })); - map1.putAll(map2); - } - - private static Map> groupCapabilityByType(Map capabilities) { - Map> groupedCapabilities = new HashMap<>(); - - Set typesSet = new HashSet<>(); - List allCapabilityDefinitions = new ArrayList<>(); - for (Entry capabilitiesEntry : capabilities.entrySet()) { - typesSet.addAll( capabilitiesEntry.getValue().getListToscaDataDefinition() - .stream().map(CapabilityDataDefinition::getType).collect(Collectors.toSet())); - - allCapabilityDefinitions.addAll(capabilitiesEntry.getValue().getListToscaDataDefinition() - .stream().map(CapabilityDefinition::new).collect(Collectors.toList())); - } - - for(String capType : typesSet) { - groupedCapabilities.put(capType, allCapabilityDefinitions.stream() - .filter(capabilityDefinition -> capabilityDefinition.getType() - .equals(capType)).collect(Collectors.toList())); - } - return groupedCapabilities; - } - - private static void setRequirementsToComponent(TopologyTemplate topologyTemplate, Component component) { - Map requirements = topologyTemplate.getRequirements(); - Map> componentRequirements = component.getRequirements(); - if(MapUtils.isNotEmpty(requirements)) { - if(componentRequirements == null) { - componentRequirements = new HashMap<>(); - } - componentRequirements.putAll(groupRequirementByType(requirements)); - component.setRequirements(componentRequirements); - } - } - - private static Map> groupRequirementByType(Map requirements) { - Map> groupedRequirement = new HashMap<>(); - - Set typesSet = new HashSet<>(); - List allRequirements = new ArrayList<>(); - for (Entry requirementsEntry : requirements.entrySet()) { - typesSet.addAll( requirementsEntry.getValue().getListToscaDataDefinition() - .stream().map(RequirementDataDefinition::getCapability).collect(Collectors.toSet())); - - allRequirements.addAll(requirementsEntry.getValue().getListToscaDataDefinition() - .stream().map(RequirementDefinition::new).collect(Collectors.toList())); - } - - for(String capType : typesSet) { - groupedRequirement.put(capType, allRequirements.stream().filter(requirementDefinition -> - requirementDefinition.getCapability().equals(capType)).collect(Collectors.toList())); - } - return groupedRequirement; - - } - - - private static void setCapabilitiesToComponentAndGroups(TopologyTemplate topologyTemplate, Component component) { - - Map calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties(); - - if (capabilitiesAndGroupsExist(topologyTemplate, component)) { - Map groupsMap = component.getGroups().stream().collect(Collectors.toMap(GroupDefinition::getUniqueId,Function.identity())); - - for (Map.Entry entry : topologyTemplate.getCalculatedCapabilities().entrySet()) { - findSetCapabilitiesToComponentAndGroup(calculatedCapProperties, component, groupsMap, entry); - } - } - } - - private static boolean capabilitiesAndGroupsExist(TopologyTemplate topologyTemplate, Component component) { - return MapUtils.isNotEmpty(topologyTemplate.getCalculatedCapabilities()) && CollectionUtils.isNotEmpty(component.getGroups()); - } - - private static void findSetCapabilitiesToComponentAndGroup(Map calculatedCapProperties, Component component, Map groupsMap, Map.Entry entry) { - - String uniqueId = entry.getKey(); - if(groupsMap.containsKey(uniqueId)){ - setCapabilitiesToComponentAndGroup(calculatedCapProperties, component, entry, groupsMap.get(uniqueId)); - } else { - log.warn("The group with uniqueId {} was not found", uniqueId); - } - } - - private static void setCapabilitiesToComponentAndGroup(Map calculatedCapProperties, Component component, Map.Entry entry, GroupDefinition group) { - - for (Entry entryTypeList : entry.getValue().getMapToscaDataDefinition().entrySet()) { - String capabilityType = entryTypeList.getKey(); - List caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(cap -> mergeInstCapabiltyWithProperty(cap, group.getUniqueId(), calculatedCapProperties)).collect(Collectors.toList()); - if (component.getCapabilities().containsKey(capabilityType)) { - component.getCapabilities().get(capabilityType).addAll(caps); - } else { - component.getCapabilities().put(capabilityType, caps); - } - group.getCapabilities().put(capabilityType, Lists.newArrayList(caps)); - } - } - - private static CapabilityDefinition mergeInstCapabiltyWithProperty(CapabilityDataDefinition cap, String ownerId, Map calculatedCapProperties) { - CapabilityDefinition capability = new CapabilityDefinition(cap); - if (calculatedCapProperties != null) { - MapCapabilityProperty mapOfMapPropertiesDataDefinition = calculatedCapProperties.get(ownerId); - if (mapOfMapPropertiesDataDefinition != null && mapOfMapPropertiesDataDefinition.getMapToscaDataDefinition() != null) { - Map toscaCapPropMap = mapOfMapPropertiesDataDefinition.getMapToscaDataDefinition(); - toscaCapPropMap.forEach(( keyPath, capProp)-> findConvertSetProperties(cap, ownerId, capability, keyPath, capProp)); - } - } - return capability; - } - - private static void findConvertSetProperties(CapabilityDataDefinition cap, String primaryPathKey, CapabilityDefinition capability, String path, MapPropertiesDataDefinition capProp) { - // format key of capability properties : - // VF instance in service : instanceId#ownerId#type#capName - // VFC instance in VF : instanceId#type#capName -> instanceId=ownerId - // Group in service : groupName#ownerId#type#capName - // Group in VF : groupName#type#capName -> groupName=ownerId - String[] result = path.split(CAP_PROP_DELIM); - if (result.length < 4) { - log.debug("wrong key format for capabilty, key {}", capProp); - return; - } - if (relatedPropertiesExist(cap, primaryPathKey, capProp, result)) { - capability.setProperties(capProp.getMapToscaDataDefinition().values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList())); - } - } - - private static boolean relatedPropertiesExist(CapabilityDataDefinition cap, String primaryPathKey, MapPropertiesDataDefinition capProp, String[] result) { - return capProp != null && MapUtils.isNotEmpty(capProp.getMapToscaDataDefinition()) && areRelatedProperties(cap, primaryPathKey, result); - } - - private static boolean areRelatedProperties(CapabilityDataDefinition cap, String primaryPathKey, String[] result) { - int primaryKeyIndex = 0; - int ownerIndex = 1; - int typeIndex = result.length - 2; - int nameIndex = result.length - 1; - return result[typeIndex].equals(cap.getType()) && result[nameIndex].equals(cap.getName()) && cap.getOwnerId().equals(result[ownerIndex]) && primaryPathKey.equals(result[primaryKeyIndex]); - } - - private static void setComponentInstancesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { - - Map componentInstances = new HashMap<>(); - ComponentInstanceDataDefinition convertedInstance; - if (component.getComponentInstances() != null) { - for (ComponentInstance instance : component.getComponentInstances()) { - convertedInstance = new ComponentInstanceDataDefinition(instance); - if (instance.getGroupInstances() != null) { - MapGroupsDataDefinition groupsMap = new MapGroupsDataDefinition(); - - groupsMap.setMapToscaDataDefinition(instance.getGroupInstances().stream().map(GroupInstanceDataDefinition::new).collect(Collectors.toMap(GroupInstanceDataDefinition::getName, Function.identity()))); - if (topologyTemplate.getInstGroups() == null) { - topologyTemplate.setInstGroups(new HashMap<>()); - } - topologyTemplate.getInstGroups().put(instance.getUniqueId(), groupsMap); - } - componentInstances.put(instance.getUniqueId(), convertedInstance); - } - } - topologyTemplate.setComponentInstances(componentInstances); - - } - - private static void setComponentInstancesInputsToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { - - if (component.getComponentInstancesInputs() != null) { - topologyTemplate.setInstInputs(new HashMap<>()); - MapPropertiesDataDefinition inputsMap; - for (Entry> entry : component.getComponentInstancesInputs().entrySet()) { - inputsMap = new MapPropertiesDataDefinition(); - - inputsMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity()))); - - topologyTemplate.getInstInputs().put(entry.getKey(), inputsMap); - } - } - } - - private static void setComponentInstancesPropertiesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { - - if (component.getComponentInstancesProperties() != null) { - topologyTemplate.setInstProperties(new HashMap<>()); - MapPropertiesDataDefinition propertiesMap; - for (Entry> entry : component.getComponentInstancesProperties().entrySet()) { - propertiesMap = new MapPropertiesDataDefinition(); - - propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity()))); - - topologyTemplate.getInstProperties().put(entry.getKey(), propertiesMap); - } - } - } - - private static void setComponentInstancesArtifactsToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { - - List componentInstances = component.getComponentInstances(); - if (componentInstances != null) { - topologyTemplate.setInstanceArtifacts(new HashMap<>()); - topologyTemplate.setInstDeploymentArtifacts(new HashMap<>()); - - for (ComponentInstance ci : componentInstances) { - Map artifacts = ci.getArtifacts(); - if (artifacts != null) { - Map mapToscaDataDefinitionArtifact = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - MapArtifactDataDefinition insArtifact = new MapArtifactDataDefinition(mapToscaDataDefinitionArtifact); - topologyTemplate.getInstanceArtifacts().put(ci.getUniqueId(), insArtifact); - } - - Map deplArtifacts = ci.getDeploymentArtifacts(); - if (deplArtifacts != null) { - Map mapToscaDataDefinitionDepArtifact = deplArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - MapArtifactDataDefinition insDepArtifact = new MapArtifactDataDefinition(mapToscaDataDefinitionDepArtifact); - topologyTemplate.getInstDeploymentArtifacts().put(ci.getUniqueId(), insDepArtifact); - } - } - } - } - - private static void setComponentInstancesAttributesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { - - if (component.getComponentInstancesAttributes() != null) { - topologyTemplate.setInstAttributes(new HashMap<>()); - MapPropertiesDataDefinition attributesMap; - for (Entry> entry : component.getComponentInstancesAttributes().entrySet()) { - attributesMap = new MapPropertiesDataDefinition(); - - attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity()))); - - topologyTemplate.getInstAttributes().put(entry.getKey(), attributesMap); - } - } - } - - public static ComponentMetadataData convertToComponentMetadata(GraphVertex vertex) { - ComponentMetadataData metadata = null; - switch (vertex.getType()) { - case SERVICE: - metadata = new ServiceMetadataData(vertex.getMetadataJson()); - break; - case RESOURCE: - metadata = new ResourceMetadataData(vertex.getMetadataJson()); - break; - case PRODUCT: - metadata = new ProductMetadataData(vertex.getMetadataJson()); - break; - default: - break; - } - if (metadata != null) { - metadata.getMetadataDataDefinition().setUniqueId(vertex.getUniqueId()); - metadata.getMetadataDataDefinition().setLastUpdateDate((Long) vertex.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE)); - metadata.getMetadataDataDefinition().setUUID((String) vertex.getJsonMetadataField(JsonPresentationFields.UUID)); - metadata.getMetadataDataDefinition().setState((String) vertex.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)); - } - return metadata; - } - - public static List convertToGroupDefinitions(Map groups) { - - List groupDefinitions = null; - if (MapUtils.isNotEmpty(groups)) { - groupDefinitions = groups.values().stream().map(GroupDefinition::new).collect(Collectors.toList()); - } - return groupDefinitions; - } - - public static Map extractCapabilityProperteisFromInstances(List instances, boolean fromCsar) { - return instances - .stream() - .collect(Collectors.toMap(ComponentInstanceDataDefinition::getUniqueId, - ci -> convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), ci.getUniqueId(), fromCsar))); - } - - public static Map extractCapabilityPropertiesFromGroups(List groups, boolean fromCsar) { - if(CollectionUtils.isNotEmpty(groups)) - return groups - .stream() - .collect(Collectors.toMap(GroupDefinition::getUniqueId, - g -> convertToMapOfMapCapabiltyProperties(g.getCapabilities(), g.getUniqueId(), fromCsar))); - return Maps.newHashMap(); - } - - public static Map extractCapabilitiesFromGroups(final List groupDefinitions) { - Map calculatedCapabilities = Maps.newHashMap(); - for(GroupDefinition groupDefinition :groupDefinitions){ - calculatedCapabilities.put(groupDefinition.getUniqueId(), new MapListCapabilityDataDefinition(buildMapOfListsOfCapabilities(groupDefinition))); - } - return calculatedCapabilities; - } - - public static Map buildMapOfListsOfCapabilities(GroupDefinition groupDefinition) { - return groupDefinition.getCapabilities().entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, e-> new ListCapabilityDataDefinition(e.getValue() - .stream() - .map(CapabilityDataDefinition::new) - .collect(Collectors.toList())))); - } - -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java index 40c39f3405..e75533f447 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java @@ -1,6 +1,6 @@ package org.openecomp.sdc.be.model.operations; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; @@ -15,14 +15,16 @@ public class StorageException extends RuntimeException{ this.params = params; } - public StorageException(String message, Throwable cause, TitanOperationStatus titanOperationStatus, String... params){ + public StorageException(String message, Throwable cause, JanusGraphOperationStatus janusGraphOperationStatus, String... params){ super(message, cause); - storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus); + storageOperationStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + janusGraphOperationStatus); this.params = params; } - public StorageException(TitanOperationStatus titanOperationStatus, String... params) { - storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus); + public StorageException(JanusGraphOperationStatus janusGraphOperationStatus, String... params) { + storageOperationStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + janusGraphOperationStatus); this.params = params; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAdditionalInformationOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAdditionalInformationOperation.java index 3fb58a0fa3..b1ce9de66e 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAdditionalInformationOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAdditionalInformationOperation.java @@ -20,9 +20,9 @@ package org.openecomp.sdc.be.model.operations.api; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.AdditionalInformationDefinition; @@ -32,19 +32,19 @@ import java.util.List; public interface IAdditionalInformationOperation { - public Either addAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key, String value); + public Either addAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key, String value); - public Either updateAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String origKey, String key, String value); + public Either updateAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String origKey, String key, String value); - public Either deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key); + public Either deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key); - public Either addAdditionalInformationNode(NodeTypeEnum nodeType, String resourceUniqueId); + public Either addAdditionalInformationNode(NodeTypeEnum nodeType, String resourceUniqueId); - public Either addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters); + public Either addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters); - public TitanOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId, List properties); + public JanusGraphOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId, List properties); - public TitanOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId, List properties); + public JanusGraphOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId, List properties); public Either createAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key, String value, boolean inTransaction); @@ -54,20 +54,20 @@ public interface IAdditionalInformationOperation { public Either getNumberOfAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction); - public Either getNumberOfParameters(NodeTypeEnum nodeType, String resourceId); + public Either getNumberOfParameters(NodeTypeEnum nodeType, String resourceId); - public Either getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id); + public Either getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id); public Either getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction); - public Either getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification); + public Either getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification); public Either getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification, boolean inTransaction); public Either deleteAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction); - public Either addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, TitanVertex matadatVertex); + public Either addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, JanusGraphVertex matadatVertex); - public TitanOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters, TitanVertex metadataVertex); + public JanusGraphOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters, JanusGraphVertex metadataVertex); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java index e1b04e9230..e3b7689d30 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 @@ -20,7 +20,7 @@ package org.openecomp.sdc.be.model.operations.api; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; @@ -37,6 +37,6 @@ public interface IArtifactOperation { public Either, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction); - public StorageOperationStatus addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, TitanVertex parentVertex); + public StorageOperationStatus addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, JanusGraphVertex parentVertex); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java index da059fe3ad..3525e1362e 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 @@ -21,13 +21,13 @@ package org.openecomp.sdc.be.model.operations.api; import fj.data.Either; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.model.PropertyDefinition; import java.util.Map; public interface ICapabilityOperation { - Either, TitanOperationStatus> getAllCapabilityTypePropertiesFromAllDerivedFrom(String firstParentType); + Either, JanusGraphOperationStatus> getAllCapabilityTypePropertiesFromAllDerivedFrom(String firstParentType); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java index 4316f733a7..780b9af70e 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java @@ -21,7 +21,7 @@ package org.openecomp.sdc.be.model.operations.api; import fj.data.Either; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import java.util.Map; @@ -46,5 +46,5 @@ public interface ICapabilityTypeOperation { public Either getCapabilityType(String uniqueId); public Either getCapabilityType(String uniqueId, boolean inTransaction); - Either, TitanOperationStatus> getAllCapabilityTypes(); + Either, JanusGraphOperationStatus> getAllCapabilityTypes(); } 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 0c03ee3bf0..100916fe9e 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 @@ -21,13 +21,13 @@ package org.openecomp.sdc.be.model.operations.api; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.resources.data.InputValueData; public interface IInputsOperation { - ImmutablePair findInputValue(String resourceInstanceId, String propertyId); + ImmutablePair findInputValue(String resourceInstanceId, String propertyId); ComponentInstanceInput buildResourceInstanceInput(InputValueData propertyValueData, ComponentInstanceInput resourceInstanceInput); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java index 3e987ed101..c53f3e3d86 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java @@ -24,7 +24,7 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.reflect.TypeToken; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import java.lang.reflect.Type; import java.util.List; @@ -37,9 +37,9 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; -import org.openecomp.sdc.be.dao.titan.HealingTitanGenericDao; -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; @@ -63,7 +63,7 @@ public abstract class AbstractOperation { private static final Logger log = Logger.getLogger(AbstractOperation.class.getName()); @Autowired - protected HealingTitanGenericDao titanGenericDao; + protected HealingJanusGraphGenericDao janusGraphGenericDao; public static final String EMPTY_VALUE = null; @@ -74,8 +74,8 @@ public abstract class AbstractOperation { protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); - protected Either addDefinitionToNodeType(SomeDefenition someDefinition, NodeTypeEnum nodeType, String nodeUniqueId, final GraphEdgeLabels edgeType, - Supplier dataBuilder, Supplier defNameGenerator) { + protected Either addDefinitionToNodeType(SomeDefenition someDefinition, NodeTypeEnum nodeType, String nodeUniqueId, final GraphEdgeLabels edgeType, + Supplier dataBuilder, Supplier defNameGenerator) { String defName = defNameGenerator.get(); log.debug("Got {} {}", defName, someDefinition); @@ -84,29 +84,31 @@ public abstract class AbstractOperation { log.debug("Before adding {} to graph. data = {}", defName, someData); @SuppressWarnings("unchecked") - Either eitherSomeData = titanGenericDao.createNode(someData, (Class) someData.getClass()); + Either eitherSomeData = janusGraphGenericDao + .createNode(someData, (Class) someData.getClass()); log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData); if (eitherSomeData.isRight()) { - TitanOperationStatus operationStatus = eitherSomeData.right().value(); + JanusGraphOperationStatus operationStatus = eitherSomeData.right().value(); log.error("Failed to add {} to graph. status is {}", defName, operationStatus); return Either.right(operationStatus); } UniqueIdData uniqueIdData = new UniqueIdData(nodeType, nodeUniqueId); log.debug("Before associating {} to {}.", uniqueIdData, defName); - Either eitherRelations = titanGenericDao.createRelation(uniqueIdData, eitherSomeData.left().value(), edgeType, null); + Either eitherRelations = janusGraphGenericDao + .createRelation(uniqueIdData, eitherSomeData.left().value(), edgeType, null); if (eitherRelations.isRight()) { - TitanOperationStatus operationStatus = eitherRelations.right().value(); + JanusGraphOperationStatus operationStatus = eitherRelations.right().value(); BeEcompErrorManager.getInstance().logInternalFlowError("AddDefinitionToNodeType", "Failed to associate" + nodeType.getName() + " " + nodeUniqueId + "to " + defName + "in graph. status is " + operationStatus, ErrorSeverity.ERROR); return Either.right(operationStatus); } return Either.left(eitherSomeData.left().value()); } - protected TitanOperationStatus addDefinitionToNodeType(TitanVertex vertex, SomeDefenition someDefinition, NodeTypeEnum nodeType, String nodeUniqueId, final GraphEdgeLabels edgeType, - Supplier dataBuilder, Supplier defNameGenerator) { + protected JanusGraphOperationStatus addDefinitionToNodeType(JanusGraphVertex vertex, SomeDefenition someDefinition, NodeTypeEnum nodeType, String nodeUniqueId, final GraphEdgeLabels edgeType, + Supplier dataBuilder, Supplier defNameGenerator) { String defName = defNameGenerator.get(); log.debug("Got {} {}", defName, someDefinition); @@ -115,18 +117,20 @@ public abstract class AbstractOperation { log.debug("Before adding {} to graph. data = {}", defName, someData); @SuppressWarnings("unchecked") - Either eitherSomeData = titanGenericDao.createNode(someData); + Either eitherSomeData = janusGraphGenericDao.createNode(someData); log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData); if (eitherSomeData.isRight()) { - TitanOperationStatus operationStatus = eitherSomeData.right().value(); + JanusGraphOperationStatus operationStatus = eitherSomeData.right().value(); log.error("Failed to add {} to graph. status is {}", defName, operationStatus); return operationStatus; } - TitanOperationStatus relations = titanGenericDao.createEdge(vertex, eitherSomeData.left().value(), edgeType, null); - if (!relations.equals(TitanOperationStatus.OK)) { + JanusGraphOperationStatus + relations = janusGraphGenericDao + .createEdge(vertex, eitherSomeData.left().value(), edgeType, null); + if (!relations.equals(JanusGraphOperationStatus.OK)) { BeEcompErrorManager.getInstance().logInternalFlowError("AddDefinitionToNodeType", "Failed to associate" + nodeType.getName() + " " + nodeUniqueId + "to " + defName + "in graph. status is " + relations, ErrorSeverity.ERROR); return relations; } @@ -134,25 +138,27 @@ public abstract class AbstractOperation { } interface NodeElementFetcher { - TitanOperationStatus findAllNodeElements(String nodeId, List listTofill); + JanusGraphOperationStatus findAllNodeElements(String nodeId, List listTofill); } - public TitanOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List elements, NodeElementFetcher singleNodeFetcher) { + public JanusGraphOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List elements, NodeElementFetcher singleNodeFetcher) { if (log.isTraceEnabled()) log.trace("Going to fetch elements under resource {}", resourceId); - TitanOperationStatus resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements); + JanusGraphOperationStatus + resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements); - if (resourceAttributesStatus != TitanOperationStatus.OK) { + if (resourceAttributesStatus != JanusGraphOperationStatus.OK) { return resourceAttributesStatus; } - Either, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, + Either, JanusGraphOperationStatus> parentNodes = janusGraphGenericDao + .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) { + JanusGraphOperationStatus parentNodesStatus = parentNodes.right().value(); + if (parentNodesStatus != JanusGraphOperationStatus.NOT_FOUND) { BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find parent elements of resource " + resourceId + ". status is " + parentNodesStatus, ErrorSeverity.ERROR); return parentNodesStatus; } @@ -161,25 +167,25 @@ public abstract class AbstractOperation { if (parentNodes.isLeft()) { ImmutablePair parnetNodePair = parentNodes.left().value(); String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - TitanOperationStatus addParentIntStatus = findAllResourceElementsDefinitionRecursively(parentUniqueId, elements, singleNodeFetcher); + JanusGraphOperationStatus addParentIntStatus = findAllResourceElementsDefinitionRecursively(parentUniqueId, elements, singleNodeFetcher); - if (addParentIntStatus != TitanOperationStatus.OK) { + if (addParentIntStatus != JanusGraphOperationStatus.OK) { BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find all resource elements of resource " + parentUniqueId, ErrorSeverity.ERROR); return addParentIntStatus; } } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } protected void handleTransactionCommitRollback(boolean inTransaction, Either result) { if (!inTransaction) { if (result == null || result.isRight()) { log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } @@ -212,7 +218,7 @@ public abstract class AbstractOperation { } String innerType = null; - Either checkInnerType = getInnerType(type, propertyDefinition::getSchema); + Either checkInnerType = getInnerType(type, propertyDefinition::getSchema); if (checkInnerType.isRight()) { return StorageOperationStatus.INVALID_TYPE; } @@ -300,19 +306,19 @@ public abstract class AbstractOperation { return value; } - protected Either getInnerType(ToscaPropertyType type, Supplier schemeGen) { + protected Either getInnerType(ToscaPropertyType type, Supplier schemeGen) { String innerType = null; if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { SchemaDefinition def = schemeGen.get(); if (def == null) { log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + return Either.right(JanusGraphOperationStatus.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); + return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT); } innerType = propDef.getType(); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java index ebec8b134b..f247bbb74d 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java @@ -20,7 +20,7 @@ package org.openecomp.sdc.be.model.operations.impl; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Vertex; @@ -29,10 +29,10 @@ 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.GraphRelation; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; 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.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -58,7 +58,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe private static final Logger log = Logger.getLogger(AdditionalInformationOperation.class.getName()); @javax.annotation.Resource - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; private static final String GOING_TO_EXECUTE_COMMIT_ON_GRAPH = "Going to execute commit on graph."; private static final String GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH = "Going to execute rollback on graph."; @@ -71,18 +71,20 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe @Override - public Either addAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String key, String value) { + public Either addAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String key, String value) { - TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); - if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { + JanusGraphOperationStatus + verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); + if (verifyNodeTypeVsComponent != JanusGraphOperationStatus.OK) { return Either.right(verifyNodeTypeVsComponent); } - Either, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + Either, JanusGraphOperationStatus> getResult = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (getResult.isRight()) { - TitanOperationStatus status = getResult.right().value(); + JanusGraphOperationStatus status = getResult.right().value(); return Either.right(status); } @@ -104,17 +106,18 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe if (parameters.containsKey(key)) { log.debug("The key {} already exists under component {}", key, componentId); - return Either.right(TitanOperationStatus.ALREADY_EXIST); + return Either.right(JanusGraphOperationStatus.ALREADY_EXIST); } idToKey.put(String.valueOf(lastCreatedCounter), key); parameters.put(key, value); parameterData.getAdditionalInfoParameterDataDefinition().setLastCreatedCounter(lastCreatedCounter); - Either updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); + Either updateNode = janusGraphGenericDao + .updateNode(parameterData, AdditionalInfoParameterData.class); if (updateNode.isRight()) { - TitanOperationStatus status = updateNode.right().value(); + JanusGraphOperationStatus status = updateNode.right().value(); BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status)); return Either.right(status); } @@ -126,18 +129,20 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either updateAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id, String key, String value) { + public Either updateAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id, String key, String value) { - TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); - if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { + JanusGraphOperationStatus + verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); + if (verifyNodeTypeVsComponent != JanusGraphOperationStatus.OK) { return Either.right(verifyNodeTypeVsComponent); } - Either, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + Either, JanusGraphOperationStatus> getResult = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (getResult.isRight()) { - TitanOperationStatus status = getResult.right().value(); + JanusGraphOperationStatus status = getResult.right().value(); return Either.right(status); } @@ -146,7 +151,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe Map parameters = parameterData.getParameters(); Map idToKey = parameterData.getIdToKey(); if (idToKey == null || !idToKey.containsKey(id)) { - return Either.right(TitanOperationStatus.INVALID_ID); + return Either.right(JanusGraphOperationStatus.INVALID_ID); } String origKey = idToKey.get(id); @@ -154,7 +159,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe if (!origKey.equals(key)) { if (parameters.containsKey(key)) { log.debug("The key {} already exists", key); - return Either.right(TitanOperationStatus.ALREADY_EXIST); + return Either.right(JanusGraphOperationStatus.ALREADY_EXIST); } String removed = parameters.remove(origKey); log.trace("The key-value {} = {} was removed from additionalInformation", origKey, removed); @@ -162,10 +167,11 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe parameters.put(key, value); idToKey.put(id, key); - Either updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); + Either updateNode = janusGraphGenericDao + .updateNode(parameterData, AdditionalInfoParameterData.class); if (updateNode.isRight()) { - TitanOperationStatus status = updateNode.right().value(); + JanusGraphOperationStatus status = updateNode.right().value(); BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter", "additional information of resource " + componentId, String.valueOf(status)); return Either.right(status); } @@ -177,18 +183,20 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) { + public Either deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) { - TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); - if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { + JanusGraphOperationStatus + verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); + if (verifyNodeTypeVsComponent != JanusGraphOperationStatus.OK) { return Either.right(verifyNodeTypeVsComponent); } - Either, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + Either, JanusGraphOperationStatus> getResult = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (getResult.isRight()) { - TitanOperationStatus status = getResult.right().value(); + JanusGraphOperationStatus status = getResult.right().value(); return Either.right(status); } @@ -198,7 +206,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe Map idToKey = parameterData.getIdToKey(); if (idToKey == null || !idToKey.containsKey(id)) { - return Either.right(TitanOperationStatus.INVALID_ID); + return Either.right(JanusGraphOperationStatus.INVALID_ID); } String key = idToKey.get(id); @@ -206,10 +214,11 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe String removedValue = parameters.remove(key); log.trace("The key-value {} = {} was removed from additionalInformation", removedKey, removedValue); - Either updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); + Either updateNode = janusGraphGenericDao + .updateNode(parameterData, AdditionalInfoParameterData.class); if (updateNode.isRight()) { - TitanOperationStatus status = updateNode.right().value(); + JanusGraphOperationStatus status = updateNode.right().value(); BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("DeleteAdditionalInformationParameter", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status)); return Either.right(status); } @@ -248,7 +257,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId) { + public Either addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId) { UniqueIdData from = new UniqueIdData(nodeType, componentId); @@ -258,18 +267,20 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(additionalInfoParameterDataDefinition, new HashMap<>(), new HashMap<>()); - Either createNode = titanGenericDao.createNode(additionalInfoParameterData, AdditionalInfoParameterData.class); + Either createNode = janusGraphGenericDao + .createNode(additionalInfoParameterData, AdditionalInfoParameterData.class); if (createNode.isRight()) { - TitanOperationStatus status = createNode.right().value(); + JanusGraphOperationStatus status = createNode.right().value(); BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("AddAdditionalInformationNode", uniqueId, String.valueOf(status)); return Either.right(status); } AdditionalInfoParameterData to = createNode.left().value(); - Either createRelation = titanGenericDao.createRelation(from, to, GraphEdgeLabels.ADDITIONAL_INFORMATION, null); + Either createRelation = janusGraphGenericDao + .createRelation(from, to, GraphEdgeLabels.ADDITIONAL_INFORMATION, null); if (createRelation.isRight()) { - TitanOperationStatus status = createRelation.right().value(); + JanusGraphOperationStatus status = createRelation.right().value(); return Either.right(status); } @@ -277,7 +288,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, TitanVertex metadataVertex) { + public Either addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, JanusGraphVertex metadataVertex) { String uniqueId = UniqueIdBuilder.buildAdditionalInformationUniqueId(componentId); AdditionalInfoParameterDataDefinition additionalInfoParameterDataDefinition = new AdditionalInfoParameterDataDefinition(); @@ -285,26 +296,27 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(additionalInfoParameterDataDefinition, new HashMap<>(), new HashMap<>()); - Either createNode = titanGenericDao.createNode(additionalInfoParameterData); + Either createNode = janusGraphGenericDao.createNode(additionalInfoParameterData); if (createNode.isRight()) { - TitanOperationStatus status = createNode.right().value(); + JanusGraphOperationStatus status = createNode.right().value(); BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("AddAdditionalInformationNode", uniqueId, String.valueOf(status)); return Either.right(status); } - TitanVertex additionalInfoVertex = createNode.left().value(); + JanusGraphVertex additionalInfoVertex = createNode.left().value(); - TitanOperationStatus createRelation = titanGenericDao.createEdge(metadataVertex, additionalInfoVertex, GraphEdgeLabels.ADDITIONAL_INFORMATION, null); + JanusGraphOperationStatus createRelation = janusGraphGenericDao + .createEdge(metadataVertex, additionalInfoVertex, GraphEdgeLabels.ADDITIONAL_INFORMATION, null); - if (!createRelation.equals(TitanOperationStatus.OK)) { + if (!createRelation.equals(JanusGraphOperationStatus.OK)) { return Either.right(createRelation); } return Either.left(additionalInfoVertex); } - public Either addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters) { + public Either addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters) { - Either status = this.addAdditionalInformationNode(nodeType, componentId); + Either status = this.addAdditionalInformationNode(nodeType, componentId); if (status.isRight()) { return Either.right(status.right().value()); @@ -314,7 +326,8 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe populateParameterNodeWithParameters(parameterData, parameters); - Either updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); + Either updateNode = janusGraphGenericDao + .updateNode(parameterData, AdditionalInfoParameterData.class); if (updateNode.isRight()) { return Either.right(updateNode.right().value()); @@ -325,21 +338,21 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe return Either.left(informationDefinition); } - public TitanOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters, TitanVertex metadataVertex) { + public JanusGraphOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters, JanusGraphVertex metadataVertex) { - Either status = this.addAdditionalInformationNode(nodeType, componentId, metadataVertex); + Either status = this.addAdditionalInformationNode(nodeType, componentId, metadataVertex); if (status.isRight()) { return status.right().value(); } - TitanVertex additionalInfoVertex = status.left().value(); + JanusGraphVertex additionalInfoVertex = status.left().value(); - Map newProp = titanGenericDao.getProperties(additionalInfoVertex); + Map newProp = janusGraphGenericDao.getProperties(additionalInfoVertex); AdditionalInfoParameterData parameterData = GraphElementFactory.createElement(NodeTypeEnum.AdditionalInfoParameters.getName(), GraphElementTypeEnum.Node, newProp, AdditionalInfoParameterData.class); populateParameterNodeWithParameters(parameterData, parameters); - return titanGenericDao.updateVertex(parameterData, additionalInfoVertex); + return janusGraphGenericDao.updateVertex(parameterData, additionalInfoVertex); } private void populateParameterNodeWithParameters(AdditionalInfoParameterData parameterData, AdditionalInformationDefinition aiDefinition) { @@ -373,21 +386,22 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public TitanOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId, List properties) { + public JanusGraphOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId, List properties) { log.trace("Going to fetch additional information under resource {}", uniqueId); - TitanOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Resource, uniqueId, properties); + JanusGraphOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Resource, uniqueId, properties); - if (!resourceCapabilitiesStatus.equals(TitanOperationStatus.OK)) { + if (!resourceCapabilitiesStatus.equals(JanusGraphOperationStatus.OK)) { return resourceCapabilitiesStatus; } - Either, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, + Either, JanusGraphOperationStatus> parentNodes = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class); if (parentNodes.isRight()) { - TitanOperationStatus parentNodesStatus = parentNodes.right().value(); - if (!parentNodesStatus.equals(TitanOperationStatus.NOT_FOUND)) { + JanusGraphOperationStatus parentNodesStatus = parentNodes.right().value(); + if (!parentNodesStatus.equals(JanusGraphOperationStatus.NOT_FOUND)) { log.error("Failed to find parent additional information of resource {}. status is {}", uniqueId, parentNodesStatus); return parentNodesStatus; } @@ -396,33 +410,34 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe if (parentNodes.isLeft()) { ImmutablePair parnetNodePair = parentNodes.left().value(); String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - TitanOperationStatus addParentIntStatus = findResourceAllAdditionalInformationRecursively(parentUniqueId, properties); + JanusGraphOperationStatus addParentIntStatus = findResourceAllAdditionalInformationRecursively(parentUniqueId, properties); - if (addParentIntStatus != TitanOperationStatus.OK) { + if (addParentIntStatus != JanusGraphOperationStatus.OK) { log.error("Failed to find all resource additional information of resource {}", parentUniqueId); return addParentIntStatus; } } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } @Override - public TitanOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId, List properties) { + public JanusGraphOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId, List properties) { log.trace("Going to fetch additional information under service {}", uniqueId); - TitanOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Service, uniqueId, properties); + JanusGraphOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Service, uniqueId, properties); - if (!resourceCapabilitiesStatus.equals(TitanOperationStatus.OK)) { + if (!resourceCapabilitiesStatus.equals(JanusGraphOperationStatus.OK)) { return resourceCapabilitiesStatus; } - Either, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Service, + Either, JanusGraphOperationStatus> parentNodes = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Service, ServiceMetadataData.class); if (parentNodes.isRight()) { - TitanOperationStatus parentNodesStatus = parentNodes.right().value(); - if (!parentNodesStatus.equals(TitanOperationStatus.NOT_FOUND)) { + JanusGraphOperationStatus parentNodesStatus = parentNodes.right().value(); + if (!parentNodesStatus.equals(JanusGraphOperationStatus.NOT_FOUND)) { log.error("Failed to find parent additional information of resource {}. status is {}", uniqueId, parentNodesStatus); return parentNodesStatus; } @@ -431,26 +446,27 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe if (parentNodes.isLeft()) { ImmutablePair parnetNodePair = parentNodes.left().value(); String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - TitanOperationStatus addParentIntStatus = findServiceAllAdditionalInformationRecursively(parentUniqueId, properties); + JanusGraphOperationStatus addParentIntStatus = findServiceAllAdditionalInformationRecursively(parentUniqueId, properties); - if (addParentIntStatus != TitanOperationStatus.OK) { + if (addParentIntStatus != JanusGraphOperationStatus.OK) { log.error("Failed to find all resource additional information of resource {}", parentUniqueId); return addParentIntStatus; } } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } - private TitanOperationStatus findAdditionalInformationOfNode(NodeTypeEnum nodeType, String uniqueId, List properties) { + private JanusGraphOperationStatus findAdditionalInformationOfNode(NodeTypeEnum nodeType, String uniqueId, List properties) { - Either, TitanOperationStatus> childNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + Either, JanusGraphOperationStatus> childNode = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (childNode.isRight()) { - TitanOperationStatus status = childNode.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; + JanusGraphOperationStatus status = childNode.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.OK; } return status; } @@ -464,7 +480,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe properties.add(additionalInfoDef); } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } @@ -483,13 +499,13 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe try { - Either either = this.addAdditionalInformationParameter(nodeType, resourceId, key, value); + Either either = this.addAdditionalInformationParameter(nodeType, resourceId, key, value); if (either.isRight()) { - TitanOperationStatus status = either.right().value(); + JanusGraphOperationStatus status = either.right().value(); log.debug("Failed to add additional information property {} to component {}. Status is {}", key, resourceId, status); BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("CreateAdditionalInformationParameter", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + resourceId, String.valueOf(status)); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } else { AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); result = Either.left(additionalInformationDefinition); @@ -509,11 +525,11 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe try { - Either either = this.updateAdditionalInformationParameter(nodeType, resourceId, id, key, value); + Either either = this.updateAdditionalInformationParameter(nodeType, resourceId, id, key, value); if (either.isRight()) { log.info("Failed to update additional information property {} to component {}", key, resourceId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value())); } else { AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); result = Either.left(additionalInformationDefinition); @@ -534,11 +550,11 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe try { - Either either = this.deleteAdditionalInformationParameter(nodeType, resourceId, id); + Either either = this.deleteAdditionalInformationParameter(nodeType, resourceId, id); if (either.isRight()) { log.error("Failed to delete additional information id {} to component {}", id, resourceId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value())); } else { AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); result = Either.left(additionalInformationDefinition); @@ -559,11 +575,11 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe try { - Either either = this.getNumberOfParameters(nodeType, resourceId); + Either either = this.getNumberOfParameters(nodeType, resourceId); if (either.isRight()) { log.error("Failed to get the number of additional information properties in component {}", resourceId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value())); } else { Integer counter = either.left().value(); result = Either.left(counter); @@ -574,10 +590,10 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe if (!inTransaction) { if (result == null || result.isRight()) { log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } @@ -585,13 +601,14 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either getNumberOfParameters(NodeTypeEnum nodeType, String resourceId) { + public Either getNumberOfParameters(NodeTypeEnum nodeType, String resourceId) { - Either, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + Either, JanusGraphOperationStatus> getResult = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (getResult.isRight()) { - TitanOperationStatus status = getResult.right().value(); + JanusGraphOperationStatus status = getResult.right().value(); return Either.right(status); } @@ -609,18 +626,20 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either getAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) { + public Either getAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) { - TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); - if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { + JanusGraphOperationStatus + verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); + if (verifyNodeTypeVsComponent != JanusGraphOperationStatus.OK) { return Either.right(verifyNodeTypeVsComponent); } - Either, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + Either, JanusGraphOperationStatus> getResult = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (getResult.isRight()) { - TitanOperationStatus status = getResult.right().value(); + JanusGraphOperationStatus status = getResult.right().value(); return Either.right(status); } @@ -630,7 +649,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe Map idToKey = parameterData.getIdToKey(); if (idToKey == null || !idToKey.containsKey(id)) { - return Either.right(TitanOperationStatus.INVALID_ID); + return Either.right(JanusGraphOperationStatus.INVALID_ID); } String key = idToKey.get(id); @@ -638,11 +657,12 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe log.trace("The key-value {} = {} was retrieved for id {}", key, value, id); - Either updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); + Either updateNode = janusGraphGenericDao + .updateNode(parameterData, AdditionalInfoParameterData.class); if (updateNode.isRight()) { - TitanOperationStatus status = updateNode.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = updateNode.right().value(); + if (status != JanusGraphOperationStatus.NOT_FOUND) { BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameter", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status)); } return Either.right(status); @@ -655,21 +675,23 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String componentId, boolean ignoreVerification) { + public Either getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String componentId, boolean ignoreVerification) { if (!ignoreVerification) { - TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); - if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { + JanusGraphOperationStatus + verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); + if (verifyNodeTypeVsComponent != JanusGraphOperationStatus.OK) { return Either.right(verifyNodeTypeVsComponent); } } - Either, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + Either, JanusGraphOperationStatus> getResult = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (getResult.isRight()) { - TitanOperationStatus status = getResult.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = getResult.right().value(); + if (status != JanusGraphOperationStatus.NOT_FOUND) { BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameters", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status)); } return Either.right(status); @@ -693,11 +715,11 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe try { - Either either = this.getAllAdditionalInformationParameters(nodeType, resourceId, ignoreVerification); + Either either = this.getAllAdditionalInformationParameters(nodeType, resourceId, ignoreVerification); if (either.isRight()) { - TitanOperationStatus status = either.right().value(); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + JanusGraphOperationStatus status = either.right().value(); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } else { AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); result = Either.left(additionalInformationDefinition); @@ -716,10 +738,10 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe if (!inTransaction) { if (result == null || result.isRight()) { log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } @@ -732,11 +754,11 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe try { - Either either = this.getAdditionalInformationParameter(nodeType, resourceId, id); + Either either = this.getAdditionalInformationParameter(nodeType, resourceId, id); if (either.isRight()) { log.error("Failed to fetch additional information property with id {} of component {}", id, resourceId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value())); } else { AdditionalInfoParameterInfo additionalInformationDefinition = either.left().value(); result = Either.left(additionalInformationDefinition); @@ -756,16 +778,17 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe try { - Either, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + Either, JanusGraphOperationStatus> getResult = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (getResult.isRight()) { - TitanOperationStatus status = getResult.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = getResult.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { return Either.right(StorageOperationStatus.OK); } else { BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("DeleteAdditionalInformationNode", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + resourceId, String.valueOf(status)); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } return result; } @@ -773,11 +796,12 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe ImmutablePair value = getResult.left().value(); AdditionalInfoParameterData parameterData = value.getLeft(); - Either deleteNodeRes = titanGenericDao.deleteNode(parameterData, AdditionalInfoParameterData.class); + Either deleteNodeRes = janusGraphGenericDao + .deleteNode(parameterData, AdditionalInfoParameterData.class); if (deleteNodeRes.isRight()) { - TitanOperationStatus status = getResult.right().value(); + JanusGraphOperationStatus status = getResult.right().value(); BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("DeleteAdditionalInformationNode", (String) parameterData.getUniqueId(), String.valueOf(status)); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); return result; } @@ -792,12 +816,13 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } } - private TitanOperationStatus verifyNodeTypeVsComponent(NodeTypeEnum nodeType, String componentId) { - Either vertexByProperty = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId); + private JanusGraphOperationStatus verifyNodeTypeVsComponent(NodeTypeEnum nodeType, String componentId) { + Either vertexByProperty = janusGraphGenericDao + .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId); if (vertexByProperty.isRight()) { - TitanOperationStatus status = vertexByProperty.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; + JanusGraphOperationStatus status = vertexByProperty.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } return status; } else { @@ -806,14 +831,14 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe if (label != null) { if (!label.equals(nodeType.getName())) { log.debug("The node type {} is not appropriate to component {}", nodeType, componentId); - return TitanOperationStatus.INVALID_ID; + return JanusGraphOperationStatus.INVALID_ID; } } else { log.debug("The node type {} with id {} does not have a label property.", nodeType, componentId); - return TitanOperationStatus.INVALID_ID; + return JanusGraphOperationStatus.INVALID_ID; } } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } } 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 9beb2053a3..4e65fa5d2b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java @@ -20,8 +20,8 @@ package org.openecomp.sdc.be.model.operations.impl; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Direction; @@ -33,11 +33,11 @@ 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.GraphRelation; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; 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.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; @@ -61,7 +61,7 @@ public class ArtifactOperation implements IArtifactOperation { private static final String THE_RETURNED_ARTIFACT_DEFINTION_IS = "The returned ArtifactDefintion is {}"; @javax.annotation.Resource - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; @javax.annotation.Resource private HeatParametersOperation heatParametersOperation; @@ -77,12 +77,12 @@ public class ArtifactOperation implements IArtifactOperation { super(); } - public TitanGenericDao getTitanGenericDao() { - return titanGenericDao; + public JanusGraphGenericDao getJanusGraphGenericDao() { + return janusGraphGenericDao; } - public void setTitanGenericDao(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; + public void setJanusGraphGenericDao(JanusGraphGenericDao janusGraphGenericDao) { + this.janusGraphGenericDao = janusGraphGenericDao; } public HeatParametersOperation getHeatParametersOperation() { @@ -100,13 +100,13 @@ public class ArtifactOperation implements IArtifactOperation { if (status.isRight()) { if (!inTransaction) { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } log.debug("Failed to add artifact {} to {} {}", artifactInfo.getArtifactName(), type , parentId); return Either.right(status.right().value()); } else { if (!inTransaction) { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } ArtifactData artifactData = status.left().value(); @@ -119,7 +119,7 @@ public class ArtifactOperation implements IArtifactOperation { } @Override - public StorageOperationStatus addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, TitanVertex parentVertex) { + public StorageOperationStatus addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, JanusGraphVertex parentVertex) { StorageOperationStatus status = addArtifactToGraph(artifactInfo, parentId, type, failIfExist, parentVertex); @@ -129,7 +129,7 @@ public class ArtifactOperation implements IArtifactOperation { return status; } - private StorageOperationStatus addArtifactToGraph(ArtifactDefinition artifactInfo, String id, NodeTypeEnum type, boolean failIfexist, TitanVertex parentVertex) { + private StorageOperationStatus addArtifactToGraph(ArtifactDefinition artifactInfo, String id, NodeTypeEnum type, boolean failIfexist, JanusGraphVertex parentVertex) { if (artifactInfo.getUniqueId() == null || artifactInfo.getUniqueId().isEmpty()) { String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactInfo.getArtifactLabel()); @@ -142,20 +142,21 @@ public class ArtifactOperation implements IArtifactOperation { ArtifactData artifactData = new ArtifactData(artifactInfo); - Either existArtifact = titanGenericDao.getVertexByProperty(artifactData.getUniqueIdKey(), artifactData.getUniqueId()); + Either existArtifact = janusGraphGenericDao + .getVertexByProperty(artifactData.getUniqueIdKey(), artifactData.getUniqueId()); if (existArtifact.isRight()) { - if (existArtifact.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + if (existArtifact.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) { // create new node log.debug("Before adding artifact to graph {}", artifactData); if (artifactData.getArtifactDataDefinition().getArtifactUUID() == null || artifactData.getArtifactDataDefinition().getArtifactUUID().isEmpty()) updateUUID(artifactData.getArtifactDataDefinition(), null, artifactData.getArtifactDataDefinition().getArtifactVersion()); - Either createNodeResult = titanGenericDao.createNode(artifactData); + Either createNodeResult = janusGraphGenericDao.createNode(artifactData); if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); log.debug("Failed to add artifact {} to graph. status is {}", artifactData.getArtifactDataDefinition().getArtifactName(), operationStatus); BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add artifact", artifactData.getArtifactDataDefinition().getArtifactName(), String.valueOf(operationStatus)); - return DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationStatus); } // add heat parameters @@ -169,11 +170,11 @@ public class ArtifactOperation implements IArtifactOperation { } else { log.debug("Failed to check existance of artifact in graph for id {}", artifactData.getUniqueId()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(existArtifact.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(existArtifact.right().value()); } } else if (failIfexist) { log.debug("Artifact {} already exist", artifactData.getUniqueId()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ALREADY_EXIST); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ALREADY_EXIST); } // save logical artifact ref name on edge as property @@ -181,10 +182,11 @@ public class ArtifactOperation implements IArtifactOperation { properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), artifactInfo.getArtifactLabel()); if (artifactInfo.getArtifactGroupType() != null) properties.put(GraphEdgePropertiesDictionary.GROUP_TYPE.getProperty(), artifactInfo.getArtifactGroupType().getType()); - TitanOperationStatus relation = titanGenericDao.createEdge(parentVertex, artifactData, GraphEdgeLabels.ARTIFACT_REF, properties); - if (!relation.equals(TitanOperationStatus.OK)) { + JanusGraphOperationStatus relation = janusGraphGenericDao + .createEdge(parentVertex, artifactData, GraphEdgeLabels.ARTIFACT_REF, properties); + if (!relation.equals(JanusGraphOperationStatus.OK)) { log.debug("Failed to create relation in graph for id {} to new artifact", id); - return DaoStatusConverter.convertTitanStatusToStorageStatus(relation); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(relation); } return StorageOperationStatus.OK; @@ -203,21 +205,23 @@ public class ArtifactOperation implements IArtifactOperation { ArtifactData artifactData = new ArtifactData(artifactInfo); - Either existArtifact = titanGenericDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + Either existArtifact = janusGraphGenericDao + .getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); if (existArtifact.isRight()) { - if (existArtifact.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + if (existArtifact.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) { // create new node log.debug("Before adding artifact to graph {}" , artifactData); if (artifactData.getArtifactDataDefinition().getArtifactUUID() == null || artifactData.getArtifactDataDefinition().getArtifactUUID().isEmpty()) updateUUID(artifactData.getArtifactDataDefinition(), null, artifactData.getArtifactDataDefinition().getArtifactVersion()); - Either createNodeResult = titanGenericDao.createNode(artifactData, ArtifactData.class); + Either createNodeResult = janusGraphGenericDao + .createNode(artifactData, ArtifactData.class); log.debug("After adding artifact to graph {}", artifactData); if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); log.debug("Failed to add artifact {} to graph. status is {}", artifactData.getArtifactDataDefinition().getArtifactName(), operationStatus); BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add artifact", artifactData.getArtifactDataDefinition().getArtifactName(), String.valueOf(operationStatus)); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationStatus)); } artifactData = createNodeResult.left().value(); @@ -232,11 +236,12 @@ public class ArtifactOperation implements IArtifactOperation { } else { log.debug("Failed to check existance of artifact in graph for id {}", artifactData.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(existArtifact.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(existArtifact.right().value())); } } else if (failIfexist) { log.debug("Artifact {} already exist", artifactData.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ALREADY_EXIST)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + JanusGraphOperationStatus.ALREADY_EXIST)); } else { artifactData = existArtifact.left().value(); } @@ -248,10 +253,11 @@ public class ArtifactOperation implements IArtifactOperation { properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), artifactInfo.getArtifactLabel()); if (artifactInfo.getArtifactGroupType() != null) properties.put(GraphEdgePropertiesDictionary.GROUP_TYPE.getProperty(), artifactInfo.getArtifactGroupType().getType()); - Either relation = titanGenericDao.createRelation(parent, artifactData, GraphEdgeLabels.ARTIFACT_REF, properties); + Either relation = janusGraphGenericDao + .createRelation(parent, artifactData, GraphEdgeLabels.ARTIFACT_REF, properties); if (relation.isRight()) { log.debug("Failed to create relation in graph fro id {} to new artifact", id); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(relation.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(relation.right().value())); } return Either.left(artifactData); @@ -291,14 +297,14 @@ public class ArtifactOperation implements IArtifactOperation { if (status.isRight()) { if (!inTransaction) { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } log.debug("Failed to update artifact {} of {} {}. status is {}", artifactId, type.getName(), id, status.right().value()); BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactId, String.valueOf(status.right().value())); return Either.right(status.right().value()); } else { if (!inTransaction) { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } ArtifactData artifactData = status.left().value(); @@ -314,7 +320,7 @@ public class ArtifactOperation implements IArtifactOperation { if (status.isRight()) { if (!inTransaction) { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } log.debug("Failed to delete artifact {} of resource {}", artifactId, id); @@ -322,7 +328,7 @@ public class ArtifactOperation implements IArtifactOperation { return Either.right(status.right().value()); } else { if (!inTransaction) { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } ArtifactData artifactData = status.left().value(); @@ -335,21 +341,21 @@ public class ArtifactOperation implements IArtifactOperation { @SuppressWarnings("null") private Either updateArtifactOnGraph(ArtifactDefinition artifactInfo, String artifactId, NodeTypeEnum type, String id) { - Either graph = titanGenericDao.getGraph(); + Either graph = janusGraphGenericDao.getGraph(); if (graph.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(graph.right().value())); } - TitanGraph tGraph = graph.left().value(); + JanusGraph tGraph = graph.left().value(); @SuppressWarnings("unchecked") - Iterable verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId).vertices(); - Iterator iterator = verticesArtifact.iterator(); + 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); } - TitanVertex artifactV = iterator.next(); + JanusGraphVertex artifactV = iterator.next(); Iterator iterEdge = artifactV.edges(Direction.IN, GraphEdgeLabels.ARTIFACT_REF.getProperty()); @@ -385,8 +391,10 @@ public class ArtifactOperation implements IArtifactOperation { String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactInfo.getArtifactLabel()); artifactInfo.setUniqueId(uniqueId); // update UUID and artifact version - String oldChecksum = artifactV.valueOrNull(titanGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty())); - String oldVersion = artifactV.valueOrNull(titanGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty())); + String oldChecksum = artifactV.valueOrNull( + janusGraphGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty())); + String oldVersion = artifactV.valueOrNull( + janusGraphGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty())); updateUUID(artifactInfo, oldChecksum, oldVersion); log.debug("try to create new artifact ref node for id {}", uniqueId); Either addedArtifactRes = addArtifactToGraph(artifactInfo, id, type, true); @@ -435,10 +443,11 @@ public class ArtifactOperation implements IArtifactOperation { Vertex vertexIn = edgeToHeat.inVertex(); String generatedFromArtifactId = vertexIn.value(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef)); UniqueIdData generatedFromArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, generatedFromArtifactId); - Either createRelationToGeneratedFromArtifactRes = titanGenericDao.createRelation(addedArtifact, generatedFromArtifactNode, GraphEdgeLabels.GENERATED_FROM, null); + Either createRelationToGeneratedFromArtifactRes = janusGraphGenericDao + .createRelation(addedArtifact, generatedFromArtifactNode, GraphEdgeLabels.GENERATED_FROM, null); if (createRelationToGeneratedFromArtifactRes.isRight()) { log.error("Failed to create relation from heat_env {} to heat {}", addedArtifact.getUniqueId(), generatedFromArtifactNode); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createRelationToGeneratedFromArtifactRes.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createRelationToGeneratedFromArtifactRes.right().value())); } } } @@ -446,14 +455,17 @@ public class ArtifactOperation implements IArtifactOperation { } else { if (edgeCount == 1) { - String oldChecksum = artifactV.valueOrNull(titanGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty())); - String oldVersion = artifactV.valueOrNull(titanGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty())); + String oldChecksum = artifactV.valueOrNull( + janusGraphGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty())); + String oldVersion = artifactV.valueOrNull( + janusGraphGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty())); updateUUID(artifactInfo, oldChecksum, oldVersion); // update exist - Either updatedArtifact = titanGenericDao.updateNode(artifactData, ArtifactData.class); + Either updatedArtifact = janusGraphGenericDao + .updateNode(artifactData, ArtifactData.class); if (updatedArtifact.isRight()) { log.debug("failed to update artifact node for id {}", artifactData.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updatedArtifact.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updatedArtifact.right().value())); } if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) { @@ -511,7 +523,7 @@ public class ArtifactOperation implements IArtifactOperation { return false; } - private Either setRelevantHeatParamId(TitanVertex artifactV, ArtifactDefinition artifactInfo) { + private Either setRelevantHeatParamId(JanusGraphVertex artifactV, ArtifactDefinition artifactInfo) { Map heatParametersHM = new HashMap<>(); @@ -524,7 +536,8 @@ public class ArtifactOperation implements IArtifactOperation { Vertex heatVertex = heat.inVertex(); String heatUniqueId = (String) heatVertex.value(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef)); - Either>, TitanOperationStatus> getHeatParametersRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatUniqueId, GraphEdgeLabels.HEAT_PARAMETER, + Either>, JanusGraphOperationStatus> getHeatParametersRes = janusGraphGenericDao + .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatUniqueId, GraphEdgeLabels.HEAT_PARAMETER, NodeTypeEnum.HeatParameter, HeatParameterData.class); if (getHeatParametersRes.isRight()) { log.debug("No heat parameters for heat artifact {}", heatUniqueId); @@ -550,17 +563,18 @@ public class ArtifactOperation implements IArtifactOperation { } private Either removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { - Either graph = titanGenericDao.getGraph() + Either graph = janusGraphGenericDao.getGraph() .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); if (graph.isRight()) { return Either.right(graph.right().value()); } - TitanGraph tGraph = graph.left().value(); - Either artifactData = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class) + JanusGraph tGraph = graph.left().value(); + Either artifactData = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); if (artifactData.isRight()) { log.debug("Failed to retrieve artifact for id = {}", artifactId); return Either.right(artifactData.right().value()); @@ -572,8 +586,8 @@ public class ArtifactOperation implements IArtifactOperation { } @SuppressWarnings("unchecked") - Iterable verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId).vertices(); - Iterator iterator = verticesArtifact.iterator(); + 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); @@ -649,20 +663,20 @@ public class ArtifactOperation implements IArtifactOperation { public Either, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction) { Either, StorageOperationStatus> result = null; try { - Either graph = titanGenericDao.getGraph(); + Either graph = janusGraphGenericDao.getGraph(); if (graph.isRight()) { log.debug("Failed to work with graph {}", graph.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(graph.right().value())); } - TitanGraph tGraph = graph.left().value(); + JanusGraph tGraph = graph.left().value(); @SuppressWarnings("unchecked") - Iterable vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices(); + 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(); + Iterator iterator = vertices.iterator(); Map artifactMap = new HashMap<>(); while (iterator.hasNext()) { @@ -676,15 +690,16 @@ public class ArtifactOperation implements IArtifactOperation { Vertex artifactV = edge.inVertex(); - Map properties = this.titanGenericDao.getProperties(artifactV); + Map properties = this.janusGraphGenericDao.getProperties(artifactV); ArtifactData artifact = GraphElementFactory.createElement(NodeTypeEnum.ArtifactRef.getName(), GraphElementTypeEnum.Node, properties, ArtifactData.class); if (artifact != null) { ArtifactDefinition artifactDefinition = new ArtifactDefinition(artifact.getArtifactDataDefinition()); Iterator edgesGeneratedFrom = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty()); if (edgesGeneratedFrom != null && edgesGeneratedFrom.hasNext()) { - TitanVertex inVertex = (TitanVertex) edgesGeneratedFrom.next().inVertex(); - String artifactIdGeneratedFrom = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + JanusGraphVertex inVertex = (JanusGraphVertex) edgesGeneratedFrom.next().inVertex(); + String artifactIdGeneratedFrom = (String) janusGraphGenericDao + .getProperty(inVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); artifactDefinition.setGeneratedFromId(artifactIdGeneratedFrom); } List heatParams = new ArrayList<>(); @@ -707,9 +722,9 @@ public class ArtifactOperation implements IArtifactOperation { } finally { if (!inTransaction) { if (result == null || result.isRight()) { - this.titanGenericDao.rollback(); + this.janusGraphGenericDao.rollback(); } else { - this.titanGenericDao.commit(); + this.janusGraphGenericDao.commit(); } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java index 3a0eef1a46..abd3c91eea 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java @@ -23,7 +23,7 @@ package org.openecomp.sdc.be.model.operations.impl; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.cache.ComponentCache; import org.openecomp.sdc.be.model.cache.DaoInfo; @@ -31,7 +31,7 @@ import org.openecomp.sdc.be.model.cache.jobs.*; import org.openecomp.sdc.be.model.cache.workers.CacheWorker; import org.openecomp.sdc.be.model.cache.workers.IWorker; import org.openecomp.sdc.be.model.cache.workers.SyncWorker; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; @@ -50,7 +50,7 @@ public class CacheMangerOperation implements ICacheMangerOperation { @Autowired private ToscaOperationFacade toscaOperationFacade; @Autowired - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; @Autowired private ComponentCache componentCache; @@ -183,8 +183,8 @@ public class CacheMangerOperation implements ICacheMangerOperation { } } - public TitanGenericDao getTitanGenericDao() { - return titanGenericDao; + public JanusGraphGenericDao getJanusGraphGenericDao() { + return janusGraphGenericDao; } public ComponentCache getComponentCache() { 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 382a2e00f7..ed635d1a0a 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 @@ -36,11 +36,11 @@ import java.util.stream.Collectors; 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.janusgraph.HealingJanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; 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.HealingTitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; @@ -71,11 +71,11 @@ public class CapabilityOperation extends AbstractOperation { @VisibleForTesting - public void setTitanGenericDao(HealingTitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; + public void setJanusGraphGenericDao(HealingJanusGraphGenericDao janusGraphGenericDao) { + this.janusGraphGenericDao = janusGraphGenericDao; } - public Either addCapabilityToGraph(String resourceId, CapabilityTypeData capTypeData, CapabilityDefinition capabilityDefinition) { + public Either addCapabilityToGraph(String resourceId, CapabilityTypeData capTypeData, CapabilityDefinition capabilityDefinition) { log.debug("#addCapabilityToGraph - capabilityDefinition={}", capabilityDefinition); @@ -83,11 +83,12 @@ public class CapabilityOperation extends AbstractOperation { CapabilityData capabilityData = buildCapabilityData(capabilityDefinition, capUniqueId); log.debug("addCapabilityToGraph - Before adding capability to graph. capabilityTypeData = {}", capabilityData); - Either createCapResult = titanGenericDao.createNode(capabilityData, CapabilityData.class); + Either createCapResult = janusGraphGenericDao + .createNode(capabilityData, CapabilityData.class); log.debug("addCapabilityToGraph - After adding capability to graph. status is = {}", createCapResult); if (createCapResult.isRight()) { - TitanOperationStatus operationStatus = createCapResult.right().value(); + JanusGraphOperationStatus operationStatus = createCapResult.right().value(); log.error("addCapabilityToGraph - Failed to add capability of type {} to graph. status is {}", capabilityDefinition.getType(), operationStatus); return createCapResult; } @@ -101,14 +102,15 @@ public class CapabilityOperation extends AbstractOperation { return createCapResult; } - private Either connectToCapabilityType(CapabilityData capabilityData, CapabilityTypeData capabilityTypeData) { + private Either connectToCapabilityType(CapabilityData capabilityData, CapabilityTypeData capabilityTypeData) { Map properties = new HashMap<>(); String capabilityName = capabilityData.getCapabilityDataDefinition().getName(); properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capabilityName); - return titanGenericDao.createRelation(capabilityData, capabilityTypeData, GraphEdgeLabels.CAPABILITY_IMPL, properties); + return janusGraphGenericDao + .createRelation(capabilityData, capabilityTypeData, GraphEdgeLabels.CAPABILITY_IMPL, properties); } @@ -117,13 +119,13 @@ public class CapabilityOperation extends AbstractOperation { * @param capabilites * @return */ - public Either, TitanOperationStatus> getCapabilitiesWithProps(List> capabilites) { - List> listFilledCapabilitiesResults = capabilites.stream() + public Either, JanusGraphOperationStatus> getCapabilitiesWithProps(List> capabilites) { + List> listFilledCapabilitiesResults = capabilites.stream() .map(ImmutablePair::getLeft) .map(this::toCapabilityDefinitionWithProps) .collect(Collectors.toList()); - Optional status = listFilledCapabilitiesResults.stream().filter(Either::isRight) + Optional status = listFilledCapabilitiesResults.stream().filter(Either::isRight) .map(res -> res.right().value()) .findFirst(); @@ -138,7 +140,7 @@ public class CapabilityOperation extends AbstractOperation { return Either.left(listCapabilities); } - private Either toCapabilityDefinitionWithProps(CapabilityData capabilityData) { + private Either toCapabilityDefinitionWithProps(CapabilityData capabilityData) { CapabilityDefinition capabilityDefinition = new CapabilityDefinition(capabilityData.getCapabilityDataDefinition()); return getCapabilityProperties(capabilityDefinition.getUniqueId(), capabilityDefinition.getType()) .left() @@ -157,33 +159,34 @@ public class CapabilityOperation extends AbstractOperation { * @param capabilityUid * @return */ - private Either, TitanOperationStatus> getCapabilityProperties(String capabilityUid, String capabilityType) { - Either capabilityTypeRes = capabilityTypeOperation.getCapabilityTypeByType(capabilityType); + private Either, JanusGraphOperationStatus> getCapabilityProperties(String capabilityUid, String capabilityType) { + Either capabilityTypeRes = capabilityTypeOperation.getCapabilityTypeByType(capabilityType); if (capabilityTypeRes.isRight()) { - TitanOperationStatus status = capabilityTypeRes.right().value(); + JanusGraphOperationStatus status = capabilityTypeRes.right().value(); return Either.right(status); } CapabilityTypeDefinition capabilityTypeDefinition = capabilityTypeRes.left().value(); - Either, TitanOperationStatus> typesPropsRes = getPropertiesOfCapabilityTypeAndAcestors(capabilityTypeDefinition); + Either, JanusGraphOperationStatus> typesPropsRes = getPropertiesOfCapabilityTypeAndAcestors(capabilityTypeDefinition); if (typesPropsRes.isRight()) { - TitanOperationStatus status = typesPropsRes.right().value(); + JanusGraphOperationStatus status = typesPropsRes.right().value(); return Either.right(status); } Map capabilityTypeProperties = typesPropsRes.left().value(); if (isEmpty(capabilityTypeProperties)) { - return Either.right(TitanOperationStatus.OK); + return Either.right(JanusGraphOperationStatus.OK); } Map uidToPropDefMap = capabilityTypeProperties.values().stream() .collect(Collectors.toMap(PropertyDefinition::getUniqueId, Function.identity())); // Find all properties values on the capability - Either>, TitanOperationStatus> propertyValNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, GraphEdgeLabels.PROPERTY_VALUE, + Either>, JanusGraphOperationStatus> propertyValNodes = janusGraphGenericDao + .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class); if (propertyValNodes.isRight()) { @@ -192,7 +195,7 @@ public class CapabilityOperation extends AbstractOperation { List> propValsRelationPairs = propertyValNodes.left().value(); if (isEmpty(propValsRelationPairs)) { - return Either.right(TitanOperationStatus.OK); + return Either.right(JanusGraphOperationStatus.OK); } List capabilityProperties = new ArrayList<>(); @@ -200,12 +203,13 @@ public class CapabilityOperation extends AbstractOperation { for (ImmutablePair propValRelPair : propValsRelationPairs) { PropertyValueData propertyValueData = propValRelPair.getLeft(); - Either, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueData.getUniqueId(), GraphEdgeLabels.PROPERTY_IMPL, + Either, JanusGraphOperationStatus> propertyDefRes = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueData.getUniqueId(), GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class); if (propertyDefRes.isRight()) { - TitanOperationStatus status = propertyDefRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; + JanusGraphOperationStatus status = propertyDefRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } return Either.right(status); } @@ -242,8 +246,8 @@ public class CapabilityOperation extends AbstractOperation { .collect(Collectors.toSet()); } - private Either, TitanOperationStatus> onLoadPropValuesFailure(TitanOperationStatus status, Map capabilityTypeProperties) { - if (status == TitanOperationStatus.NOT_FOUND) { + private Either, JanusGraphOperationStatus> onLoadPropValuesFailure(JanusGraphOperationStatus status, Map capabilityTypeProperties) { + if (status == JanusGraphOperationStatus.NOT_FOUND) { return Either.left(buildPropsFromCapabilityTypeProps(capabilityTypeProperties)); } else { return Either.right(status); @@ -267,15 +271,15 @@ public class CapabilityOperation extends AbstractOperation { * @param capabilityTypeDefinition * @return */ - private Either, TitanOperationStatus> getPropertiesOfCapabilityTypeAndAcestors(CapabilityTypeDefinition capabilityTypeDefinition) { + private Either, JanusGraphOperationStatus> getPropertiesOfCapabilityTypeAndAcestors(CapabilityTypeDefinition capabilityTypeDefinition) { // Get the properties on the group type of this capability Map capabilityTypeProperties = capabilityTypeDefinition.getProperties(); String derivedFrom = capabilityTypeDefinition.getDerivedFrom(); if (!Strings.isNullOrEmpty(derivedFrom)) { - Either, TitanOperationStatus> parentPropsRes = capabilityTypeOperation.getAllCapabilityTypePropertiesFromAllDerivedFrom(derivedFrom); + Either, JanusGraphOperationStatus> parentPropsRes = capabilityTypeOperation.getAllCapabilityTypePropertiesFromAllDerivedFrom(derivedFrom); if(parentPropsRes.isRight()) { - TitanOperationStatus status = parentPropsRes.right().value(); + JanusGraphOperationStatus status = parentPropsRes.right().value(); return Either.right(status); } if (capabilityTypeProperties != null) { @@ -297,15 +301,15 @@ public class CapabilityOperation extends AbstractOperation { * @param capabilityTypeData * @return */ - private Either, TitanOperationStatus> createCapabilityProperties(CapabilityData capabilityData, - CapabilityTypeData capabilityTypeData) { + private Either, JanusGraphOperationStatus> createCapabilityProperties(CapabilityData capabilityData, + CapabilityTypeData capabilityTypeData) { CapabilityDefinition capabilityDefintion = (CapabilityDefinition)capabilityData.getCapabilityDataDefinition(); CapabilityTypeDefinition capabilityTypeDefinition = (CapabilityTypeDefinition)capabilityTypeData.getCapabilityTypeDataDefinition(); - Either, TitanOperationStatus> typesPropsRes = getPropertiesOfCapabilityTypeAndAcestors(capabilityTypeDefinition); + Either, JanusGraphOperationStatus> typesPropsRes = getPropertiesOfCapabilityTypeAndAcestors(capabilityTypeDefinition); if (typesPropsRes.isRight()) { - TitanOperationStatus status = typesPropsRes.right().value(); + JanusGraphOperationStatus status = typesPropsRes.right().value(); return Either.right(status); } @@ -313,10 +317,10 @@ public class CapabilityOperation extends AbstractOperation { if (isEmpty(capabilityTypeProperties) && !isEmpty(capabilityDefintion.getProperties())) { log.debug("#createCapabilityProperties - It's not valid if group capability has properties while corresponding capability type doesn't."); - return Either.right(TitanOperationStatus.MATCH_NOT_FOUND); + return Either.right(JanusGraphOperationStatus.MATCH_NOT_FOUND); } - Optional error = capabilityDefintion.getProperties().stream() + Optional error = capabilityDefintion.getProperties().stream() .map(property -> createPropertyValue(property, capabilityData, capabilityTypeProperties.get(property.getName()))) .filter(Either::isRight) .map(result -> result.right().value()) @@ -342,11 +346,11 @@ public class CapabilityOperation extends AbstractOperation { .collect(Collectors.toList()); } - private Either createPropertyValue(ComponentInstanceProperty capabilityProperty, - CapabilityData capabilityData, - PropertyDefinition capTypePropertyDefinition) { + private Either createPropertyValue(ComponentInstanceProperty capabilityProperty, + CapabilityData capabilityData, + PropertyDefinition capTypePropertyDefinition) { if (capTypePropertyDefinition == null) { - return Either.right(TitanOperationStatus.MATCH_NOT_FOUND); + return Either.right(JanusGraphOperationStatus.MATCH_NOT_FOUND); } CapabilityDefinition capabilityDefintion = (CapabilityDefinition)capabilityData.getCapabilityDataDefinition(); @@ -357,7 +361,8 @@ public class CapabilityOperation extends AbstractOperation { PropertyValueData propertyValueData = new PropertyValueData(); propertyValueData.setUniqueId(uniqueId); propertyValueData.setValue(capabilityProperty.getValue()); - Either propResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class); + Either propResult = janusGraphGenericDao + .createNode(propertyValueData, PropertyValueData.class); // It's not accepted if Capability Type doesn't have suitable property propResult = propResult.left() .bind(propValueData -> connectToProperty(propValueData, capTypePropertyDefinition)) @@ -372,22 +377,23 @@ public class CapabilityOperation extends AbstractOperation { return propResult; } - private Either connectCapability(PropertyValueData propValueData, String name, CapabilityData capabilityData) { + private Either connectCapability(PropertyValueData propValueData, String name, CapabilityData capabilityData) { Map properties = new HashMap<>(); properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), name); - return titanGenericDao.createRelation(capabilityData, propValueData, GraphEdgeLabels.PROPERTY_VALUE, properties); + return janusGraphGenericDao.createRelation(capabilityData, propValueData, GraphEdgeLabels.PROPERTY_VALUE, properties); } - private Either connectToProperty(PropertyValueData propValueData, PropertyDefinition propertyDefinition) { - Either dataTypesRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), + private Either connectToProperty(PropertyValueData propValueData, PropertyDefinition propertyDefinition) { + Either dataTypesRes = janusGraphGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyDefinition.getUniqueId(), PropertyData.class); Map properties = new HashMap<>(); properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), propertyDefinition.getName()); return dataTypesRes.left() - .bind(propertyData -> titanGenericDao.createRelation(propValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, properties)); + .bind(propertyData -> janusGraphGenericDao + .createRelation(propValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, properties)); } @@ -408,12 +414,14 @@ public class CapabilityOperation extends AbstractOperation { public StorageOperationStatus deleteCapability(CapabilityDefinition capabilityDef) { - return titanGenericDao.deleteChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), capabilityDef.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, + return janusGraphGenericDao + .deleteChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), capabilityDef.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class) .left() - .bind(props -> titanGenericDao.deleteNode(new CapabilityData(capabilityDef), CapabilityData.class)) + .bind(props -> janusGraphGenericDao + .deleteNode(new CapabilityData(capabilityDef), CapabilityData.class)) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus) + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus) .right() .on(capData -> StorageOperationStatus.OK); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java index 1cc1380917..61c7e0c13e 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 @@ -30,9 +30,9 @@ import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; -import org.openecomp.sdc.be.dao.titan.HealingTitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; @@ -66,10 +66,10 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab /** * FOR TEST ONLY * - * @param titanGenericDao + * @param janusGraphGenericDao */ - public void setTitanGenericDao(HealingTitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; + public void setJanusGraphGenericDao(HealingJanusGraphGenericDao janusGraphGenericDao) { + this.janusGraphGenericDao = janusGraphGenericDao; } @Override @@ -102,26 +102,27 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab if (!inTransaction) { if (result == null || result.isRight()) { log.error("#addCapabilityType - Going to execute rollback on graph."); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug("#addCapabilityType - Going to execute commit on graph."); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } } - public Either, TitanOperationStatus> getAllCapabilityTypePropertiesFromAllDerivedFrom(String firstParentType) { + public Either, JanusGraphOperationStatus> getAllCapabilityTypePropertiesFromAllDerivedFrom(String firstParentType) { return propertyOperation.getAllTypePropertiesFromAllDerivedFrom(firstParentType, NodeTypeEnum.CapabilityType, CapabilityTypeData.class); } public Either validateUpdateProperties(CapabilityTypeDefinition capabilityTypeDefinition) { - TitanOperationStatus error = null; + JanusGraphOperationStatus error = null; if (MapUtils.isNotEmpty(capabilityTypeDefinition.getProperties()) && capabilityTypeDefinition.getDerivedFrom() != null) { - Either, TitanOperationStatus> allPropertiesRes = + Either, JanusGraphOperationStatus> allPropertiesRes = getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeDefinition.getDerivedFrom()); - if (allPropertiesRes.isRight() && !allPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + if (allPropertiesRes.isRight() && !allPropertiesRes.right().value().equals( + JanusGraphOperationStatus.NOT_FOUND)) { error = allPropertiesRes.right().value(); log.debug("Couldn't fetch derived from property nodes for capability type {}, error: {}", capabilityTypeDefinition.getType(), error); } @@ -131,7 +132,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab .forEach(e -> e.getValue().setType(derivedFromProperties.get(e.getKey()).getType())); List properties = capabilityTypeDefinition.getProperties().values().stream().collect(Collectors.toList()); - Either, TitanOperationStatus> validatePropertiesRes = propertyOperation.validatePropertiesUniqueness(allPropertiesRes.left().value(), + Either, JanusGraphOperationStatus> validatePropertiesRes = propertyOperation.validatePropertiesUniqueness(allPropertiesRes.left().value(), properties); if (validatePropertiesRes.isRight()) { error = validatePropertiesRes.right().value(); @@ -141,7 +142,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab if (error == null) { return Either.left(capabilityTypeDefinition); } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error)); } @@ -179,21 +180,22 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab CapabilityTypeData capabilityTypeData = buildCapabilityTypeData(capabilityTypeDefinition, ctUniqueId); log.debug("Before adding capability type to graph. capabilityTypeData = {}", capabilityTypeData); - Either createCTResult = titanGenericDao.createNode(capabilityTypeData, CapabilityTypeData.class); + Either createCTResult = janusGraphGenericDao + .createNode(capabilityTypeData, CapabilityTypeData.class); log.debug("After adding capability type to graph. status is = {}", createCTResult); if (createCTResult.isRight()) { - TitanOperationStatus operationStatus = createCTResult.right().value(); + JanusGraphOperationStatus operationStatus = createCTResult.right().value(); log.error("Failed to capability type {} to graph. status is {}", capabilityTypeDefinition.getType(), operationStatus); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationStatus)); } CapabilityTypeData resultCTD = createCTResult.left().value(); Map propertiesMap = capabilityTypeDefinition.getProperties(); - Either, TitanOperationStatus> addPropertiesToCapablityType = propertyOperation.addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.CapabilityType, propertiesMap); + Either, JanusGraphOperationStatus> addPropertiesToCapablityType = propertyOperation.addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.CapabilityType, propertiesMap); if (addPropertiesToCapablityType.isRight()) { log.error("Failed add properties {} to capability {}", propertiesMap, capabilityTypeDefinition.getType()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertiesToCapablityType.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertiesToCapablityType.right().value())); } return addDerivedFromRelation(capabilityTypeDefinition, ctUniqueId) @@ -223,14 +225,14 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab Either result = null; try { - Either ctResult = this.getCapabilityTypeByUid(uniqueId); + Either ctResult = this.getCapabilityTypeByUid(uniqueId); if (ctResult.isRight()) { - TitanOperationStatus status = ctResult.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = ctResult.right().value(); + if (status != JanusGraphOperationStatus.NOT_FOUND) { log.error("Failed to retrieve information on capability type {}. status is {}", uniqueId, status); } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(ctResult.right().value())); return result; } @@ -240,13 +242,13 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab } finally { if (!inTransaction) { log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } - public Either getCapabilityTypeByType(String capabilityType) { + public Either getCapabilityTypeByType(String capabilityType) { // Optimization: In case of Capability Type its unique ID is the same as type return getCapabilityTypeByUid(capabilityType); } @@ -257,14 +259,15 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab * @param uniqueId * @return */ - public Either getCapabilityTypeByUid(String uniqueId) { + public Either getCapabilityTypeByUid(String uniqueId) { - Either result = null; + Either result = null; - Either capabilityTypesRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, CapabilityTypeData.class); + Either capabilityTypesRes = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, CapabilityTypeData.class); if (capabilityTypesRes.isRight()) { - TitanOperationStatus status = capabilityTypesRes.right().value(); + JanusGraphOperationStatus status = capabilityTypesRes.right().value(); log.debug("Capability type {} cannot be found in graph. status is {}", uniqueId, status); return Either.right(status); } @@ -272,9 +275,9 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab CapabilityTypeData ctData = capabilityTypesRes.left().value(); CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(ctData.getCapabilityTypeDataDefinition()); - Either, TitanOperationStatus> propertiesStatus = + Either, JanusGraphOperationStatus> propertiesStatus = OperationUtils.fillProperties(uniqueId, propertyOperation, NodeTypeEnum.CapabilityType); - if (propertiesStatus.isRight() && propertiesStatus.right().value() != TitanOperationStatus.OK) { + if (propertiesStatus.isRight() && propertiesStatus.right().value() != JanusGraphOperationStatus.OK) { log.error("Failed to fetch properties of capability type {}", uniqueId); return Either.right(propertiesStatus.right().value()); } @@ -283,14 +286,16 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab capabilityTypeDefinition.setProperties(propertiesStatus.left().value()); } - Either, TitanOperationStatus> parentNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, GraphEdgeLabels.DERIVED_FROM, + Either, JanusGraphOperationStatus> parentNode = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.CapabilityType, CapabilityTypeData.class); log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode); if (parentNode.isRight()) { - TitanOperationStatus titanOperationStatus = parentNode.right().value(); - if (titanOperationStatus != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find the parent capability of capability type {}. status is {}", uniqueId, titanOperationStatus); - result = Either.right(titanOperationStatus); + JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value(); + if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) { + log.error("Failed to find the parent capability of capability type {}. status is {}", uniqueId, + janusGraphOperationStatus); + result = Either.right(janusGraphOperationStatus); return result; } } else { @@ -319,9 +324,10 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab private Either updateCapabilityTypeOnGraph(CapabilityTypeDefinition capabilityTypeDefinitionNew, CapabilityTypeDefinition capabilityTypeDefinitionOld) { - return titanGenericDao.updateNode(new CapabilityTypeData(capabilityTypeDefinitionNew), CapabilityTypeData.class) + return janusGraphGenericDao + .updateNode(new CapabilityTypeData(capabilityTypeDefinitionNew), CapabilityTypeData.class) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus) + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus) .left() .bind(updatedNode -> updateProperties(capabilityTypeDefinitionNew.getUniqueId(), capabilityTypeDefinitionNew.getProperties())) .left() @@ -336,7 +342,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab log.debug("#updateCapabilityTypeProperties - updating properties for capability type with id {}", capabilityTypeId); return propertyOperation.mergePropertiesAssociatedToNode(NodeTypeEnum.CapabilityType, capabilityTypeId, properties) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); } private Either updateDerivedFrom(CapabilityTypeDefinition updatedCapabilityType, String currDerivedFromCapabilityType) { @@ -408,16 +414,17 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab public Either getCapabilityType(String uniqueId) { return getCapabilityType(uniqueId, true); } - public Either, TitanOperationStatus> getAllCapabilityTypes() { + public Either, JanusGraphOperationStatus> getAllCapabilityTypes() { Map capabilityTypes = new HashMap<>(); - Either, TitanOperationStatus> result = Either.left(capabilityTypes); + Either, JanusGraphOperationStatus> result = Either.left(capabilityTypes); - Either, TitanOperationStatus> getAllCapabilityTypes = - titanGenericDao.getByCriteria(NodeTypeEnum.CapabilityType, null, CapabilityTypeData.class); + Either, JanusGraphOperationStatus> getAllCapabilityTypes = + janusGraphGenericDao + .getByCriteria(NodeTypeEnum.CapabilityType, null, CapabilityTypeData.class); if (getAllCapabilityTypes.isRight()) { - TitanOperationStatus status = getAllCapabilityTypes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = getAllCapabilityTypes.right().value(); + if (status != JanusGraphOperationStatus.NOT_FOUND) { return Either.right(status); } else { return result; @@ -434,12 +441,12 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab log.trace("Going to fetch data type {}. uid is {}", capabilityTypeData.getCapabilityTypeDataDefinition().getType(), capabilityTypeData.getUniqueId()); - Either capabilityTypesByUid = + Either capabilityTypesByUid = getAndAddPropertiesANdDerivedFrom(capabilityTypeData.getUniqueId(), capabilityTypes); if (capabilityTypesByUid.isRight()) { - TitanOperationStatus status = capabilityTypesByUid.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; + JanusGraphOperationStatus status = capabilityTypesByUid.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } return Either.right(status); } @@ -473,18 +480,19 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab return derivedFrom; } - private Either getAndAddPropertiesANdDerivedFrom( + private Either getAndAddPropertiesANdDerivedFrom( String uniqueId, Map capabilityTypeDefinitionMap) { if (capabilityTypeDefinitionMap.containsKey(uniqueId)) { return Either.left(capabilityTypeDefinitionMap.get(uniqueId)); } - Either capabilityTypesRes = - titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, + Either capabilityTypesRes = + janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, CapabilityTypeData.class); if (capabilityTypesRes.isRight()) { - TitanOperationStatus status = capabilityTypesRes.right().value(); + JanusGraphOperationStatus status = capabilityTypesRes.right().value(); log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status); return Either.right(status); } @@ -493,10 +501,10 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(ctData.getCapabilityTypeDataDefinition()); - Either, TitanOperationStatus> propertiesStatus = + Either, JanusGraphOperationStatus> propertiesStatus = OperationUtils.fillProperties(uniqueId, propertyOperation, NodeTypeEnum.CapabilityType); - if (propertiesStatus.isRight() && propertiesStatus.right().value() != TitanOperationStatus.OK) { + if (propertiesStatus.isRight() && propertiesStatus.right().value() != JanusGraphOperationStatus.OK) { log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId); return Either.right(propertiesStatus.right().value()); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CommonTypeOperations.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CommonTypeOperations.java index 96b083274c..768a96e120 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CommonTypeOperations.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CommonTypeOperations.java @@ -10,9 +10,9 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.HealingTitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.PropertyDefinition; import org.springframework.stereotype.Component; @@ -20,25 +20,25 @@ import org.springframework.stereotype.Component; @Component public class CommonTypeOperations { - private final HealingTitanGenericDao titanGenericDao; + private final HealingJanusGraphGenericDao janusGraphGenericDao; private final PropertyOperation propertyOperation; private final OperationUtils operationUtils; - public CommonTypeOperations(HealingTitanGenericDao titanGenericDao, PropertyOperation propertyOperation, - OperationUtils operationUtils) { - this.titanGenericDao = titanGenericDao; + public CommonTypeOperations(HealingJanusGraphGenericDao janusGraphGenericDao, PropertyOperation propertyOperation, + OperationUtils operationUtils) { + this.janusGraphGenericDao = janusGraphGenericDao; this.propertyOperation = propertyOperation; this.operationUtils = operationUtils; } public void addType(T typeData, Class clazz) { - titanGenericDao.createNode(typeData, clazz) + janusGraphGenericDao.createNode(typeData, clazz) .left() - .on(operationUtils::onTitanOperationFailure); + .on(operationUtils::onJanusGraphOperationFailure); } public Optional getType(String uniqueId, Class clazz, NodeTypeEnum nodeType) { - T type = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, clazz) + T type = janusGraphGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, clazz) .left() .on(err -> null); return Optional.ofNullable(type); @@ -48,7 +48,7 @@ public class CommonTypeOperations { Map mapCriteria = new HashMap<>(); mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type); mapCriteria.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - return titanGenericDao.getByCriteria(nodeType, mapCriteria, clazz) + return janusGraphGenericDao.getByCriteria(nodeType, mapCriteria, clazz) .left() .on(err -> emptyList()) .stream() @@ -58,13 +58,14 @@ public class CommonTypeOperations { public void addProperties(String uniqueId, NodeTypeEnum nodeType, List properties) { propertyOperation.addPropertiesToElementType(uniqueId, nodeType, properties) .left() - .on(operationUtils::onTitanOperationFailure); + .on(operationUtils::onJanusGraphOperationFailure); } public void fillProperties(String uniqueId, NodeTypeEnum nodeType, Consumer> propertySetter) { - TitanOperationStatus status = propertyOperation.fillPropertiesList(uniqueId, nodeType, propertySetter); - if (status!=TitanOperationStatus.OK) { - operationUtils.onTitanOperationFailure(status); + JanusGraphOperationStatus + status = propertyOperation.fillPropertiesList(uniqueId, nodeType, propertySetter); + if (status!= JanusGraphOperationStatus.OK) { + operationUtils.onJanusGraphOperationFailure(status); } } @@ -72,13 +73,13 @@ public class CommonTypeOperations { * Handle update of type without dervidedFrom attribute */ public void updateType(T typeData, List properties, Class clazz, NodeTypeEnum nodeType) { - titanGenericDao.updateNode(typeData, clazz) + janusGraphGenericDao.updateNode(typeData, clazz) .left() - .on(operationUtils::onTitanOperationFailure); + .on(operationUtils::onJanusGraphOperationFailure); Map newProperties = properties.stream() .collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); propertyOperation.mergePropertiesAssociatedToNode(nodeType, typeData.getUniqueId(), newProperties) .left() - .on(operationUtils::onTitanOperationFailure); + .on(operationUtils::onJanusGraphOperationFailure); } } 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 34dce75c7d..91b4e0a0ce 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,8 +20,8 @@ package org.openecomp.sdc.be.model.operations.impl; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import java.util.HashMap; import java.util.Map; @@ -35,11 +35,11 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; 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.HealingTitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -83,10 +83,10 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo /** * FOR TEST ONLY * - * @param titanGenericDao + * @param janusGraphGenericDao */ - public void setTitanGenericDao(HealingTitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; + public void setJanusGraphGenericDao(HealingJanusGraphGenericDao janusGraphGenericDao) { + this.janusGraphGenericDao = janusGraphGenericDao; } @Override @@ -95,19 +95,20 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either result = null; try { - Either graphResult = titanGenericDao.getGraph(); + Either graphResult = janusGraphGenericDao.getGraph(); if (graphResult.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(graphResult.right().value())); return result; } - Either vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId); + Either vertexService = janusGraphGenericDao + .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; + JanusGraphOperationStatus status = vertexService.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexService.right().value())); return result; } Vertex vertex = vertexService.left().value(); @@ -130,34 +131,36 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (!inTransaction) { if (result == null || result.isRight()) { log.error("increaseAndGetResourceInstanceSpecificCounter operation : Going to execute rollback on graph."); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug("increaseAndGetResourceInstanceSpecificCounter operation : Going to execute commit on graph."); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } } - private void connectAttValueDataToComponentInstanceData(Wrapper errorWrapper, ComponentInstanceData compIns, AttributeValueData attValueData) { + private void connectAttValueDataToComponentInstanceData(Wrapper errorWrapper, ComponentInstanceData compIns, AttributeValueData attValueData) { - Either createRelResult = titanGenericDao.createRelation(compIns, attValueData, GraphEdgeLabels.ATTRIBUTE_VALUE, null); + Either createRelResult = janusGraphGenericDao + .createRelation(compIns, attValueData, GraphEdgeLabels.ATTRIBUTE_VALUE, null); if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); + JanusGraphOperationStatus operationStatus = createRelResult.right().value(); errorWrapper.setInnerElement(operationStatus); BeEcompErrorManager.getInstance().logInternalFlowError("connectAttValueDataToComponentInstanceData", "Failed to associate resource instance " + compIns.getUniqueId() + " attribute value " + attValueData.getUniqueId() + " in graph. status is " + operationStatus, ErrorSeverity.ERROR); } } - private void connectAttValueDataToAttData(Wrapper errorWrapper, AttributeData attData, AttributeValueData attValueData) { + private void connectAttValueDataToAttData(Wrapper errorWrapper, AttributeData attData, AttributeValueData attValueData) { - Either createRelResult = titanGenericDao.createRelation(attValueData, attData, GraphEdgeLabels.ATTRIBUTE_IMPL, null); + Either createRelResult = janusGraphGenericDao + .createRelation(attValueData, attData, GraphEdgeLabels.ATTRIBUTE_IMPL, null); if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); + JanusGraphOperationStatus 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); @@ -165,8 +168,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } } - private void createAttributeValueDataNode(ComponentInstanceProperty attributeInstanceProperty, Integer index, Wrapper errorWrapper, ComponentInstanceData resourceInstanceData, - Wrapper attValueDataWrapper) { + private void createAttributeValueDataNode(ComponentInstanceProperty attributeInstanceProperty, Integer index, Wrapper errorWrapper, ComponentInstanceData resourceInstanceData, + Wrapper attValueDataWrapper) { String valueUniqueUid = attributeInstanceProperty.getValueUniqueUid(); if (valueUniqueUid == null) { @@ -174,11 +177,12 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo AttributeValueData attributeValueData = buildAttributeValueDataFromComponentInstanceAttribute(attributeInstanceProperty, attValueDatauniqueId); log.debug("Before adding attribute value to graph {}", attributeValueData); - Either createNodeResult = titanGenericDao.createNode(attributeValueData, AttributeValueData.class); + Either createNodeResult = janusGraphGenericDao + .createNode(attributeValueData, AttributeValueData.class); log.debug("After adding attribute value to graph {}", attributeValueData); if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); errorWrapper.setInnerElement(operationStatus); } else { attValueDataWrapper.setInnerElement(createNodeResult.left().value()); @@ -186,7 +190,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } else { BeEcompErrorManager.getInstance().logInternalFlowError("CreateAttributeValueDataNode", "attribute value already exists.", ErrorSeverity.ERROR); - errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST); + errorWrapper.setInnerElement(JanusGraphOperationStatus.ALREADY_EXIST); } } @@ -258,10 +262,10 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo * @param resourceInstanceId * @return */ - private Either updateAttributeOfResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId) { + private Either updateAttributeOfResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId) { - Either result = null; - Wrapper errorWrapper = new Wrapper<>(); + 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); @@ -269,9 +273,10 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo AttributeValueData attributeValueData = updateDataContainer.getValueDataWrapper().getInnerElement(); attributeValueData.setHidden(resourceInstanceAttribute.isHidden()); attributeValueData.setValue(resourceInstanceAttribute.getValue()); - Either updateRes = titanGenericDao.updateNode(attributeValueData, AttributeValueData.class); + Either updateRes = janusGraphGenericDao + .updateNode(attributeValueData, AttributeValueData.class); if (updateRes.isRight()) { - TitanOperationStatus status = updateRes.right().value(); + JanusGraphOperationStatus status = updateRes.right().value(); errorWrapper.setInnerElement(status); } else { result = Either.left(updateRes.left().value()); @@ -284,8 +289,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } - private Either addAttributeToResourceInstance(ComponentInstanceProperty attributeInstanceProperty, String resourceInstanceId, Integer index) { - Wrapper errorWrapper = new Wrapper<>(); + 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<>(); @@ -320,7 +325,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } private void preUpdateElementOfResourceInstanceValidations(UpdateDataContainer updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, - String resourceInstanceId, Wrapper errorWrapper) { + String resourceInstanceId, Wrapper errorWrapper) { if (errorWrapper.isEmpty()) { // Verify VFC instance Exist @@ -344,14 +349,15 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } private void validateElementConnectedToInstance(UpdateDataContainer updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, - Wrapper errorWrapper) { - Either, TitanOperationStatus> child = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), resourceInstanceProerty.getValueUniqueUid(), + Wrapper errorWrapper) { + Either, JanusGraphOperationStatus> child = janusGraphGenericDao + .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; + JanusGraphOperationStatus status = child.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } errorWrapper.setInnerElement(status); @@ -361,16 +367,17 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } private void validateElementConnectedToComponentInstanceExist(UpdateDataContainer updateDataContainer, - IComponentInstanceConnectedElement resourceInstanceProerty, Wrapper errorWrapper) { + IComponentInstanceConnectedElement resourceInstanceProerty, Wrapper errorWrapper) { String valueUniqueUid = resourceInstanceProerty.getValueUniqueUid(); if (valueUniqueUid == null) { - errorWrapper.setInnerElement(TitanOperationStatus.INVALID_ID); + errorWrapper.setInnerElement(JanusGraphOperationStatus.INVALID_ID); } else { - Either findPropertyValueRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), valueUniqueUid, updateDataContainer.getSomeValueDataClassGen().get()); + Either findPropertyValueRes = janusGraphGenericDao + .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; + JanusGraphOperationStatus status = findPropertyValueRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } errorWrapper.setInnerElement(status); } else { @@ -380,31 +387,33 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } private void validateElementConnectedToComponentExist(UpdateDataContainer updateDataContainer, - IComponentInstanceConnectedElement resourceInstanceElementConnected, Wrapper errorWrapper) { + IComponentInstanceConnectedElement resourceInstanceElementConnected, Wrapper errorWrapper) { String uniqueId = resourceInstanceElementConnected.getUniqueId(); - Either findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeType()), uniqueId, updateDataContainer.getSomeDataClassGen().get()); + Either findPropertyDefRes = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeType()), uniqueId, updateDataContainer.getSomeDataClassGen().get()); if (findPropertyDefRes.isRight()) { - TitanOperationStatus status = findPropertyDefRes.right().value(); + JanusGraphOperationStatus status = findPropertyDefRes.right().value(); errorWrapper.setInnerElement(status); } } - private void validateRIExist(String resourceInstanceId, Wrapper errorWrapper) { + private void validateRIExist(String resourceInstanceId, Wrapper errorWrapper) { validateRIExist(resourceInstanceId, null, errorWrapper); } - private void validateRIExist(String resourceInstanceId, Wrapper compInsDataWrapper, Wrapper 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()); + Wrapper errorWrapper) { + Either findResInstanceRes = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(elementNodeType), elementUniqueId, elementClassGen.get()); if (findResInstanceRes.isRight()) { - TitanOperationStatus status = findResInstanceRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; + JanusGraphOperationStatus status = findResInstanceRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } errorWrapper.setInnerElement(status); } else { @@ -421,25 +430,27 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo * @param index * @return */ - private Either addInputToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index) { + private Either addInputToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index) { - Either findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class); + Either findResInstanceRes = janusGraphGenericDao + .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; + JanusGraphOperationStatus status = findResInstanceRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } return Either.right(status); } String propertyId = resourceInstanceInput.getUniqueId(); - Either findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Input), propertyId, InputsData.class); + Either findPropertyDefRes = janusGraphGenericDao + .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; + JanusGraphOperationStatus status = findPropertyDefRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } return Either.right(status); } @@ -451,13 +462,13 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo ComponentInstanceData resourceInstanceData = findResInstanceRes.left().value(); - ImmutablePair isInputValueExists = inputOperation.findInputValue(resourceInstanceId, propertyId); - if (isInputValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) { + ImmutablePair isInputValueExists = inputOperation.findInputValue(resourceInstanceId, propertyId); + if (isInputValueExists.getLeft() == JanusGraphOperationStatus.ALREADY_EXIST) { log.debug("The property {} already added to the resource instance {}", propertyId, resourceInstanceId); resourceInstanceInput.setValueUniqueUid(isInputValueExists.getRight()); } - if (isInputValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { + if (isInputValueExists.getLeft() != JanusGraphOperationStatus.NOT_FOUND) { log.debug("After finding input value of {} on componenet instance {}", propertyId, resourceInstanceId); return Either.right(isInputValueExists.getLeft()); } @@ -473,20 +484,20 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo SchemaDefinition def = propDataDef.getSchema(); if (def == null) { log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + return Either.right(JanusGraphOperationStatus.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); + return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT); } innerType = propDef.getType(); } log.debug("Before validateAndUpdatePropertyValue"); - Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); + JanusGraphOperationStatus status = allDataTypes.right().value(); BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); return Either.right(status); } @@ -501,21 +512,23 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo log.debug("After validateAndUpdateRules. pair = {} ", pair); if (pair.getRight() != null && !pair.getRight()) { BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceInput.getName(), propertyType); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT); } log.debug("Before adding property value to graph {}", propertyValueData); - Either createNodeResult = titanGenericDao.createNode(propertyValueData, InputValueData.class); + Either createNodeResult = janusGraphGenericDao + .createNode(propertyValueData, InputValueData.class); log.debug("After adding property value to graph {}", propertyValueData); if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); return Either.right(operationStatus); } - Either createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.INPUT_IMPL, null); + Either createRelResult = janusGraphGenericDao + .createRelation(propertyValueData, propertyData, GraphEdgeLabels.INPUT_IMPL, null); if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); + JanusGraphOperationStatus operationStatus = createRelResult.right().value(); log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus); return Either.right(operationStatus); } @@ -525,10 +538,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo 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); + createRelResult = janusGraphGenericDao + .createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.INPUT_VALUE, properties1); if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, operationStatus); return Either.right(operationStatus); @@ -537,7 +551,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo return Either.left(createNodeResult.left().value()); } else { log.error("property value already exists."); - return Either.right(TitanOperationStatus.ALREADY_EXIST); + return Either.right(JanusGraphOperationStatus.ALREADY_EXIST); } } @@ -548,11 +562,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo try { - Either eitherStatus = this.addAttributeToResourceInstance(resourceInstanceAttribute, resourceInstanceId, index); + 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())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value())); return result; } else { AttributeValueData attributeValueData = eitherStatus.left().value(); @@ -582,11 +596,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either result = null; try { - Either eitherAttributeValue = updateAttributeOfResourceInstance(resourceInstanceAttribute, resourceInstanceId); + 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())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherAttributeValue.right().value())); return result; } else { AttributeValueData attributeValueData = eitherAttributeValue.left().value(); @@ -618,11 +632,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo try { - Either eitherStatus = addInputToResourceInstance(resourceInstanceInput, resourceInstanceId, index); + 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())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value())); return result; } else { InputValueData propertyValueData = eitherStatus.left().value(); @@ -630,9 +644,9 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo ComponentInstanceInput propertyValueResult = inputOperation.buildResourceInstanceInput(propertyValueData, resourceInstanceInput); log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); - Either findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(resourceInstanceInput.getPath(), resourceInstanceInput.getUniqueId(), resourceInstanceInput.getDefaultValue()); + Either findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(resourceInstanceInput.getPath(), resourceInstanceInput.getUniqueId(), resourceInstanceInput.getDefaultValue()); if (findDefaultValue.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(findDefaultValue.right().value())); return result; } String defaultValue = findDefaultValue.left().value(); @@ -648,10 +662,10 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (!inTransaction) { if (result == null || result.isRight()) { log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } @@ -665,13 +679,13 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo @Override public StorageOperationStatus updateCustomizationUUID(String componentInstanceId) { - Either vertexByProperty = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId); + Either vertexByProperty = janusGraphGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId); if (vertexByProperty.isRight()) { log.debug("Failed to fetch component instance by id {} error {}", componentInstanceId, vertexByProperty.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(vertexByProperty.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexByProperty.right().value()); } UUID uuid = UUID.randomUUID(); - TitanVertex ciVertex = vertexByProperty.left().value(); + JanusGraphVertex ciVertex = vertexByProperty.left().value(); ciVertex.property(GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty(), uuid.toString()); return StorageOperationStatus.OK; @@ -686,10 +700,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo ComponentInstanceData componentData = new ComponentInstanceData(componentInstance, componentInstance.getGroupInstances().size()); componentData.getComponentInstDataDefinition().setModificationTime(modificationTime); componentData.getComponentInstDataDefinition().setCustomizationUUID(UUID.randomUUID().toString()); - Either updateNode = titanGenericDao.updateNode(componentData, ComponentInstanceData.class); + Either updateNode = janusGraphGenericDao + .updateNode(componentData, ComponentInstanceData.class); if (updateNode.isRight()) { log.error("Failed to update resource {}. status is {}", componentInstance.getUniqueId(), updateNode.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateNode.right().value())); }else{ result = Either.left(updateNode.left().value()); } @@ -700,10 +715,10 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if(!inTransaction){ if (result == null || result.isRight()) { log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java index c173b59020..b429071572 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java @@ -21,9 +21,9 @@ package org.openecomp.sdc.be.model.operations.impl; import fj.data.Either; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.operations.api.IConsumerOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -38,23 +38,25 @@ import java.util.List; @Component("consumer-operation") public class ConsumerOperation implements IConsumerOperation { - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; private static final Logger log = Logger.getLogger(ConsumerOperation.class.getName()); - public ConsumerOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; + public ConsumerOperation(@Qualifier("janusgraph-generic-dao") + JanusGraphGenericDao janusGraphGenericDao) { + this.janusGraphGenericDao = janusGraphGenericDao; } @Override public Either getCredentials(String consumerName) { Either result = null; log.debug("retriving Credentials for: {}", consumerName); - Either getNode = titanGenericDao.getNode(GraphPropertiesDictionary.CONSUMER_NAME.getProperty(), consumerName, ConsumerData.class); + Either getNode = janusGraphGenericDao + .getNode(GraphPropertiesDictionary.CONSUMER_NAME.getProperty(), consumerName, ConsumerData.class); if (getNode.isRight()) { - TitanOperationStatus status = getNode.right().value(); + JanusGraphOperationStatus status = getNode.right().value(); log.error("Error returned after get Consumer Data node {}. status returned is {}", consumerName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); return result; } ConsumerData consumerData = getNode.left().value(); @@ -64,8 +66,9 @@ public class ConsumerOperation implements IConsumerOperation { @Override public Either, StorageOperationStatus> getAll() { log.debug("retrieving all consumers"); - return titanGenericDao.getByCriteria(NodeTypeEnum.ConsumerCredentials, Collections.emptyMap(), ConsumerData.class) - .right().map(DaoStatusConverter::convertTitanStatusToStorageStatus); + return janusGraphGenericDao + .getByCriteria(NodeTypeEnum.ConsumerCredentials, Collections.emptyMap(), ConsumerData.class) + .right().map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); } @Override @@ -78,11 +81,12 @@ public class ConsumerOperation implements IConsumerOperation { Either result = null; try { log.debug("creating Credentials for: {}", consumerData.getUniqueId()); - Either createNode = titanGenericDao.createNode(consumerData, ConsumerData.class); + Either createNode = janusGraphGenericDao + .createNode(consumerData, ConsumerData.class); if (createNode.isRight()) { - TitanOperationStatus status = createNode.right().value(); + JanusGraphOperationStatus status = createNode.right().value(); log.error("Error returned after creating Consumer Data node {}. status returned is {}", consumerData.getUniqueId(), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); return result; } ConsumerData createdConsumerData = createNode.left().value(); @@ -103,11 +107,12 @@ public class ConsumerOperation implements IConsumerOperation { Either result = null; try { log.debug("delete Credentials for: {}", consumerName); - Either deleteNode = titanGenericDao.deleteNode(GraphPropertiesDictionary.CONSUMER_NAME.getProperty(), consumerName, ConsumerData.class); + Either deleteNode = janusGraphGenericDao + .deleteNode(GraphPropertiesDictionary.CONSUMER_NAME.getProperty(), consumerName, ConsumerData.class); if (deleteNode.isRight()) { - TitanOperationStatus status = deleteNode.right().value(); + JanusGraphOperationStatus status = deleteNode.right().value(); log.error("Error returned after delete Consumer Data node {}. status returned is {}", consumerName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); return result; } @@ -131,11 +136,12 @@ public class ConsumerOperation implements IConsumerOperation { Either result = null; try { log.debug("update Credentials for: {}", consumerData.getUniqueId()); - Either updateNode = titanGenericDao.updateNode(consumerData, ConsumerData.class); + Either updateNode = janusGraphGenericDao + .updateNode(consumerData, ConsumerData.class); if (updateNode.isRight()) { - TitanOperationStatus status = updateNode.right().value(); + JanusGraphOperationStatus status = updateNode.right().value(); log.error("Error returned after delete Consumer Data node {}. status returned is {}", consumerData.getUniqueId(), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); return result; } ConsumerData updatedConsumerData = updateNode.left().value(); @@ -150,10 +156,10 @@ public class ConsumerOperation implements IConsumerOperation { if (!inTransaction) { if (result == null || result.isRight()) { log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java index a66dce139b..bce7a2a73c 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java @@ -21,18 +21,18 @@ package org.openecomp.sdc.be.model.operations.impl; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; public class DaoStatusConverter { - public static StorageOperationStatus convertTitanStatusToStorageStatus(TitanOperationStatus titanStatus) { + public static StorageOperationStatus convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus janusGraphStatus) { - if (titanStatus == null) { + if (janusGraphStatus == null) { return StorageOperationStatus.GENERAL_ERROR; } - switch (titanStatus) { + switch (janusGraphStatus) { case OK: return StorageOperationStatus.OK; @@ -54,7 +54,7 @@ public class DaoStatusConverter { case ALREADY_LOCKED: return StorageOperationStatus.FAILED_TO_LOCK_ELEMENT; - case TITAN_SCHEMA_VIOLATION: + case JANUSGRAPH_SCHEMA_VIOLATION: return StorageOperationStatus.SCHEMA_VIOLATION; case INVALID_ID: diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java index 6f9555899b..e39f4b8f5a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java @@ -6,10 +6,10 @@ import org.apache.commons.lang3.tuple.Pair; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.operations.api.DerivedFromOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -24,27 +24,28 @@ import java.util.function.Function; public class DefaultDerivedFromOperation implements DerivedFromOperation { private static final Logger log = Logger.getLogger(DefaultDerivedFromOperation.class.getName()); - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; - public DefaultDerivedFromOperation(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; + public DefaultDerivedFromOperation(JanusGraphGenericDao janusGraphGenericDao) { + this.janusGraphGenericDao = janusGraphGenericDao; } @Override public Either addDerivedFromRelation(String parentUniqueId, String derivedFromUniqueId, NodeTypeEnum nodeType) { UniqueIdData from = new UniqueIdData(nodeType, parentUniqueId); UniqueIdData to = new UniqueIdData(nodeType, derivedFromUniqueId); - return titanGenericDao.createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null) + return janusGraphGenericDao.createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); } @Override public Either getDerivedFromChild(String uniqueId, NodeTypeEnum nodeType, Class clazz) { log.debug("#getDerivedFromChild - fetching derived from entity for node type {} with id {}", nodeType, uniqueId); - return titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.DERIVED_FROM, nodeType, clazz) + return janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.DERIVED_FROM, nodeType, clazz) .bimap(Pair::getKey, - DaoStatusConverter::convertTitanStatusToStorageStatus); + DaoStatusConverter::convertJanusGraphStatusToStorageStatus); } @Override @@ -53,19 +54,19 @@ public class DefaultDerivedFromOperation implements DerivedFromOperation { UniqueIdData to = new UniqueIdData(nodeType, derivedFromUniqueId); return isDerivedFromExists(from, to) .either(isRelationExist -> isRelationExist ? deleteDerivedFrom(from, to) : StorageOperationStatus.OK, - DaoStatusConverter::convertTitanStatusToStorageStatus); + DaoStatusConverter::convertJanusGraphStatusToStorageStatus); } private StorageOperationStatus deleteDerivedFrom(UniqueIdData from, UniqueIdData to) { - return titanGenericDao.deleteRelation(from, to, GraphEdgeLabels.DERIVED_FROM) + return janusGraphGenericDao.deleteRelation(from, to, GraphEdgeLabels.DERIVED_FROM) .either(deletedRelation -> StorageOperationStatus.OK, - DaoStatusConverter::convertTitanStatusToStorageStatus); + DaoStatusConverter::convertJanusGraphStatusToStorageStatus); } - private Either isDerivedFromExists(UniqueIdData from, UniqueIdData to) { - return titanGenericDao.isRelationExist(from, to, GraphEdgeLabels.DERIVED_FROM); + private Either isDerivedFromExists(UniqueIdData from, UniqueIdData to) { + return janusGraphGenericDao.isRelationExist(from, to, GraphEdgeLabels.DERIVED_FROM); } @Override @@ -74,11 +75,14 @@ public class DefaultDerivedFromOperation implements DerivedFromOperation { Map propertiesToMatch = new HashMap<>(); propertiesToMatch.put(GraphPropertiesDictionary.TYPE.getProperty(), childCandidateType); - Either, TitanOperationStatus> getResponse = titanGenericDao.getByCriteria(nodeType, propertiesToMatch, clazz); + Either, JanusGraphOperationStatus> getResponse = janusGraphGenericDao + .getByCriteria(nodeType, propertiesToMatch, clazz); if (getResponse.isRight()) { - TitanOperationStatus titanOperationStatus = getResponse.right().value(); - log.debug("Couldn't fetch type {}, error: {}", childCandidateType, titanOperationStatus); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); + JanusGraphOperationStatus janusGraphOperationStatus = getResponse.right().value(); + log.debug("Couldn't fetch type {}, error: {}", childCandidateType, + janusGraphOperationStatus); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + janusGraphOperationStatus)); } T node = getResponse.left().value().get(0); String childUniqueId = node.getUniqueId(); @@ -91,13 +95,16 @@ public class DefaultDerivedFromOperation implements DerivedFromOperation { do { travelledTypes.add(childType); - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), childUniqueId, GraphEdgeLabels.DERIVED_FROM, + Either>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao + .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), childUniqueId, GraphEdgeLabels.DERIVED_FROM, nodeType, clazz); if (childrenNodes.isRight()) { - if (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND) { - TitanOperationStatus titanOperationStatus = getResponse.right().value(); - log.debug("Couldn't fetch derived from node for type {}, error: {}", childCandidateType, titanOperationStatus); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); + if (childrenNodes.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus janusGraphOperationStatus = getResponse.right().value(); + log.debug("Couldn't fetch derived from node for type {}, error: {}", childCandidateType, + janusGraphOperationStatus); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + janusGraphOperationStatus)); } else { log.debug("Derived from node is not found for type {} - this is OK for root capability.", childCandidateType); return Either.left(false); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java index fd455bcde8..ce9d320ed7 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java @@ -20,8 +20,8 @@ package org.openecomp.sdc.be.model.operations.impl; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Vertex; @@ -31,10 +31,10 @@ 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.janusgraph.JanusGraphOperationStatus; 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.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.datatypes.category.CategoryDataDefinition; import org.openecomp.sdc.be.datatypes.category.GroupingDataDefinition; import org.openecomp.sdc.be.datatypes.category.SubCategoryDataDefinition; @@ -62,13 +62,14 @@ import java.util.*; @Component("element-operation") public class ElementOperation implements IElementOperation { - private static final String COULDN_T_FETCH_TITAN_GRAPH = "Couldn't fetch titan graph"; + private static final String COULDN_T_FETCH_janusGraph_GRAPH = "Couldn't fetch janusgraph graph"; private static final String UNKNOWN_CATEGORY_TYPE = "Unknown category type {}"; - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; - public ElementOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) { + public ElementOperation(@Qualifier("janusgraph-generic-dao") + JanusGraphGenericDao janusGraphGenericDao) { super(); - this.titanGenericDao = titanGenericDao; + this.janusGraphGenericDao = janusGraphGenericDao; } private static final Logger log = Logger.getLogger(ElementOperation.class.getName()); @@ -109,12 +110,13 @@ public class ElementOperation implements IElementOperation { CategoryData categoryData = new CategoryData(nodeType, category); try { - Either createNode = titanGenericDao.createNode(categoryData, CategoryData.class); + Either createNode = janusGraphGenericDao + .createNode(categoryData, CategoryData.class); if (createNode.isRight()) { - TitanOperationStatus value = createNode.right().value(); + JanusGraphOperationStatus value = createNode.right().value(); ActionStatus actionStatus = ActionStatus.GENERAL_ERROR; log.debug("Problem while creating category, reason {}", value); - if (value == TitanOperationStatus.TITAN_SCHEMA_VIOLATION) { + if (value == JanusGraphOperationStatus.JANUSGRAPH_SCHEMA_VIOLATION) { actionStatus = ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS; } result = Either.right(actionStatus); @@ -126,9 +128,9 @@ public class ElementOperation implements IElementOperation { } finally { if (!inTransaction) { if (result != null && result.isLeft()) { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } else { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } } } @@ -146,12 +148,13 @@ public class ElementOperation implements IElementOperation { try { // create edge from category to sub-category - Either categoryNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); + Either categoryNode = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); ActionStatus actionStatus = ActionStatus.GENERAL_ERROR; if (categoryNode.isRight()) { - TitanOperationStatus titanOperationStatus = categoryNode.right().value(); - log.debug("Problem while fetching category, reason {}", titanOperationStatus); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus janusGraphOperationStatus = categoryNode.right().value(); + log.debug("Problem while fetching category, reason {}", janusGraphOperationStatus); + if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) { actionStatus = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND; } result = Either.right(actionStatus); @@ -162,18 +165,20 @@ public class ElementOperation implements IElementOperation { subCategory.setUniqueId(UniqueIdBuilder.buildSubCategoryUid(categoryDataDefinition.getUniqueId(), subCategory.getNormalizedName())); SubCategoryData subCategoryData = new SubCategoryData(nodeType, subCategory); - Either subCategoryNode = titanGenericDao.createNode(subCategoryData, SubCategoryData.class); + Either subCategoryNode = janusGraphGenericDao + .createNode(subCategoryData, SubCategoryData.class); if (subCategoryNode.isRight()) { - TitanOperationStatus titanOperationStatus = subCategoryNode.right().value(); - log.debug("Problem while creating category, reason {}", titanOperationStatus); - if (titanOperationStatus == TitanOperationStatus.TITAN_SCHEMA_VIOLATION) { + JanusGraphOperationStatus janusGraphOperationStatus = subCategoryNode.right().value(); + log.debug("Problem while creating category, reason {}", janusGraphOperationStatus); + if (janusGraphOperationStatus == JanusGraphOperationStatus.JANUSGRAPH_SCHEMA_VIOLATION) { actionStatus = ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY; } result = Either.right(actionStatus); return result; } - Either relation = titanGenericDao.createRelation(categoryNode.left().value(), subCategoryNode.left().value(), GraphEdgeLabels.SUB_CATEGORY, null); + Either relation = janusGraphGenericDao + .createRelation(categoryNode.left().value(), subCategoryNode.left().value(), GraphEdgeLabels.SUB_CATEGORY, null); if (relation.isRight()) { log.debug("Problem while create relation between category and sub-category ", relation.right().value()); result = Either.right(actionStatus); @@ -185,9 +190,9 @@ public class ElementOperation implements IElementOperation { } finally { if (!inTransaction) { if (result != null && result.isLeft()) { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } else { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } } } @@ -200,12 +205,13 @@ public class ElementOperation implements IElementOperation { try { // create edge from sub-category to grouping - Either subCategoryNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); + Either subCategoryNode = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); ActionStatus actionStatus = ActionStatus.GENERAL_ERROR; if (subCategoryNode.isRight()) { - TitanOperationStatus titanOperationStatus = subCategoryNode.right().value(); - log.debug("Problem while fetching category, reason {}", titanOperationStatus); - if (titanOperationStatus == TitanOperationStatus.TITAN_SCHEMA_VIOLATION) { + JanusGraphOperationStatus janusGraphOperationStatus = subCategoryNode.right().value(); + log.debug("Problem while fetching category, reason {}", janusGraphOperationStatus); + if (janusGraphOperationStatus == JanusGraphOperationStatus.JANUSGRAPH_SCHEMA_VIOLATION) { actionStatus = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND; } result = Either.right(actionStatus); @@ -216,18 +222,20 @@ public class ElementOperation implements IElementOperation { grouping.setUniqueId(UniqueIdBuilder.buildGroupingUid(subCatData.getUniqueId(), grouping.getNormalizedName())); GroupingData groupingData = new GroupingData(nodeType, grouping); - Either groupingNode = titanGenericDao.createNode(groupingData, GroupingData.class); + Either groupingNode = janusGraphGenericDao + .createNode(groupingData, GroupingData.class); if (groupingNode.isRight()) { - TitanOperationStatus titanOperationStatus = groupingNode.right().value(); - log.debug("Problem while creating grouping, reason {}", titanOperationStatus); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus janusGraphOperationStatus = groupingNode.right().value(); + log.debug("Problem while creating grouping, reason {}", janusGraphOperationStatus); + if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) { actionStatus = ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY; } result = Either.right(actionStatus); return result; } - Either relation = titanGenericDao.createRelation(subCategoryNode.left().value(), groupingNode.left().value(), GraphEdgeLabels.GROUPING, null); + Either relation = janusGraphGenericDao + .createRelation(subCategoryNode.left().value(), groupingNode.left().value(), GraphEdgeLabels.GROUPING, null); if (relation.isRight()) { log.debug("Problem while create relation between sub-category and grouping", relation.right().value()); result = Either.right(actionStatus); @@ -238,9 +246,9 @@ public class ElementOperation implements IElementOperation { return result; } finally { if (result != null && result.isLeft()) { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } else { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } } } @@ -253,8 +261,9 @@ public class ElementOperation implements IElementOperation { return Either.right(ActionStatus.GENERAL_ERROR); } - Either, TitanOperationStatus> either = titanGenericDao.getAll(nodeType, org.openecomp.sdc.be.resources.data.category.CategoryData.class); - if (either.isRight() && (either.right().value() != TitanOperationStatus.NOT_FOUND)) { + Either, JanusGraphOperationStatus> either = janusGraphGenericDao + .getAll(nodeType, org.openecomp.sdc.be.resources.data.category.CategoryData.class); + if (either.isRight() && (either.right().value() != JanusGraphOperationStatus.NOT_FOUND)) { log.debug("Problem while get all categories. reason - {}", either.right().value()); return Either.right(ActionStatus.GENERAL_ERROR); } @@ -267,8 +276,9 @@ public class ElementOperation implements IElementOperation { CategoryDefinition categoryDefinition = new CategoryDefinition(categoryDataDefinition); String categoryName = categoryDataDefinition.getName(); log.trace("Found category {}, category type {}", categoryName, nodeType); - TitanOperationStatus setSubCategories = setSubCategories(nodeType, categoryDefinition); - if (setSubCategories != TitanOperationStatus.OK) { + JanusGraphOperationStatus + setSubCategories = setSubCategories(nodeType, categoryDefinition); + if (setSubCategories != JanusGraphOperationStatus.OK) { log.debug("Failed to set sub-categories for category {}, category type {}, error {}", categoryName, nodeType, setSubCategories); return Either.right(ActionStatus.GENERAL_ERROR); } @@ -278,25 +288,26 @@ public class ElementOperation implements IElementOperation { return Either.left(categoryList); } finally { if (!inTransaction) { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } - private TitanOperationStatus setSubCategories(NodeTypeEnum parentNodeType, CategoryDefinition parentCategory) { + private JanusGraphOperationStatus setSubCategories(NodeTypeEnum parentNodeType, CategoryDefinition parentCategory) { NodeTypeEnum childNodeType = getChildNodeType(parentNodeType); if (childNodeType != null) { String categoryName = parentCategory.getName(); log.trace("Getting sub-categories for category {}, category type {}", categoryName, parentNodeType); - Either>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentCategory.getUniqueId(), GraphEdgeLabels.SUB_CATEGORY, + Either>, JanusGraphOperationStatus> parentNode = janusGraphGenericDao + .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentCategory.getUniqueId(), GraphEdgeLabels.SUB_CATEGORY, childNodeType, SubCategoryData.class); if (parentNode.isRight()) { - TitanOperationStatus titanOperationStatus = parentNode.right().value(); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value(); + if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) { log.trace("Didn't find subcategories for category {}, category type {}", categoryName, parentNodeType); - titanOperationStatus = TitanOperationStatus.OK; + janusGraphOperationStatus = JanusGraphOperationStatus.OK; } - return titanOperationStatus; + return janusGraphOperationStatus; } List> subsCategoriesData = parentNode.left().value(); List subCategoriesDefinitions = new ArrayList<>(); @@ -305,32 +316,34 @@ public class ElementOperation implements IElementOperation { SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(subCategoryDataDefinition); log.trace("Found sub-category {} for category {}, category type {}", subCategoryDataDefinition.getName(), categoryName, parentNodeType); - TitanOperationStatus setGroupings = setGroupings(childNodeType, subCategoryDefinition); - if (setGroupings != TitanOperationStatus.OK) { + JanusGraphOperationStatus + setGroupings = setGroupings(childNodeType, subCategoryDefinition); + if (setGroupings != JanusGraphOperationStatus.OK) { log.debug("Failed to set groupings for sub-category {}, sub-category type {}, error {}", subCategoryDataDefinition.getName(), childNodeType, setGroupings); - return TitanOperationStatus.GENERAL_ERROR; + return JanusGraphOperationStatus.GENERAL_ERROR; } subCategoriesDefinitions.add(subCategoryDefinition); } parentCategory.setSubcategories(subCategoriesDefinitions); } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } - private TitanOperationStatus setGroupings(NodeTypeEnum parentNodeType, SubCategoryDefinition parentSubCategory) { + private JanusGraphOperationStatus setGroupings(NodeTypeEnum parentNodeType, SubCategoryDefinition parentSubCategory) { NodeTypeEnum childNodeType = getChildNodeType(parentNodeType); if (childNodeType != null) { String subCategoryName = parentSubCategory.getName(); log.trace("Getting groupings for subcategory {}, subcategory type {}", subCategoryName, parentNodeType); - Either>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentSubCategory.getUniqueId(), GraphEdgeLabels.GROUPING, + Either>, JanusGraphOperationStatus> parentNode = janusGraphGenericDao + .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentSubCategory.getUniqueId(), GraphEdgeLabels.GROUPING, childNodeType, GroupingData.class); if (parentNode.isRight()) { - TitanOperationStatus titanOperationStatus = parentNode.right().value(); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value(); + if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) { log.trace("Didn't find groupings for subcategory {}, subcategory type {}", subCategoryName, parentNodeType); - titanOperationStatus = TitanOperationStatus.OK; + janusGraphOperationStatus = JanusGraphOperationStatus.OK; } - return titanOperationStatus; + return janusGraphOperationStatus; } List> groupingData = parentNode.left().value(); List groupingDefinitions = new ArrayList<>(); @@ -341,7 +354,7 @@ public class ElementOperation implements IElementOperation { } parentSubCategory.setGroupings(groupingDefinitions); } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } private static NodeTypeEnum getChildNodeType(NodeTypeEnum parentTypeEnum) { @@ -370,11 +383,13 @@ public class ElementOperation implements IElementOperation { return Either.right(ActionStatus.GENERAL_ERROR); } - Either categoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); + Either categoryDataEither = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); if (categoryDataEither.isRight()) { - TitanOperationStatus titanOperationStatus = categoryDataEither.right().value(); - log.debug("Problem while get category by id {}. reason {}", categoryId, titanOperationStatus); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus janusGraphOperationStatus = categoryDataEither.right().value(); + log.debug("Problem while get category by id {}. reason {}", categoryId, + janusGraphOperationStatus); + if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) { return Either.right(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND); } return Either.right(ActionStatus.GENERAL_ERROR); @@ -382,7 +397,7 @@ public class ElementOperation implements IElementOperation { CategoryDataDefinition categoryDataDefinition = categoryDataEither.left().value().getCategoryDataDefinition(); return Either.left(new CategoryDefinition(categoryDataDefinition)); } finally { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } @@ -394,11 +409,13 @@ public class ElementOperation implements IElementOperation { return Either.right(ActionStatus.GENERAL_ERROR); } - Either subCategoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); + Either subCategoryDataEither = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); if (subCategoryDataEither.isRight()) { - TitanOperationStatus titanOperationStatus = subCategoryDataEither.right().value(); - log.debug("Problem while get sub-category by id {}. reason {}", subCategoryId, titanOperationStatus); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus janusGraphOperationStatus = subCategoryDataEither.right().value(); + log.debug("Problem while get sub-category by id {}. reason {}", subCategoryId, + janusGraphOperationStatus); + if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) { return Either.right(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND); } return Either.right(ActionStatus.GENERAL_ERROR); @@ -406,7 +423,7 @@ public class ElementOperation implements IElementOperation { SubCategoryDataDefinition subCategoryDataDefinition = subCategoryDataEither.left().value().getSubCategoryDataDefinition(); return Either.left(new SubCategoryDefinition(subCategoryDataDefinition)); } finally { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } @@ -419,24 +436,25 @@ public class ElementOperation implements IElementOperation { result = Either.right(ActionStatus.GENERAL_ERROR); return result; } - Either categoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); + Either categoryDataEither = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); if (categoryDataEither.isRight()) { log.debug("Failed to retrieve category for id {} ", categoryId); result = Either.right(ActionStatus.GENERAL_ERROR); return result; } - Either graph = titanGenericDao.getGraph(); + Either graph = janusGraphGenericDao.getGraph(); if (graph.isRight()) { - log.debug(COULDN_T_FETCH_TITAN_GRAPH); + log.debug(COULDN_T_FETCH_janusGraph_GRAPH); result = Either.right(ActionStatus.GENERAL_ERROR); return result; } - TitanGraph tGraph = graph.left().value(); + JanusGraph tGraph = graph.left().value(); - Iterable verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId).vertices(); - Iterator iterator = verticesArtifact.iterator(); + Iterable verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId).vertices(); + Iterator iterator = verticesArtifact.iterator(); if (!iterator.hasNext()) { log.debug("No category node for id = {}", categoryId); result = Either.right(ActionStatus.GENERAL_ERROR); @@ -449,9 +467,9 @@ public class ElementOperation implements IElementOperation { return result; } finally { if (result != null && result.isLeft()) { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } else { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } } } @@ -465,24 +483,25 @@ public class ElementOperation implements IElementOperation { result = Either.right(ActionStatus.GENERAL_ERROR); return result; } - Either subCategoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); + Either subCategoryDataEither = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); if (subCategoryDataEither.isRight()) { log.debug("Failed to retrieve sub-category for id {}", subCategoryId); result = Either.right(ActionStatus.GENERAL_ERROR); return result; } - Either graph = titanGenericDao.getGraph(); + Either graph = janusGraphGenericDao.getGraph(); if (graph.isRight()) { - log.debug(COULDN_T_FETCH_TITAN_GRAPH); + log.debug(COULDN_T_FETCH_janusGraph_GRAPH); result = Either.right(ActionStatus.GENERAL_ERROR); return result; } - TitanGraph tGraph = graph.left().value(); + JanusGraph tGraph = graph.left().value(); - Iterable verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId).vertices(); - Iterator iterator = verticesArtifact.iterator(); + Iterable verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId).vertices(); + Iterator iterator = verticesArtifact.iterator(); if (!iterator.hasNext()) { log.debug("No sub-category node for id {}", subCategoryId); result = Either.right(ActionStatus.GENERAL_ERROR); @@ -496,9 +515,9 @@ public class ElementOperation implements IElementOperation { return result; } finally { if (result != null && result.isLeft()) { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } else { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } } @@ -513,24 +532,25 @@ public class ElementOperation implements IElementOperation { result = Either.right(ActionStatus.GENERAL_ERROR); return result; } - Either groupingDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class); + Either groupingDataEither = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class); if (groupingDataEither.isRight()) { log.debug("Failed to retrieve grouping for id {}", groupingId); result = Either.right(ActionStatus.GENERAL_ERROR); return result; } - Either graph = titanGenericDao.getGraph(); + Either graph = janusGraphGenericDao.getGraph(); if (graph.isRight()) { - log.debug(COULDN_T_FETCH_TITAN_GRAPH); + log.debug(COULDN_T_FETCH_janusGraph_GRAPH); result = Either.right(ActionStatus.GENERAL_ERROR); return result; } - TitanGraph tGraph = graph.left().value(); + JanusGraph tGraph = graph.left().value(); - Iterable verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId).vertices(); - Iterator iterator = verticesArtifact.iterator(); + Iterable verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId).vertices(); + Iterator iterator = verticesArtifact.iterator(); if (!iterator.hasNext()) { log.debug("No grouping node for id {}", groupingId); result = Either.right(ActionStatus.GENERAL_ERROR); @@ -544,9 +564,9 @@ public class ElementOperation implements IElementOperation { return result; } finally { if (result != null && result.isLeft()) { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } else { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } } } @@ -557,8 +577,9 @@ public class ElementOperation implements IElementOperation { Map properties = new HashMap<>(); properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName); try { - Either, TitanOperationStatus> categoryEither = titanGenericDao.getByCriteria(nodeType, properties, CategoryData.class); - if (categoryEither.isRight() && categoryEither.right().value() != TitanOperationStatus.NOT_FOUND) { + Either, JanusGraphOperationStatus> categoryEither = janusGraphGenericDao + .getByCriteria(nodeType, properties, CategoryData.class); + if (categoryEither.isRight() && categoryEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) { log.debug("Failed to get categories, nodeType {}, normalizedName {}, error {}", nodeType, normalizedName, categoryEither.right().value()); return Either.right(ActionStatus.GENERAL_ERROR); } @@ -575,7 +596,7 @@ public class ElementOperation implements IElementOperation { return Either.left(true); } } finally { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } @@ -584,8 +605,9 @@ public class ElementOperation implements IElementOperation { String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(parentCategoryId, subCategoryNormName); try { - Either subCategoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); - if (subCategoryDataEither.isRight() && subCategoryDataEither.right().value() != TitanOperationStatus.NOT_FOUND) { + Either subCategoryDataEither = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); + if (subCategoryDataEither.isRight() && subCategoryDataEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) { log.debug("Failed to get sub-category with id {}, error {}", subCategoryId, subCategoryDataEither.right().value()); return Either.right(ActionStatus.GENERAL_ERROR); } @@ -598,7 +620,7 @@ public class ElementOperation implements IElementOperation { return Either.left(true); } } finally { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } @@ -607,8 +629,9 @@ public class ElementOperation implements IElementOperation { String groupingId = UniqueIdBuilder.buildGroupingUid(parentSubCategoryId, groupingNormName); try { - Either groupingDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class); - if (groupingDataEither.isRight() && groupingDataEither.right().value() != TitanOperationStatus.NOT_FOUND) { + Either groupingDataEither = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class); + if (groupingDataEither.isRight() && groupingDataEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) { log.debug("Failed to get grouping with id {}, error {}", groupingId, groupingDataEither.right().value()); return Either.right(ActionStatus.GENERAL_ERROR); } @@ -621,7 +644,7 @@ public class ElementOperation implements IElementOperation { return Either.left(true); } } finally { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } @@ -630,8 +653,9 @@ public class ElementOperation implements IElementOperation { Map properties = new HashMap<>(); properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName); try { - Either, TitanOperationStatus> subCategoryEither = titanGenericDao.getByCriteria(nodeType, properties, SubCategoryData.class); - if (subCategoryEither.isRight() && subCategoryEither.right().value() != TitanOperationStatus.NOT_FOUND) { + Either, JanusGraphOperationStatus> subCategoryEither = janusGraphGenericDao + .getByCriteria(nodeType, properties, SubCategoryData.class); + if (subCategoryEither.isRight() && subCategoryEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) { log.debug("Failed to get sub-categories, nodeType {}, normalizedName {}, error {}", nodeType, normalizedName, subCategoryEither.right().value()); return Either.right(ActionStatus.GENERAL_ERROR); } @@ -646,7 +670,7 @@ public class ElementOperation implements IElementOperation { return Either.left(null); } } finally { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } @@ -655,8 +679,9 @@ public class ElementOperation implements IElementOperation { Map properties = new HashMap<>(); properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), groupingNormalizedName); try { - Either, TitanOperationStatus> groupingEither = titanGenericDao.getByCriteria(nodeType, properties, GroupingData.class); - if (groupingEither.isRight() && groupingEither.right().value() != TitanOperationStatus.NOT_FOUND) { + Either, JanusGraphOperationStatus> groupingEither = janusGraphGenericDao + .getByCriteria(nodeType, properties, GroupingData.class); + if (groupingEither.isRight() && groupingEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) { log.debug("Failed to get grouping, nodeType {}, normalizedName {}, error {}", nodeType, groupingNormalizedName, groupingEither.right().value()); return Either.right(ActionStatus.GENERAL_ERROR); } @@ -671,7 +696,7 @@ public class ElementOperation implements IElementOperation { return Either.left(null); } } finally { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } @@ -682,7 +707,8 @@ public class ElementOperation implements IElementOperation { @Override public Either, ActionStatus> getAllTags() { try { - Either, TitanOperationStatus> either = titanGenericDao.getAll(NodeTypeEnum.Tag, TagData.class); + Either, JanusGraphOperationStatus> either = janusGraphGenericDao + .getAll(NodeTypeEnum.Tag, TagData.class); if (either.isRight()) { log.debug("Problem while get all tags. reason - {}", either.right().value()); return Either.right(ActionStatus.GENERAL_ERROR); @@ -691,7 +717,7 @@ public class ElementOperation implements IElementOperation { List tagList = convertToListOfTag(tagDataList); return Either.left(tagList); } finally { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } @@ -708,12 +734,14 @@ public class ElementOperation implements IElementOperation { } else { categoryUid = UniqueIdBuilder.buildServiceCategoryUid(name, type); } - Either either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(type), categoryUid, clazz); + Either either = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(type), categoryUid, clazz); if (either.isRight()) { - TitanOperationStatus titanOperationStatus = either.right().value(); - log.debug("Problem while geting category with id {}. reason - {}", categoryUid, titanOperationStatus.name()); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus janusGraphOperationStatus = either.right().value(); + log.debug("Problem while geting category with id {}. reason - {}", categoryUid, janusGraphOperationStatus + .name()); + if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) { return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); } else { return Either.right(StorageOperationStatus.GENERAL_ERROR); @@ -804,12 +832,14 @@ public class ElementOperation implements IElementOperation { String categoryUid = UniqueIdBuilder.buildServiceCategoryUid(name, type); Map props = new HashMap<>(); props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(name)); - Either, TitanOperationStatus> either = titanGenericDao.getByCriteria(type, props, clazz); + Either, JanusGraphOperationStatus> either = janusGraphGenericDao + .getByCriteria(type, props, clazz); if (either.isRight()) { - TitanOperationStatus titanOperationStatus = either.right().value(); - log.debug("Problem while geting category with id {}. reason - {}", categoryUid, titanOperationStatus.name()); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus janusGraphOperationStatus = either.right().value(); + log.debug("Problem while geting category with id {}. reason - {}", categoryUid, janusGraphOperationStatus + .name()); + if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) { return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); } else { return Either.right(StorageOperationStatus.GENERAL_ERROR); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java index b87da5ad9a..009f375a13 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 @@ -20,8 +20,8 @@ package org.openecomp.sdc.be.model.operations.impl; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -33,7 +33,7 @@ public class GraphLockOperation implements IGraphLockOperation { private static final Logger log = Logger.getLogger(GraphLockOperation.class.getName()); @javax.annotation.Resource - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; public GraphLockOperation() { super(); @@ -47,15 +47,15 @@ public class GraphLockOperation implements IGraphLockOperation { @Override public StorageOperationStatus lockComponent(String componentId, NodeTypeEnum nodeType) { log.info("lock resource with id {}", componentId); - TitanOperationStatus lockElementStatus = null; + JanusGraphOperationStatus lockElementStatus = null; try { - lockElementStatus = titanGenericDao.lockElement(componentId, nodeType); + lockElementStatus = janusGraphGenericDao.lockElement(componentId, nodeType); } catch (Exception e) { - lockElementStatus = TitanOperationStatus.ALREADY_LOCKED; + lockElementStatus = JanusGraphOperationStatus.ALREADY_LOCKED; } - return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(lockElementStatus); } @@ -66,30 +66,32 @@ public class GraphLockOperation implements IGraphLockOperation { */ @Override public StorageOperationStatus unlockComponent(String componentId, NodeTypeEnum nodeType) { - TitanOperationStatus lockElementStatus = titanGenericDao.releaseElement(componentId, nodeType); - return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus); + JanusGraphOperationStatus lockElementStatus = janusGraphGenericDao + .releaseElement(componentId, nodeType); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(lockElementStatus); } @Override public StorageOperationStatus unlockComponentByName(String name, String componentId, NodeTypeEnum nodeType) { - TitanOperationStatus lockElementStatus = titanGenericDao.releaseElement(name, nodeType); - return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus); + JanusGraphOperationStatus + lockElementStatus = janusGraphGenericDao.releaseElement(name, nodeType); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(lockElementStatus); } @Override public StorageOperationStatus lockComponentByName(String name, NodeTypeEnum nodeType) { log.info("lock resource with name {}", name); - TitanOperationStatus lockElementStatus = null; + JanusGraphOperationStatus lockElementStatus = null; try { - lockElementStatus = titanGenericDao.lockElement(name, nodeType); + lockElementStatus = janusGraphGenericDao.lockElement(name, nodeType); } catch (Exception e) { - lockElementStatus = TitanOperationStatus.ALREADY_LOCKED; + lockElementStatus = JanusGraphOperationStatus.ALREADY_LOCKED; } - return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(lockElementStatus); } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java index 4c86af45e5..39d4c73afb 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,8 +20,8 @@ package org.openecomp.sdc.be.model.operations.impl; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -31,9 +31,9 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; 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.elements.GroupInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; @@ -74,37 +74,38 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI Either, StorageOperationStatus> result = null; List groupInstanceRes = new ArrayList<>(); - Either graph = titanGenericDao.getGraph(); + Either graph = janusGraphGenericDao.getGraph(); if (graph.isRight()) { log.debug("Failed to work with graph {}", graph.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(graph.right().value())); } - TitanGraph tGraph = graph.left().value(); + JanusGraph tGraph = graph.left().value(); @SuppressWarnings("unchecked") - Iterable vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices(); + Iterable vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices(); if (vertices == null || vertices.iterator() == null || !vertices.iterator().hasNext()) { log.debug("No nodes for type {} for id = {}", parentType, parentId); result = Either.right(StorageOperationStatus.NOT_FOUND); return result; } - Iterator iterator = vertices.iterator(); + Iterator iterator = vertices.iterator(); Vertex vertex = iterator.next(); Map edgeProperties = null; - Either>, TitanOperationStatus> childrenByEdgeCriteria = titanGenericDao.getChildrenByEdgeCriteria(vertex, parentId, GraphEdgeLabels.GROUP_INST, NodeTypeEnum.GroupInstance, + Either>, JanusGraphOperationStatus> childrenByEdgeCriteria = janusGraphGenericDao + .getChildrenByEdgeCriteria(vertex, parentId, GraphEdgeLabels.GROUP_INST, NodeTypeEnum.GroupInstance, GroupInstanceData.class, edgeProperties); if (childrenByEdgeCriteria.isRight()) { - TitanOperationStatus status = childrenByEdgeCriteria.right().value(); + JanusGraphOperationStatus status = childrenByEdgeCriteria.right().value(); log.debug("Failed to find group instance {} on graph", childrenByEdgeCriteria.right().value()); - if (status == TitanOperationStatus.NOT_FOUND) { + if (status == JanusGraphOperationStatus.NOT_FOUND) { return Either.left(groupInstanceRes); } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } List> list = childrenByEdgeCriteria.left().value(); @@ -120,16 +121,16 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI } GroupDefinition groupDefinition = groupRes.left().value(); - Either, TitanOperationStatus> groupInstancePropertyValuesRes = getAllGroupInstancePropertyValuesData(groupInstData); + Either, JanusGraphOperationStatus> groupInstancePropertyValuesRes = getAllGroupInstancePropertyValuesData(groupInstData); if(groupInstancePropertyValuesRes.isRight()){ - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(groupInstancePropertyValuesRes.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(groupInstancePropertyValuesRes.right().value())); } buildGroupInstanceFromGroup(groupInstance, groupDefinition, groupInstancePropertyValuesRes.left().value()); - Either>, TitanOperationStatus> artifactsRes = getGroupArtifactsPairs(groupInstance.getUniqueId()); + Either>, JanusGraphOperationStatus> artifactsRes = getGroupArtifactsPairs(groupInstance.getUniqueId()); if (artifactsRes.isRight()) { - TitanOperationStatus status = artifactsRes.right().value(); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + JanusGraphOperationStatus status = artifactsRes.right().value(); + if (status != JanusGraphOperationStatus.OK) { + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); return result; } } else { @@ -175,11 +176,11 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI try { - Either eitherStatus = addPropertyToGroupInstance(groupInstanceProperty, groupInstanceId, index); + Either eitherStatus = addPropertyToGroupInstance(groupInstanceProperty, groupInstanceId, index); if (eitherStatus.isRight()) { log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", groupInstanceProperty, groupInstanceId, eitherStatus.right().value().name()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value())); return result; } else { PropertyValueData propertyValueData = eitherStatus.left().value(); @@ -187,9 +188,9 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, groupInstanceProperty); log.debug("The returned GroupInstanceProperty is {}", propertyValueResult); - Either findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(groupInstanceProperty.getPath(), groupInstanceProperty.getUniqueId(), groupInstanceProperty.getDefaultValue()); + Either findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(groupInstanceProperty.getPath(), groupInstanceProperty.getUniqueId(), groupInstanceProperty.getDefaultValue()); if (findDefaultValue.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(findDefaultValue.right().value())); return result; } String defaultValue = findDefaultValue.left().value(); @@ -205,10 +206,10 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI if (!inTransaction) { if (result == null || result.isRight()) { log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } @@ -233,25 +234,27 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI * @param index * @return */ - public Either addPropertyToGroupInstance(ComponentInstanceProperty groupInstanceProperty, String groupInstanceId, Integer index) { + public Either addPropertyToGroupInstance(ComponentInstanceProperty groupInstanceProperty, String groupInstanceId, Integer index) { - Either findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupInstanceId, GroupInstanceData.class); + Either findResInstanceRes = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupInstanceId, GroupInstanceData.class); if (findResInstanceRes.isRight()) { - TitanOperationStatus status = findResInstanceRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; + JanusGraphOperationStatus status = findResInstanceRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } return Either.right(status); } String propertyId = groupInstanceProperty.getUniqueId(); - Either findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class); + Either findPropertyDefRes = janusGraphGenericDao + .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; + JanusGraphOperationStatus status = findPropertyDefRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } return Either.right(status); } @@ -262,11 +265,11 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI PropertyData propertyData = findPropertyDefRes.left().value(); GroupInstanceData resourceInstanceData = findResInstanceRes.left().value(); - ImmutablePair isPropertyValueExists = propertyOperation.findPropertyValue(groupInstanceId, propertyId); - if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) { + ImmutablePair isPropertyValueExists = propertyOperation.findPropertyValue(groupInstanceId, propertyId); + if (isPropertyValueExists.getLeft() == JanusGraphOperationStatus.ALREADY_EXIST) { log.debug("The property {} already added to the resource instance {}", propertyId, groupInstanceId); groupInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight()); - Either updatePropertyOfResourceInstance = updatePropertyOfGroupInstance(groupInstanceProperty, groupInstanceId); + Either updatePropertyOfResourceInstance = updatePropertyOfGroupInstance(groupInstanceProperty, groupInstanceId); if (updatePropertyOfResourceInstance.isRight()) { BeEcompErrorManager.getInstance().logInternalFlowError(UPDATE_PROPERTY_VALUE_ON_COMPONENT_INSTANCE, FAILED_TO_UPDATE_PROPERTY_VALUE_ON_INSTANCE_STATUS_IS + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR); return Either.right(updatePropertyOfResourceInstance.right().value()); @@ -274,7 +277,7 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI return Either.left(updatePropertyOfResourceInstance.left().value()); } - if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { + if (isPropertyValueExists.getLeft() != JanusGraphOperationStatus.NOT_FOUND) { log.debug("After finding property value of {} on componenet instance {}", propertyId, groupInstanceId); return Either.right(isPropertyValueExists.getLeft()); } @@ -290,20 +293,20 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI SchemaDefinition def = propDataDef.getSchema(); if (def == null) { log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + return Either.right(JanusGraphOperationStatus.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); + return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT); } innerType = propDef.getType(); } log.debug("Before validateAndUpdatePropertyValue"); - Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); + JanusGraphOperationStatus status = allDataTypes.right().value(); BeEcompErrorManager.getInstance().logInternalFlowError(UPDATE_PROPERTY_VALUE_ON_COMPONENT_INSTANCE, FAILED_TO_UPDATE_PROPERTY_VALUE_ON_INSTANCE_STATUS_IS + status, ErrorSeverity.ERROR); return Either.right(status); } @@ -314,7 +317,7 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI if (isValid.isRight()) { Boolean res = isValid.right().value(); if (!res) { - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT); } } else { Object object = isValid.left().value(); @@ -333,32 +336,35 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI log.debug("After validateAndUpdateRules. pair = {}", pair); if (pair.getRight() != null && !pair.getRight()) { BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProperty.getName(), propertyType); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT); } propertyOperation.addRulesToNewPropertyValue(propertyValueData, groupInstanceProperty, groupInstanceId); log.debug("Before adding property value to graph {}", propertyValueData); - Either createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class); + Either createNodeResult = janusGraphGenericDao + .createNode(propertyValueData, PropertyValueData.class); log.debug("After adding property value to graph {}", propertyValueData); if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); return Either.right(operationStatus); } propertyValueData = createNodeResult.left().value(); - Either createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null); + Either createRelResult = janusGraphGenericDao + .createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null); if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); + JanusGraphOperationStatus 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); + createRelResult = janusGraphGenericDao + .createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null); if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); + JanusGraphOperationStatus operationStatus = createRelResult.right().value(); log.error("Failed to associate resource instance {} property value {} in graph. status is {}", groupInstanceId, uniqueId, operationStatus); return Either.right(operationStatus); } @@ -366,7 +372,7 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI return Either.left(propertyValueData); } else { log.error("property value already exists."); - return Either.right(TitanOperationStatus.ALREADY_EXIST); + return Either.right(JanusGraphOperationStatus.ALREADY_EXIST); } } @@ -376,9 +382,9 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI * * @return */ - public Either updatePropertyOfGroupInstance(ComponentInstanceProperty groupInstanceProerty, String groupInstanceId) { + public Either updatePropertyOfGroupInstance(ComponentInstanceProperty groupInstanceProerty, String groupInstanceId) { - Wrapper errorWrapper = new Wrapper<>(); + Wrapper errorWrapper = new Wrapper<>(); UpdateDataContainer updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.PROPERTY_IMPL, (() -> PropertyData.class), (() -> PropertyValueData.class), NodeTypeEnum.Property, NodeTypeEnum.PropertyValue); @@ -403,19 +409,19 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI SchemaDefinition def = propDataDef.getSchema(); if (def == null) { log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + return Either.right(JanusGraphOperationStatus.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); + return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT); } innerType = propDef.getType(); } // Specific Update Logic - Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); + JanusGraphOperationStatus status = allDataTypes.right().value(); BeEcompErrorManager.getInstance().logInternalFlowError(UPDATE_PROPERTY_VALUE_ON_COMPONENT_INSTANCE, FAILED_TO_UPDATE_PROPERTY_VALUE_ON_INSTANCE_STATUS_IS + status, ErrorSeverity.ERROR); return Either.right(status); } @@ -425,7 +431,7 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI if (isValid.isRight()) { Boolean res = isValid.right().value(); if (!res) { - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT); } } else { Object object = isValid.left().value(); @@ -440,13 +446,14 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI ImmutablePair pair = propertyOperation.validateAndUpdateRules(propertyType, groupInstanceProerty.getRules(), innerType, allDataTypes.left().value(), true); if (pair.getRight() != null && !pair.getRight()) { BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProerty.getName(), propertyType); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT); } propertyOperation.updateRulesInPropertyValue(propertyValueData, groupInstanceProerty, groupInstanceId); - Either updateRes = titanGenericDao.updateNode(propertyValueData, PropertyValueData.class); + Either updateRes = janusGraphGenericDao + .updateNode(propertyValueData, PropertyValueData.class); if (updateRes.isRight()) { - TitanOperationStatus status = updateRes.right().value(); + JanusGraphOperationStatus status = updateRes.right().value(); return Either.right(status); } else { return Either.left(updateRes.left().value()); @@ -505,7 +512,7 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI } private void preUpdateElementOfResourceInstanceValidations(UpdateDataContainer updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, - String resourceInstanceId, Wrapper errorWrapper) { + String resourceInstanceId, Wrapper errorWrapper) { if (errorWrapper.isEmpty()) { // Verify VFC instance Exist @@ -529,14 +536,15 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI } private void validateElementConnectedToInstance(UpdateDataContainer updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, - Wrapper errorWrapper) { - Either, TitanOperationStatus> child = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), resourceInstanceProerty.getValueUniqueUid(), + Wrapper errorWrapper) { + Either, JanusGraphOperationStatus> child = janusGraphGenericDao + .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; + JanusGraphOperationStatus status = child.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } errorWrapper.setInnerElement(status); @@ -546,16 +554,17 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI } private void validateElementConnectedToComponentInstanceExist(UpdateDataContainer updateDataContainer, - IComponentInstanceConnectedElement resourceInstanceProerty, Wrapper errorWrapper) { + IComponentInstanceConnectedElement resourceInstanceProerty, Wrapper errorWrapper) { String valueUniqueUid = resourceInstanceProerty.getValueUniqueUid(); if (valueUniqueUid == null) { - errorWrapper.setInnerElement(TitanOperationStatus.INVALID_ID); + errorWrapper.setInnerElement(JanusGraphOperationStatus.INVALID_ID); } else { - Either findPropertyValueRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), valueUniqueUid, updateDataContainer.getSomeValueDataClassGen().get()); + Either findPropertyValueRes = janusGraphGenericDao + .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; + JanusGraphOperationStatus status = findPropertyValueRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } errorWrapper.setInnerElement(status); } else { @@ -565,31 +574,33 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI } private void validateElementConnectedToComponentExist(UpdateDataContainer updateDataContainer, - IComponentInstanceConnectedElement resourceInstanceElementConnected, Wrapper errorWrapper) { + IComponentInstanceConnectedElement resourceInstanceElementConnected, Wrapper errorWrapper) { String uniqueId = resourceInstanceElementConnected.getUniqueId(); - Either findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeType()), uniqueId, updateDataContainer.getSomeDataClassGen().get()); + Either findPropertyDefRes = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeType()), uniqueId, updateDataContainer.getSomeDataClassGen().get()); if (findPropertyDefRes.isRight()) { - TitanOperationStatus status = findPropertyDefRes.right().value(); + JanusGraphOperationStatus status = findPropertyDefRes.right().value(); errorWrapper.setInnerElement(status); } } - private void validateGIExist(String resourceInstanceId, Wrapper errorWrapper) { + private void validateGIExist(String resourceInstanceId, Wrapper errorWrapper) { validateGIExist(resourceInstanceId, null, errorWrapper); } - private void validateGIExist(String resourceInstanceId, Wrapper compInsDataWrapper, Wrapper errorWrapper) { + private void validateGIExist(String resourceInstanceId, Wrapper compInsDataWrapper, Wrapper errorWrapper) { validateElementExistInGraph(resourceInstanceId, NodeTypeEnum.GroupInstance, () -> GroupInstanceData.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()); + Wrapper errorWrapper) { + Either findResInstanceRes = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(elementNodeType), elementUniqueId, elementClassGen.get()); if (findResInstanceRes.isRight()) { - TitanOperationStatus status = findResInstanceRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; + JanusGraphOperationStatus status = findResInstanceRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } errorWrapper.setInnerElement(status); } else { @@ -627,16 +638,17 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI return updatedProperty; } - private Either>, TitanOperationStatus> getGroupArtifactsPairs(String groupUniqueId) { + private Either>, JanusGraphOperationStatus> getGroupArtifactsPairs(String groupUniqueId) { - Either>, TitanOperationStatus> result = null; + Either>, JanusGraphOperationStatus> result = null; - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupUniqueId, GraphEdgeLabels.GROUP_ARTIFACT_REF, + Either>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao + .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupUniqueId, GraphEdgeLabels.GROUP_ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class); if (childrenNodes.isRight()) { - TitanOperationStatus status = childrenNodes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; + JanusGraphOperationStatus status = childrenNodes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.OK; } result = Either.right(status); @@ -696,24 +708,26 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI for (GroupInstance groupDefinition : associatedGroups) { UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.GroupInstance, groupDefinition.getUniqueId()); - Either deleteRelation = titanGenericDao.deleteRelation(groupData, oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF); + Either deleteRelation = janusGraphGenericDao + .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; + JanusGraphOperationStatus status = deleteRelation.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); } - Either createRelation = titanGenericDao.createRelation(groupData, newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props); + Either createRelation = janusGraphGenericDao + .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; + JanusGraphOperationStatus status = createRelation.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); } } @@ -721,17 +735,17 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI return StorageOperationStatus.OK; } - private Either, TitanOperationStatus> getAllGroupInstancePropertyValuesData(GroupInstanceData groupInstData) { + private Either, JanusGraphOperationStatus> getAllGroupInstancePropertyValuesData(GroupInstanceData groupInstData) { - Either, TitanOperationStatus> result = null; + Either, JanusGraphOperationStatus> result = null; try{ - Either>, TitanOperationStatus> getPropertyValueChildrenRes = - titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), groupInstData.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, + Either>, JanusGraphOperationStatus> getPropertyValueChildrenRes = + janusGraphGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), groupInstData.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class, true); if(getPropertyValueChildrenRes.isRight()){ - TitanOperationStatus status = getPropertyValueChildrenRes.right().value(); + JanusGraphOperationStatus status = getPropertyValueChildrenRes.right().value(); log.debug("Failed to fetch property value nodes for group instance {}. Status is {}. ", groupInstData.getName(), status); - if(status == TitanOperationStatus.NOT_FOUND){ + if(status == JanusGraphOperationStatus.NOT_FOUND){ result = Either.left(null); }else{ result = Either.right(status); @@ -743,7 +757,7 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI } catch(Exception e){ log.debug("The Exception occured during fetch group instance () property values. The message is {}. ", groupInstData.getName(), e.getMessage(), e); if(result == null){ - result = Either.right(TitanOperationStatus.GENERAL_ERROR); + result = Either.right(JanusGraphOperationStatus.GENERAL_ERROR); } } return result; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java index 11878376f5..c8135ad54b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java @@ -25,19 +25,19 @@ import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; -import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.IGroupOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -58,14 +58,14 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation private static final Logger log = Logger.getLogger(GroupOperation.class.getName()); - private final TitanDao titanDao; + private final JanusGraphDao janusGraphDao; private final TopologyTemplateOperation topologyTemplateOperation; private final PropertyOperation propertyOperation; private final GroupTypeOperation groupTypeOperation; private final ApplicationDataTypeCache dataTypeCache; - public GroupOperation(TitanDao titanDao, TopologyTemplateOperation topologyTemplateOperation, PropertyOperation propertyOperation, GroupTypeOperation groupTypeOperation, ApplicationDataTypeCache dataTypeCache) { - this.titanDao = titanDao; + public GroupOperation(JanusGraphDao janusGraphDao, TopologyTemplateOperation topologyTemplateOperation, PropertyOperation propertyOperation, GroupTypeOperation groupTypeOperation, ApplicationDataTypeCache dataTypeCache) { + this.janusGraphDao = janusGraphDao; this.topologyTemplateOperation = topologyTemplateOperation; this.propertyOperation = propertyOperation; this.groupTypeOperation = groupTypeOperation; @@ -83,17 +83,18 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation * @param groupUniqueId * @return */ - private Either, TitanOperationStatus> getGroupMembers(String groupUniqueId) { + private Either, JanusGraphOperationStatus> getGroupMembers(String groupUniqueId) { - Either, TitanOperationStatus> result = null; + Either, JanusGraphOperationStatus> result = null; - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.GROUP_MEMBER, + Either>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao + .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.GROUP_MEMBER, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class); if (childrenNodes.isRight()) { - TitanOperationStatus status = childrenNodes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; + JanusGraphOperationStatus status = childrenNodes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.OK; } result = Either.right(status); @@ -119,10 +120,11 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation private Either getGroupTypeOfGroup(String groupUniqueId) { - Either, StorageOperationStatus> groupTypeRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.TYPE_OF, NodeTypeEnum.GroupType, + Either, StorageOperationStatus> groupTypeRes = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.TYPE_OF, NodeTypeEnum.GroupType, GroupTypeData.class) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); if (groupTypeRes.isRight()) { StorageOperationStatus status = groupTypeRes.right().value(); @@ -169,10 +171,11 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation Map uidToPropDefMap = groupTypeProperties.stream().collect(Collectors.toMap(PropertyDefinition::getUniqueId, Function.identity())); // Find all properties values on the group - Either>, StorageOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUid, GraphEdgeLabels.PROPERTY_VALUE, + Either>, StorageOperationStatus> propertyImplNodes = janusGraphGenericDao + .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUid, GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); if (propertyImplNodes.isRight()) { StorageOperationStatus status = propertyImplNodes.right().value(); @@ -197,10 +200,11 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation String propertyValueUid = propertyValueData.getUniqueId(); String value = propertyValueData.getValue(); - Either, StorageOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, GraphEdgeLabels.PROPERTY_IMPL, + Either, StorageOperationStatus> propertyDefRes = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); if (propertyDefRes.isRight()) { StorageOperationStatus status = propertyDefRes.right().value(); if (status == StorageOperationStatus.NOT_FOUND) { @@ -262,9 +266,10 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId); for (GroupDefinition groupDefinition : associatedGroups) { UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId()); - Either deleteRelation = titanGenericDao.deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF) + Either deleteRelation = janusGraphGenericDao + .deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); if (deleteRelation.isRight()) { StorageOperationStatus status = deleteRelation.right().value(); if (status == StorageOperationStatus.NOT_FOUND) { @@ -289,9 +294,10 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation Either result = null; - Either groupRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), uniqueId, GroupData.class) + Either groupRes = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), uniqueId, GroupData.class) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); if (groupRes.isRight()) { StorageOperationStatus status = groupRes.right().value(); log.debug("Failed to retrieve group {} from graph. Status is {}", uniqueId, status); @@ -321,7 +327,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation if (!skipMembers) { Either, StorageOperationStatus> membersRes = getGroupMembers(uniqueId) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); if (membersRes.isRight()) { StorageOperationStatus status = membersRes.right().value(); if (status != StorageOperationStatus.OK) { @@ -351,7 +357,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation if (!skipArtifacts) { Either>, StorageOperationStatus> artifactsRes = getGroupArtifactsPairs(uniqueId) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); if (artifactsRes.isRight()) { StorageOperationStatus status = artifactsRes.right().value(); if (status != StorageOperationStatus.OK) { @@ -384,12 +390,13 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation @Override public boolean isGroupExist(String groupName, boolean inTransaction) { - Either, TitanOperationStatus> eitherGroup = null; + Either, JanusGraphOperationStatus> eitherGroup = null; try { Map properties = new HashMap<>(); properties.put(GraphPropertiesDictionary.NAME.getProperty(), groupName); - eitherGroup = titanGenericDao.getByCriteria(NodeTypeEnum.Group, properties, GroupData.class); + eitherGroup = janusGraphGenericDao + .getByCriteria(NodeTypeEnum.Group, properties, GroupData.class); return eitherGroup.isLeft() && !eitherGroup.left().value().isEmpty(); } finally { @@ -401,10 +408,11 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation List groups = new ArrayList<>(); - Either>, StorageOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId, GraphEdgeLabels.GROUP, NodeTypeEnum.Group, + Either>, StorageOperationStatus> childrenNodes = janusGraphGenericDao + .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId, GraphEdgeLabels.GROUP, NodeTypeEnum.Group, GroupData.class) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); if (childrenNodes.isRight()) { StorageOperationStatus status = childrenNodes.right().value(); @@ -467,9 +475,10 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation for (GroupDefinition groupDefinition : associatedGroups) { UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId()); - Either deleteRelation = titanGenericDao.deleteRelation(groupData, oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF) + Either deleteRelation = janusGraphGenericDao + .deleteRelation(groupData, oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); log.trace("After dissociate group {} from artifact {}" , groupDefinition.getName(), oldArtifactId); if (deleteRelation.isRight()) { StorageOperationStatus status = deleteRelation.right().value(); @@ -479,9 +488,10 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation return status; } - Either createRelation = titanGenericDao.createRelation(groupData, newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props) + Either createRelation = janusGraphGenericDao + .createRelation(groupData, newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); log.trace("After associate group {} to artifact {}" , groupDefinition.getName(), newArtifact.getUniqueIdKey()); if (createRelation.isRight()) { StorageOperationStatus status = createRelation.right().value(); @@ -516,25 +526,26 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation if (result == null || result != StorageOperationStatus.OK) { log.debug("Going to execute rollback on graph."); BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } } - private Either>, TitanOperationStatus> getGroupArtifactsPairs(String groupUniqueId) { + private Either>, JanusGraphOperationStatus> getGroupArtifactsPairs(String groupUniqueId) { - Either>, TitanOperationStatus> result = null; + Either>, JanusGraphOperationStatus> result = null; - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.GROUP_ARTIFACT_REF, + Either>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao + .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; + JanusGraphOperationStatus status = childrenNodes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.OK; } result = Either.right(status); @@ -565,12 +576,12 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation StorageOperationStatus result = null; String innerType = property.getSchema() == null ? null : property.getSchema().getProperty() == null ? null : property.getSchema().getProperty().getType(); - Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); Either isValid = null; if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); + JanusGraphOperationStatus status = allDataTypes.right().value(); log.debug("Failed to fetch data types from cache. Status is {}. ", status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); } if(result == null){ isValid = propertyOperation.validateAndUpdatePropertyValue(property.getType(), property.getValue(), innerType, allDataTypes.left().value()); @@ -591,9 +602,9 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation log.debug("#updateGroupProperties - updating the properties of group {} in component {}", groupId, containerComponent.getUniqueId()); Optional group = containerComponent.getGroupById(groupId); if (group.isPresent()){ - return titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.NoParse) + return janusGraphDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.NoParse) .either(containerVertex -> updateGroupProperties(containerVertex, group.get(), propertiesToUpdate), - DaoStatusConverter::convertTitanStatusToStorageStatus); + DaoStatusConverter::convertJanusGraphStatusToStorageStatus); } else { throw new StorageException(StorageOperationStatus.NOT_FOUND, groupId); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java index 1817868255..430ba59e75 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java @@ -21,7 +21,7 @@ package org.openecomp.sdc.be.model.operations.impl; import com.google.common.base.Strings; -import com.thinkaurelius.titan.graphdb.query.TitanPredicate; +import org.janusgraph.graphdb.query.JanusGraphPredicate; import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; @@ -30,11 +30,11 @@ import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.GroupTypeDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.CapabilityDefinition; @@ -54,7 +54,7 @@ import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; -import static org.openecomp.sdc.be.dao.titan.TitanUtils.buildNotInPredicate; +import static org.openecomp.sdc.be.dao.janusgraph.JanusGraphUtils.buildNotInPredicate; @Component("group-type-operation") public class GroupTypeOperation implements IGroupTypeOperation { @@ -63,19 +63,19 @@ public class GroupTypeOperation implements IGroupTypeOperation { private static final String CREATE_FLOW_CONTEXT = "CreateGroupType"; private final PropertyOperation propertyOperation; - private final TitanGenericDao titanGenericDao; + private final JanusGraphGenericDao janusGraphGenericDao; private final CapabilityTypeOperation capabilityTypeOperation; private final CapabilityOperation capabilityOperation; private final DerivedFromOperation derivedFromOperation; private final OperationUtils operationUtils; - public GroupTypeOperation(TitanGenericDao titanGenericDao, + public GroupTypeOperation(JanusGraphGenericDao janusGraphGenericDao, PropertyOperation propertyOperation, CapabilityTypeOperation capabilityTypeOperation, CapabilityOperation capabilityOperation, DerivedFromOperation derivedFromOperation, OperationUtils operationUtils) { - this.titanGenericDao = titanGenericDao; + this.janusGraphGenericDao = janusGraphGenericDao; this.propertyOperation = propertyOperation; this.capabilityTypeOperation = capabilityTypeOperation; this.capabilityOperation = capabilityOperation; @@ -101,11 +101,11 @@ public class GroupTypeOperation implements IGroupTypeOperation { try { - Either eitherStatus = addGroupTypeToGraph(groupTypeDefinition); + Either eitherStatus = addGroupTypeToGraph(groupTypeDefinition); if (eitherStatus.isRight()) { BeEcompErrorManager.getInstance().logBeFailedCreateNodeError(CREATE_FLOW_CONTEXT, groupTypeDefinition.getType(), eitherStatus.right().value().name()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value())); } else { result = getGroupType(eitherStatus.left().value().getUniqueId(), inTransaction); @@ -114,7 +114,7 @@ public class GroupTypeOperation implements IGroupTypeOperation { return result; } finally { - titanGenericDao.handleTransactionCommitRollback(inTransaction, result); + janusGraphGenericDao.handleTransactionCommitRollback(inTransaction, result); } } @@ -127,16 +127,17 @@ public class GroupTypeOperation implements IGroupTypeOperation { public Either validateUpdateProperties(GroupTypeDefinition groupTypeDefinition) { - TitanOperationStatus error = null; + JanusGraphOperationStatus error = null; if (CollectionUtils.isNotEmpty(groupTypeDefinition.getProperties()) && !Strings.isNullOrEmpty(groupTypeDefinition.getDerivedFrom())) { - Either, TitanOperationStatus> allPropertiesRes = + Either, JanusGraphOperationStatus> allPropertiesRes = getAllGroupTypePropertiesFromAllDerivedFrom(groupTypeDefinition.getDerivedFrom()); - if (allPropertiesRes.isRight() && !allPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + if (allPropertiesRes.isRight() && !allPropertiesRes.right().value().equals( + JanusGraphOperationStatus.NOT_FOUND)) { error = allPropertiesRes.right().value(); log.debug("Couldn't fetch derived from property nodes for group type {}, error: {}", groupTypeDefinition.getType(), error); } if (error == null && !allPropertiesRes.left().value().isEmpty()) { - Either, TitanOperationStatus> validatePropertiesRes = propertyOperation.validatePropertiesUniqueness(allPropertiesRes.left().value(), + Either, JanusGraphOperationStatus> validatePropertiesRes = propertyOperation.validatePropertiesUniqueness(allPropertiesRes.left().value(), groupTypeDefinition.getProperties()); if (validatePropertiesRes.isRight()) { error = validatePropertiesRes.right().value(); @@ -146,11 +147,12 @@ public class GroupTypeOperation implements IGroupTypeOperation { if (error == null) { return Either.left(groupTypeDefinition); } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error)); } - private Either, TitanOperationStatus> getAllGroupTypePropertiesFromAllDerivedFrom(String firstParentType) { - return titanGenericDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), firstParentType, GroupTypeData.class) + private Either, JanusGraphOperationStatus> getAllGroupTypePropertiesFromAllDerivedFrom(String firstParentType) { + return janusGraphGenericDao + .getNode(GraphPropertiesDictionary.TYPE.getProperty(), firstParentType, GroupTypeData.class) .left() .bind(parentGroup -> propertyOperation.getAllTypePropertiesFromAllDerivedFrom(parentGroup.getUniqueId(), NodeTypeEnum.GroupType, GroupTypeData.class)); } @@ -185,8 +187,8 @@ public class GroupTypeOperation implements IGroupTypeOperation { } } - TitanOperationStatus createCapResult = createCapabilities(new GroupTypeData(groupTypeDef), newGroupTypeCapabilities); - return DaoStatusConverter.convertTitanStatusToStorageStatus(createCapResult); + JanusGraphOperationStatus createCapResult = createCapabilities(new GroupTypeData(groupTypeDef), newGroupTypeCapabilities); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createCapResult); } /** @@ -239,9 +241,9 @@ public class GroupTypeOperation implements IGroupTypeOperation { .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue) ): null; } - private TitanOperationStatus createCapabilities(GroupTypeData groupTypeData, Map groupCapabilities) { + private JanusGraphOperationStatus createCapabilities(GroupTypeData groupTypeData, Map groupCapabilities) { if (MapUtils.isEmpty(groupCapabilities)) { - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } return groupCapabilities.values().stream() @@ -249,11 +251,11 @@ public class GroupTypeOperation implements IGroupTypeOperation { .filter(Either::isRight) .findFirst() .map(either -> either.right().value()) - .orElse(TitanOperationStatus.OK); + .orElse(JanusGraphOperationStatus.OK); } - private Either createCapability(GroupTypeData groupTypeData, CapabilityDefinition capabilityDef) { - Either eitherCapData = capabilityTypeOperation.getCapabilityTypeByType(capabilityDef.getType()); + private Either createCapability(GroupTypeData groupTypeData, CapabilityDefinition capabilityDef) { + Either eitherCapData = capabilityTypeOperation.getCapabilityTypeByType(capabilityDef.getType()); return eitherCapData .left() .map(CapabilityTypeData::new) @@ -270,15 +272,15 @@ public class GroupTypeOperation implements IGroupTypeOperation { * @return */ private Either, StorageOperationStatus> getCapablities(String groupTypeId) { - Either>, TitanOperationStatus> groupCapabilitiesOnGraph = - titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), groupTypeId, GraphEdgeLabels.GROUP_TYPE_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class, true); + Either>, JanusGraphOperationStatus> groupCapabilitiesOnGraph = + janusGraphGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), groupTypeId, GraphEdgeLabels.GROUP_TYPE_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class, true); if (groupCapabilitiesOnGraph.isRight()) { - TitanOperationStatus capabilityStatus = groupCapabilitiesOnGraph.right().value(); - if (capabilityStatus == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus capabilityStatus = groupCapabilitiesOnGraph.right().value(); + if (capabilityStatus == JanusGraphOperationStatus.NOT_FOUND) { return Either.left(Collections.emptyList()); } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(capabilityStatus)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(capabilityStatus)); } List> groupCapabilites = groupCapabilitiesOnGraph.left().value(); @@ -286,26 +288,27 @@ public class GroupTypeOperation implements IGroupTypeOperation { return capabilityOperation.getCapabilitiesWithProps(groupCapabilites) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); } private void fillCapabilityName(ImmutablePair pair) { pair.getLeft().getCapabilityDataDefinition().setName((String)pair.getRight().getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty())); } - private Either connectToCapability(GroupTypeData groupTypeData, CapabilityData capabilityData, String capabilityName) { + private Either connectToCapability(GroupTypeData groupTypeData, CapabilityData capabilityData, String capabilityName) { Map properties = new HashMap<>(); properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capabilityName); - return titanGenericDao.createRelation(groupTypeData, capabilityData, GraphEdgeLabels.GROUP_TYPE_CAPABILITY, properties); + return janusGraphGenericDao.createRelation(groupTypeData, capabilityData, GraphEdgeLabels.GROUP_TYPE_CAPABILITY, properties); } public List getAllGroupTypes(Set excludedGroupTypes) { - Map> predicateCriteria = buildNotInPredicate(GraphPropertiesDictionary.TYPE.getProperty(), excludedGroupTypes); - List groupTypes = titanGenericDao.getByCriteriaWithPredicate(NodeTypeEnum.GroupType, predicateCriteria, GroupTypeData.class) + Map> predicateCriteria = buildNotInPredicate(GraphPropertiesDictionary.TYPE.getProperty(), excludedGroupTypes); + List groupTypes = janusGraphGenericDao + .getByCriteriaWithPredicate(NodeTypeEnum.GroupType, predicateCriteria, GroupTypeData.class) .left() - .on(operationUtils::onTitanOperationFailure); + .on(operationUtils::onJanusGraphOperationFailure); return convertGroupTypesToDefinition(groupTypes); } @@ -319,9 +322,10 @@ public class GroupTypeOperation implements IGroupTypeOperation { public Either getGroupTypeByUid(String uniqueId) { log.debug("#getGroupTypeByUid - fetching group type with id {}", uniqueId); - return titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), uniqueId, GroupTypeData.class) + return janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), uniqueId, GroupTypeData.class) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus) + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus) .left() .bind(groupType -> buildGroupTypeDefinition(uniqueId, groupType)); } @@ -346,7 +350,7 @@ public class GroupTypeOperation implements IGroupTypeOperation { return result; } finally { - titanGenericDao.handleTransactionCommitRollback(inTransaction, result); + janusGraphGenericDao.handleTransactionCommitRollback(inTransaction, result); } } @@ -375,9 +379,10 @@ public class GroupTypeOperation implements IGroupTypeOperation { return result; } - Either, StorageOperationStatus> groupTypeEither = titanGenericDao.getByCriteria(NodeTypeEnum.GroupType, properties, GroupTypeData.class) + Either, StorageOperationStatus> groupTypeEither = janusGraphGenericDao + .getByCriteria(NodeTypeEnum.GroupType, properties, GroupTypeData.class) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); if (groupTypeEither.isRight()) { result = Either.right(groupTypeEither.right().value()); } else { @@ -391,7 +396,7 @@ public class GroupTypeOperation implements IGroupTypeOperation { return result; } finally { - titanGenericDao.handleTransactionCommitRollback(inTransaction, result); + janusGraphGenericDao.handleTransactionCommitRollback(inTransaction, result); } } @@ -432,11 +437,11 @@ public class GroupTypeOperation implements IGroupTypeOperation { .bind(propsMap -> fillDerivedFromProperties(groupType, derivedFromNode, new ArrayList<>(propsMap.values()))); } - Either, StorageOperationStatus> handleGroupTypeHasNoProperties(TitanOperationStatus err) { - if (err == TitanOperationStatus.NOT_FOUND) { + Either, StorageOperationStatus> handleGroupTypeHasNoProperties(JanusGraphOperationStatus err) { + if (err == JanusGraphOperationStatus.NOT_FOUND) { return Either.left(new HashMap<>()); } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(err)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(err)); } private Either, StorageOperationStatus> fillDerivedFromProperties(GroupTypeDefinition groupType, GroupTypeData derivedFromNode, List groupTypeDirectProperties) { @@ -493,7 +498,7 @@ public class GroupTypeOperation implements IGroupTypeOperation { * @param groupTypeDefinition * @return */ - private Either addGroupTypeToGraph(GroupTypeDefinition groupTypeDefinition) { + private Either addGroupTypeToGraph(GroupTypeDefinition groupTypeDefinition) { log.debug("Got group type {}", groupTypeDefinition); @@ -503,18 +508,19 @@ public class GroupTypeOperation implements IGroupTypeOperation { log.debug("Before adding group type to graph. groupTypeData = {}", groupTypeData); - Either createGTResult = titanGenericDao.createNode(groupTypeData, GroupTypeData.class); + Either createGTResult = janusGraphGenericDao + .createNode(groupTypeData, GroupTypeData.class); log.debug("After adding group type to graph. status is = {}", createGTResult); if (createGTResult.isRight()) { - TitanOperationStatus operationStatus = createGTResult.right().value(); + JanusGraphOperationStatus operationStatus = createGTResult.right().value(); log.error("Failed to add group type {} to graph. status is {}", groupTypeDefinition.getType(), operationStatus); return Either.right(operationStatus); } GroupTypeData resultCTD = createGTResult.left().value(); List properties = groupTypeDefinition.getProperties(); - Either, TitanOperationStatus> addPropertiesToCapablityType = propertyOperation.addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.GroupType, properties); + Either, JanusGraphOperationStatus> addPropertiesToCapablityType = propertyOperation.addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.GroupType, properties); if (addPropertiesToCapablityType.isRight()) { log.error("Failed add properties {} to capability {}", properties, groupTypeDefinition.getType()); return Either.right(addPropertiesToCapablityType.right().value()); @@ -522,7 +528,7 @@ public class GroupTypeOperation implements IGroupTypeOperation { String derivedFrom = groupTypeDefinition.getDerivedFrom(); if (derivedFrom != null) { - Either createRelation = connectToDerivedFrom(ctUniqueId, derivedFrom); + Either createRelation = connectToDerivedFrom(ctUniqueId, derivedFrom); if (createRelation.isRight()) { return Either.right(createRelation.right().value()); } @@ -530,8 +536,8 @@ public class GroupTypeOperation implements IGroupTypeOperation { Map groupCapTypes = groupTypeDefinition.getCapabilities(); if (!MapUtils.isEmpty(groupCapTypes)) { - TitanOperationStatus status = createCapabilities(groupTypeData, groupCapTypes); - if (status != TitanOperationStatus.OK) { + JanusGraphOperationStatus status = createCapabilities(groupTypeData, groupCapTypes); + if (status != JanusGraphOperationStatus.OK) { return Either.right(status); } } @@ -541,21 +547,23 @@ public class GroupTypeOperation implements IGroupTypeOperation { } - private Either connectToDerivedFrom(String ctUniqueId, String derivedFrom) { + private Either connectToDerivedFrom(String ctUniqueId, String derivedFrom) { log.debug("Before creating relation between Group Type with id {} to its parent {}", ctUniqueId, derivedFrom); - Either derivedFromGroupTypeResult = - titanGenericDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), derivedFrom, GroupTypeData.class); + Either derivedFromGroupTypeResult = + janusGraphGenericDao + .getNode(GraphPropertiesDictionary.TYPE.getProperty(), derivedFrom, GroupTypeData.class); if (derivedFromGroupTypeResult.isLeft()) { UniqueIdData from = new UniqueIdData(NodeTypeEnum.GroupType, ctUniqueId); GroupTypeData to = derivedFromGroupTypeResult.left().value(); - Either createRelation = titanGenericDao.createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null); + Either createRelation = janusGraphGenericDao + .createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null); log.debug("After create relation between Group Type with id {} to its parent {}, status is {}.", ctUniqueId, derivedFrom, createRelation); return createRelation; } else { - TitanOperationStatus status = derivedFromGroupTypeResult.right().value(); + JanusGraphOperationStatus status = derivedFromGroupTypeResult.right().value(); log.debug("Failed to found parent Group Type {}, stauts is {}.", derivedFrom, status); return Either.right(status); } @@ -579,23 +587,29 @@ public class GroupTypeOperation implements IGroupTypeOperation { public Either isCapabilityTypeDerivedFrom(String childCandidateType, String parentCandidateType) { Map propertiesToMatch = new HashMap<>(); propertiesToMatch.put(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childCandidateType); - Either, TitanOperationStatus> getResponse = titanGenericDao.getByCriteria(NodeTypeEnum.CapabilityType, propertiesToMatch, CapabilityTypeData.class); + Either, JanusGraphOperationStatus> getResponse = janusGraphGenericDao + .getByCriteria(NodeTypeEnum.CapabilityType, propertiesToMatch, CapabilityTypeData.class); if (getResponse.isRight()) { - TitanOperationStatus titanOperationStatus = getResponse.right().value(); - log.debug("Couldn't fetch capability type {}, error: {}", childCandidateType, titanOperationStatus); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); + JanusGraphOperationStatus janusGraphOperationStatus = getResponse.right().value(); + log.debug("Couldn't fetch capability type {}, error: {}", childCandidateType, + janusGraphOperationStatus); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + janusGraphOperationStatus)); } String childUniqueId = getResponse.left().value().get(0).getUniqueId(); Set travelledTypes = new HashSet<>(); do { travelledTypes.add(childUniqueId); - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childUniqueId, GraphEdgeLabels.DERIVED_FROM, + Either>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao + .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childUniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.CapabilityType, CapabilityTypeData.class); if (childrenNodes.isRight()) { - if (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND) { - TitanOperationStatus titanOperationStatus = getResponse.right().value(); - log.debug("Couldn't fetch derived from node for capability type {}, error: {}", childCandidateType, titanOperationStatus); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); + if (childrenNodes.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus janusGraphOperationStatus = getResponse.right().value(); + log.debug("Couldn't fetch derived from node for capability type {}, error: {}", childCandidateType, + janusGraphOperationStatus); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + janusGraphOperationStatus)); } else { log.debug("Derived from node is not found for type {} - this is OK for root capability.", childCandidateType); return Either.left(false); @@ -627,9 +641,9 @@ public class GroupTypeOperation implements IGroupTypeOperation { private Either updateGroupTypeOnGraph(GroupTypeDefinition updatedGroupType, GroupTypeDefinition currGroupType) { updateGroupTypeData(updatedGroupType, currGroupType); - return titanGenericDao.updateNode(new GroupTypeData(updatedGroupType), GroupTypeData.class) + return janusGraphGenericDao.updateNode(new GroupTypeData(updatedGroupType), GroupTypeData.class) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus) + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus) .left() .bind(updatedNode -> updateGroupProperties(updatedGroupType.getUniqueId(), updatedGroupType.getProperties())) .left() @@ -649,7 +663,7 @@ public class GroupTypeOperation implements IGroupTypeOperation { .collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())): null; return propertyOperation.mergePropertiesAssociatedToNode(NodeTypeEnum.GroupType, groupId, mapProperties) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java index 6d050afb2c..823c33a311 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java @@ -25,10 +25,10 @@ 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.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; 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.HeatParameterDefinition; import org.openecomp.sdc.be.model.heat.HeatParameterType; @@ -55,27 +55,28 @@ public class HeatParametersOperation implements IHeatParametersOperation { private static final Logger log = Logger.getLogger(HeatParametersOperation.class.getName()); @javax.annotation.Resource - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; - public TitanGenericDao getTitanGenericDao() { - return titanGenericDao; + public JanusGraphGenericDao getJanusGraphGenericDao() { + return janusGraphGenericDao; } - public void setTitanGenericDao(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; + public void setJanusGraphGenericDao(JanusGraphGenericDao janusGraphGenericDao) { + this.janusGraphGenericDao = janusGraphGenericDao; } public StorageOperationStatus getHeatParametersOfNode(NodeTypeEnum nodeType, String uniqueId, List properties) { - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.HEAT_PARAMETER, NodeTypeEnum.HeatParameter, + Either>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao + .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.HEAT_PARAMETER, NodeTypeEnum.HeatParameter, HeatParameterData.class); if (childrenNodes.isRight()) { - TitanOperationStatus status = childrenNodes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; + JanusGraphOperationStatus status = childrenNodes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.OK; } - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); } List> values = childrenNodes.left().value(); @@ -103,15 +104,16 @@ public class HeatParametersOperation implements IHeatParametersOperation { public StorageOperationStatus getParametersValueNodes(NodeTypeEnum parentNodeType, String parentUniqueId, List heatValues) { - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentUniqueId, GraphEdgeLabels.PARAMETER_VALUE, + Either>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao + .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentUniqueId, GraphEdgeLabels.PARAMETER_VALUE, NodeTypeEnum.HeatParameterValue, HeatParameterValueData.class); if (childrenNodes.isRight()) { - TitanOperationStatus status = childrenNodes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; + JanusGraphOperationStatus status = childrenNodes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.OK; } - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); } List> values = childrenNodes.left().value(); @@ -144,14 +146,14 @@ public class HeatParametersOperation implements IHeatParametersOperation { for (HeatParameterDefinition propertyDefinition : heatParams) { String propertyUid = propertyDefinition.getUniqueId(); - Either deletePropertyRes = deleteHeatParameterFromGraph(propertyUid); + Either deletePropertyRes = deleteHeatParameterFromGraph(propertyUid); if (deletePropertyRes.isRight()) { log.error("Failed to delete heat parameter with id {}", propertyUid); - TitanOperationStatus status = deletePropertyRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; + JanusGraphOperationStatus status = deletePropertyRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } } @@ -173,14 +175,14 @@ public class HeatParametersOperation implements IHeatParametersOperation { for (HeatParameterValueData propertyDefinition : heatValues) { String propertyUid = (String) propertyDefinition.getUniqueId(); - Either deletePropertyRes = deleteHeatParameterValueFromGraph(propertyUid); + Either deletePropertyRes = deleteHeatParameterValueFromGraph(propertyUid); if (deletePropertyRes.isRight()) { log.error("Failed to delete heat parameter value with id {}", propertyUid); - TitanOperationStatus status = deletePropertyRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; + JanusGraphOperationStatus status = deletePropertyRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); } } @@ -189,14 +191,15 @@ public class HeatParametersOperation implements IHeatParametersOperation { return StorageOperationStatus.OK; } - private Either deleteHeatParameterFromGraph(String propertyId) { + private Either deleteHeatParameterFromGraph(String propertyId) { log.debug("Before deleting heat parameter from graph {}" , propertyId); - return titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameter), propertyId, HeatParameterData.class); + return janusGraphGenericDao + .deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameter), propertyId, HeatParameterData.class); } - private Either deleteHeatParameterValueFromGraph(String propertyId) { + private Either deleteHeatParameterValueFromGraph(String propertyId) { log.debug("Before deleting heat parameter from graph {}" , propertyId); - return titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameterValue), propertyId, HeatParameterValueData.class); + return janusGraphGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameterValue), propertyId, HeatParameterValueData.class); } @Override @@ -207,10 +210,10 @@ public class HeatParametersOperation implements IHeatParametersOperation { String propertyName = propertyDefinition.getName(); - Either addPropertyToGraph = addPropertyToGraph(propertyName, propertyDefinition, parentId, nodeType); + Either addPropertyToGraph = addPropertyToGraph(propertyName, propertyDefinition, parentId, nodeType); if (addPropertyToGraph.isRight()) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyToGraph.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertyToGraph.right().value()); } } } @@ -228,17 +231,18 @@ public class HeatParametersOperation implements IHeatParametersOperation { for (HeatParameterDefinition property : properties) { HeatParameterData heatParameterData = new HeatParameterData(property); - Either updateNode = titanGenericDao.updateNode(heatParameterData, HeatParameterData.class); + Either updateNode = janusGraphGenericDao + .updateNode(heatParameterData, HeatParameterData.class); if (updateNode.isRight()) { log.debug("failed to update heat parameter in graph. id = {}", property.getUniqueId()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateNode.right().value()); } } return StorageOperationStatus.OK; } - public Either addPropertyToGraph(String propertyName, HeatParameterDefinition propertyDefinition, String parentId, NodeTypeEnum nodeType) { + public Either addPropertyToGraph(String propertyName, HeatParameterDefinition propertyDefinition, String parentId, NodeTypeEnum nodeType) { UniqueIdData parentNode = new UniqueIdData(nodeType, parentId); @@ -246,19 +250,21 @@ public class HeatParametersOperation implements IHeatParametersOperation { HeatParameterData propertyData = new HeatParameterData(propertyDefinition); log.debug("Before adding property to graph {}" , propertyData); - Either createNodeResult = titanGenericDao.createNode(propertyData, HeatParameterData.class); + Either createNodeResult = janusGraphGenericDao + .createNode(propertyData, HeatParameterData.class); log.debug("After adding property to graph {}" , propertyData); if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus); return Either.right(operationStatus); } Map props = new HashMap<>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName); - Either createRelResult = titanGenericDao.createRelation(parentNode, propertyData, GraphEdgeLabels.HEAT_PARAMETER, props); + Either createRelResult = janusGraphGenericDao + .createRelation(parentNode, propertyData, GraphEdgeLabels.HEAT_PARAMETER, props); if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); + JanusGraphOperationStatus operationStatus = createRelResult.right().value(); log.error("Failed to associate {} {} to heat parameter {} in graph. status is {}", nodeType.getName(), parentId, propertyName, operationStatus); return Either.right(operationStatus); } @@ -371,7 +377,8 @@ public class HeatParametersOperation implements IHeatParametersOperation { @Override public Either updateHeatParameterValue(HeatParameterDefinition heatParam, String artifactId, String resourceInstanceId, String artifactLabel) { String heatEnvId = UniqueIdBuilder.buildHeatParameterValueUniqueId(resourceInstanceId, artifactLabel, heatParam.getName()); - Either getNode = titanGenericDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatEnvId, HeatParameterValueData.class); + Either getNode = janusGraphGenericDao + .getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatEnvId, HeatParameterValueData.class); if (getNode.isRight() || getNode.left().value() == null) { if (heatParam.getCurrentValue() == null || (heatParam.getDefaultValue() != null && heatParam.getCurrentValue().equals(heatParam.getDefaultValue()))) { log.debug("Updated heat parameter value equals default value. No need to create heat parameter value for heat parameter {}", heatParam.getUniqueId()); @@ -388,15 +395,17 @@ public class HeatParametersOperation implements IHeatParametersOperation { HeatParameterValueData heatParameterValue = new HeatParameterValueData(); heatParameterValue.setUniqueId(heatParam.getUniqueId()); if (heatParam.getCurrentValue() == null || (heatParam.getDefaultValue() != null && heatParam.getCurrentValue().equals(heatParam.getDefaultValue()))) { - Either deleteParameterValueIncomingRelation = titanGenericDao.deleteIncomingRelationByCriteria(heatParameterValue, GraphEdgeLabels.PARAMETER_VALUE, null); + Either deleteParameterValueIncomingRelation = janusGraphGenericDao + .deleteIncomingRelationByCriteria(heatParameterValue, GraphEdgeLabels.PARAMETER_VALUE, null); if (deleteParameterValueIncomingRelation.isRight()) { log.debug("Failed to delete heat parameter value incoming relation on graph. id = {}", heatParameterValue.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteParameterValueIncomingRelation.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(deleteParameterValueIncomingRelation.right().value())); } - Either getOutgoingRelation = titanGenericDao.getOutgoingEdgeByCriteria(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) heatParameterValue.getUniqueId(), GraphEdgeLabels.PARAMETER_IMPL, null); + Either getOutgoingRelation = janusGraphGenericDao + .getOutgoingEdgeByCriteria(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) heatParameterValue.getUniqueId(), GraphEdgeLabels.PARAMETER_IMPL, null); if (getOutgoingRelation.isRight()) { log.debug("Failed to get heat parameter value outgoing relation from graph. id = {}", heatParameterValue.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getOutgoingRelation.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getOutgoingRelation.right().value())); } Edge edge = getOutgoingRelation.left().value(); if (edge == null) { @@ -405,33 +414,35 @@ public class HeatParametersOperation implements IHeatParametersOperation { } edge.remove(); - Either deleteNode = titanGenericDao.deleteNode(heatParameterValue, HeatParameterValueData.class); + Either deleteNode = janusGraphGenericDao + .deleteNode(heatParameterValue, HeatParameterValueData.class); if (deleteNode.isRight()) { log.debug("Failed to delete heat parameter value on graph. id = {}", heatParameterValue.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteNode.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(deleteNode.right().value())); } return Either.left(deleteNode.left().value()); } heatParameterValue.setValue(heatParam.getCurrentValue()); - Either updateNode = titanGenericDao.updateNode(heatParameterValue, HeatParameterValueData.class); + Either updateNode = janusGraphGenericDao + .updateNode(heatParameterValue, HeatParameterValueData.class); if (updateNode.isRight()) { log.debug("Failed to update heat parameter value in graph. id = {}", heatParameterValue.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateNode.right().value())); } return Either.left(updateNode.left().value()); } public Either createHeatParameterValue(HeatParameterDefinition heatParam, String artifactId, String resourceInstanceId, String artifactLabel) { - Either addHeatValueToGraph = addHeatValueToGraph(heatParam, artifactLabel, artifactId, resourceInstanceId); + Either addHeatValueToGraph = addHeatValueToGraph(heatParam, artifactLabel, artifactId, resourceInstanceId); if (addHeatValueToGraph.isRight()) { log.debug("Failed to create heat parameters value on graph for artifact {}", artifactId); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addHeatValueToGraph.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addHeatValueToGraph.right().value())); } return Either.left(addHeatValueToGraph.left().value()); } - public Either addHeatValueToGraph(HeatParameterDefinition heatParameter, String artifactLabel, String artifactId, String resourceInstanceId) { + public Either addHeatValueToGraph(HeatParameterDefinition heatParameter, String artifactLabel, String artifactId, String resourceInstanceId) { UniqueIdData heatEnvNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId); HeatParameterValueData heatValueData = new HeatParameterValueData(); @@ -439,26 +450,29 @@ public class HeatParametersOperation implements IHeatParametersOperation { heatValueData.setValue(heatParameter.getCurrentValue()); log.debug("Before adding property to graph {}", heatValueData); - Either createNodeResult = titanGenericDao.createNode(heatValueData, HeatParameterValueData.class); + Either createNodeResult = janusGraphGenericDao + .createNode(heatValueData, HeatParameterValueData.class); log.debug("After adding property to graph {}", heatValueData); if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); log.error("Failed to add heat value {} to graph. status is {}", heatValueData.getUniqueId(), operationStatus); return Either.right(operationStatus); } Map props = new HashMap<>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), heatParameter.getName()); - Either createRelResult = titanGenericDao.createRelation(heatEnvNode, heatValueData, GraphEdgeLabels.PARAMETER_VALUE, props); + Either createRelResult = janusGraphGenericDao + .createRelation(heatEnvNode, heatValueData, GraphEdgeLabels.PARAMETER_VALUE, props); if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); + JanusGraphOperationStatus operationStatus = createRelResult.right().value(); log.error("Failed to associate heat value {} to heat env artifact {} in graph. status is {}", heatValueData.getUniqueId(), artifactId, operationStatus); return Either.right(operationStatus); } UniqueIdData heatParameterNode = new UniqueIdData(NodeTypeEnum.HeatParameter, heatParameter.getUniqueId()); - Either createRel2Result = titanGenericDao.createRelation(heatValueData, heatParameterNode, GraphEdgeLabels.PARAMETER_IMPL, null); + Either createRel2Result = janusGraphGenericDao + .createRelation(heatValueData, heatParameterNode, GraphEdgeLabels.PARAMETER_IMPL, null); if (createRel2Result.isRight()) { - TitanOperationStatus operationStatus = createRel2Result.right().value(); + JanusGraphOperationStatus operationStatus = createRel2Result.right().value(); log.error("Failed to associate heat value {} to heat parameter {} in graph. status is {}", heatValueData.getUniqueId(), heatParameter.getName(), operationStatus); return Either.right(operationStatus); } 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 9c5445a8c2..b9a4c7f66f 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 @@ -26,10 +26,10 @@ import org.apache.tinkerpop.gremlin.structure.Edge; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.operations.api.IInputsOperation; @@ -48,20 +48,22 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati @Autowired PropertyOperation propertyOperation; - public TitanOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List elements, NodeElementFetcher singleNodeFetcher) { + public JanusGraphOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List elements, NodeElementFetcher singleNodeFetcher) { log.trace("Going to fetch elements under resource {}" , resourceId); - TitanOperationStatus resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements); + JanusGraphOperationStatus + resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements); - if (resourceAttributesStatus != TitanOperationStatus.OK) { + if (resourceAttributesStatus != JanusGraphOperationStatus.OK) { return resourceAttributesStatus; } - Either, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class); + Either, JanusGraphOperationStatus> parentNodes = janusGraphGenericDao + .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) { + JanusGraphOperationStatus parentNodesStatus = parentNodes.right().value(); + if (parentNodesStatus != JanusGraphOperationStatus.NOT_FOUND) { BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find parent elements of resource " + resourceId + ". status is " + parentNodesStatus, ErrorSeverity.ERROR); return parentNodesStatus; } @@ -70,26 +72,26 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati if (parentNodes.isLeft()) { ImmutablePair parnetNodePair = parentNodes.left().value(); String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - TitanOperationStatus addParentIntStatus = findAllResourceElementsDefinitionRecursively(parentUniqueId, elements, singleNodeFetcher); + JanusGraphOperationStatus addParentIntStatus = findAllResourceElementsDefinitionRecursively(parentUniqueId, elements, singleNodeFetcher); - if (addParentIntStatus != TitanOperationStatus.OK) { + if (addParentIntStatus != JanusGraphOperationStatus.OK) { BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find all resource elements of resource " + parentUniqueId, ErrorSeverity.ERROR); return addParentIntStatus; } } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } @Override - public ImmutablePair findInputValue(String resourceInstanceId, String propertyId) { + public ImmutablePair findInputValue(String resourceInstanceId, String propertyId) { log.debug("Going to check whether the property {} already added to resource instance {}", propertyId, resourceInstanceId); - Either, TitanOperationStatus> getAllRes = getAllInputsOfResourceInstanceOnlyInputDefId(resourceInstanceId); + Either, JanusGraphOperationStatus> getAllRes = getAllInputsOfResourceInstanceOnlyInputDefId(resourceInstanceId); if (getAllRes.isRight()) { - TitanOperationStatus status = getAllRes.right().value(); + JanusGraphOperationStatus status = getAllRes.right().value(); log.trace("After fetching all properties of resource instance {}. Status is {}" ,resourceInstanceId, status); return new ImmutablePair<>(status, null); } @@ -102,12 +104,12 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati log.trace("Go over property {} under resource instance {}. valueUniqueId = {}" ,propertyUniqueId, resourceInstanceId, valueUniqueUid); if (propertyId.equals(propertyUniqueId) && valueUniqueUid != null) { log.debug("The property {} already created under resource instance {}", propertyId, resourceInstanceId); - return new ImmutablePair<>(TitanOperationStatus.ALREADY_EXIST, valueUniqueUid); + return new ImmutablePair<>(JanusGraphOperationStatus.ALREADY_EXIST, valueUniqueUid); } } } - return new ImmutablePair<>(TitanOperationStatus.NOT_FOUND, null); + return new ImmutablePair<>(JanusGraphOperationStatus.NOT_FOUND, null); } /** @@ -116,34 +118,36 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati * @param resourceInstanceUid * @return */ - public Either, TitanOperationStatus> getAllInputsOfResourceInstanceOnlyInputDefId(String resourceInstanceUid) { + public Either, JanusGraphOperationStatus> getAllInputsOfResourceInstanceOnlyInputDefId(String resourceInstanceUid) { return getAllInputsOfResourceInstanceOnlyInputDefId(resourceInstanceUid, NodeTypeEnum.ResourceInstance); } - public Either, TitanOperationStatus> getAllInputsOfResourceInstanceOnlyInputDefId(String resourceInstanceUid, NodeTypeEnum instanceNodeType) { + public Either, JanusGraphOperationStatus> getAllInputsOfResourceInstanceOnlyInputDefId(String resourceInstanceUid, NodeTypeEnum instanceNodeType) { - Either findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, ComponentInstanceData.class); + Either findResInstanceRes = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, ComponentInstanceData.class); if (findResInstanceRes.isRight()) { - TitanOperationStatus status = findResInstanceRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; + JanusGraphOperationStatus status = findResInstanceRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } return Either.right(status); } - Either>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, GraphEdgeLabels.INPUT_VALUE, NodeTypeEnum.InputValue, InputValueData.class); + Either>, JanusGraphOperationStatus> propertyImplNodes = janusGraphGenericDao + .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, GraphEdgeLabels.INPUT_VALUE, NodeTypeEnum.InputValue, InputValueData.class); if (propertyImplNodes.isRight()) { - TitanOperationStatus status = propertyImplNodes.right().value(); + JanusGraphOperationStatus status = propertyImplNodes.right().value(); return Either.right(status); } List> list = propertyImplNodes.left().value(); if (list == null || list.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); + return Either.right(JanusGraphOperationStatus.NOT_FOUND); } List result = new ArrayList<>(); @@ -155,7 +159,8 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati String propertyValueUid = propertyValueData.getUniqueId(); String value = propertyValueData.getValue(); - Either, TitanOperationStatus> inputNodes = titanGenericDao.getParentNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), propertyValueData.getUniqueId(), GraphEdgeLabels.GET_INPUT, NodeTypeEnum.Input, InputsData.class); + Either, JanusGraphOperationStatus> inputNodes = janusGraphGenericDao + .getParentNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), propertyValueData.getUniqueId(), GraphEdgeLabels.GET_INPUT, NodeTypeEnum.Input, InputsData.class); if (inputNodes.isRight()) { @@ -165,25 +170,28 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati InputsData input = inputNodes.left().value().left; String inputId = input.getPropertyDataDefinition().getUniqueId(); - Either, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InputValue), propertyValueUid, GraphEdgeLabels.INPUT_IMPL, NodeTypeEnum.Property, PropertyData.class); + Either, JanusGraphOperationStatus> propertyDefRes = janusGraphGenericDao + .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; + JanusGraphOperationStatus status = propertyDefRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } return Either.right(status); } ImmutablePair propertyDefPair = propertyDefRes.left().value(); PropertyData propertyData = propertyDefPair.left; - Either inputsEges = titanGenericDao.getIncomingEdgeByCriteria(propertyData, GraphEdgeLabels.INPUT, null); + Either inputsEges = janusGraphGenericDao + .getIncomingEdgeByCriteria(propertyData, GraphEdgeLabels.INPUT, null); if (inputsEges.isRight()) { - TitanOperationStatus status = inputsEges.right().value(); + JanusGraphOperationStatus status = inputsEges.right().value(); return Either.right(status); } Edge edge = inputsEges.left().value(); - String inputName = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.NAME.getProperty()); + String inputName = (String) janusGraphGenericDao + .getProperty(edge, GraphEdgePropertiesDictionary.NAME.getProperty()); ComponentInstanceInput resourceInstanceProperty = new ComponentInstanceInput(propertyData.getPropertyDataDefinition(), inputId, value, propertyValueUid); 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 ab2eb0323d..b9e95c507f 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 @@ -24,10 +24,10 @@ import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; 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.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -63,7 +63,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation private ArtifactOperation artifactOperation; @javax.annotation.Resource - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; @Override public Either addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean inTransaction) { @@ -72,27 +72,29 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } - private Either addOperationToGraph(InterfaceDefinition interf, String opName, Operation op, InterfaceData interfaceData) { + private Either addOperationToGraph(InterfaceDefinition interf, String opName, Operation op, InterfaceData interfaceData) { op.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId((String) interfaceData.getUniqueId(), opName)); OperationData operationData = new OperationData(op); log.debug("Before adding operation to graph {}", operationData); - Either createOpNodeResult = titanGenericDao.createNode(operationData, OperationData.class); + Either createOpNodeResult = janusGraphGenericDao + .createNode(operationData, OperationData.class); log.debug("After adding operation to graph {}", operationData); if (createOpNodeResult.isRight()) { - TitanOperationStatus opStatus = createOpNodeResult.right().value(); + JanusGraphOperationStatus 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); - Either createRelResult = titanGenericDao.createRelation(interfaceData, operationData, GraphEdgeLabels.INTERFACE_OPERATION, props); + Either createRelResult = janusGraphGenericDao + .createRelation(interfaceData, operationData, GraphEdgeLabels.INTERFACE_OPERATION, props); if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createOpNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createOpNodeResult.right().value(); log.error("Failed to associate operation {} to property {} in graph. status is {}", interfaceData.getUniqueId(), opName, operationStatus); return Either.right(operationStatus); @@ -118,7 +120,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } - private Either addInterfaceToGraph(InterfaceDefinition interfaceInfo, String interfaceName, String resourceId) { + private Either addInterfaceToGraph(InterfaceDefinition interfaceInfo, String interfaceName, String resourceId) { InterfaceData interfaceData = new InterfaceData(interfaceInfo); @@ -129,33 +131,36 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation interfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted)); - Either existInterface = titanGenericDao.getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class); + Either existInterface = janusGraphGenericDao + .getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class); if (existInterface.isRight()) { return createInterfaceNodeAndRelation(interfaceNameSplitted, resourceId, interfaceData, resourceData); } else { log.debug("Interface {} already exist", interfaceData.getUniqueId()); - return Either.right(TitanOperationStatus.ALREADY_EXIST); + return Either.right(JanusGraphOperationStatus.ALREADY_EXIST); } } - private Either createInterfaceNodeAndRelation(String interfaceName, String resourceId, InterfaceData interfaceData, ResourceMetadataData resourceData) { + 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); + Either createNodeResult = janusGraphGenericDao + .createNode(interfaceData, InterfaceData.class); log.debug("After adding property to graph {}", interfaceData); if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); log.error("Failed to add interface {} to graph. status is {}", interfaceName, operationStatus); return Either.right(operationStatus); } Map props = new HashMap<>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), interfaceName); - Either createRelResult = titanGenericDao.createRelation(resourceData, interfaceData, GraphEdgeLabels.INTERFACE, props); + Either createRelResult = janusGraphGenericDao + .createRelation(resourceData, interfaceData, GraphEdgeLabels.INTERFACE, props); if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); log.error("Failed to associate resource {} to property {} in graph. status is {}", resourceId, interfaceName, operationStatus); return Either.right(operationStatus); @@ -164,22 +169,24 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation return Either.left(createNodeResult.left().value()); } - private Either createOperationNodeAndRelation(String operationName, OperationData operationData, InterfaceData interfaceData) { + private Either createOperationNodeAndRelation(String operationName, OperationData operationData, InterfaceData interfaceData) { log.debug("Before adding operation to graph {}", operationData); - Either createNodeResult = titanGenericDao.createNode(operationData, OperationData.class); + Either createNodeResult = janusGraphGenericDao + .createNode(operationData, OperationData.class); log.debug("After adding operation to graph {}", interfaceData); if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); log.error("Failed to add interfoperationce {} to graph. status is {}", operationName, operationStatus); return Either.right(operationStatus); } Map props = new HashMap<>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), operationName); - Either createRelResult = titanGenericDao.createRelation(interfaceData, operationData, GraphEdgeLabels.INTERFACE_OPERATION, props); + Either createRelResult = janusGraphGenericDao + .createRelation(interfaceData, operationData, GraphEdgeLabels.INTERFACE_OPERATION, props); if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); log.error("Failed to associate operation {} to interface {} in graph. status is {}", operationName, interfaceData.getUniqueId(), operationStatus); return Either.right(operationStatus); @@ -205,15 +212,15 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation return result; } - TitanOperationStatus findInterfacesRes = TitanOperationStatus.GENERAL_ERROR; + JanusGraphOperationStatus findInterfacesRes = JanusGraphOperationStatus.GENERAL_ERROR; if (recursively) { findInterfacesRes = findAllInterfacesRecursively(resourceId, interfaces); } else { findInterfacesRes = findAllInterfacesNotRecursively(resourceId, interfaces); } - if (!findInterfacesRes.equals(TitanOperationStatus.OK)) { + if (!findInterfacesRes.equals(JanusGraphOperationStatus.OK)) { log.error("Failed to get all interfaces of resource {}. status is {}", resourceId, findInterfacesRes); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findInterfacesRes)); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(findInterfacesRes)); return result; } result = Either.left(interfaces); @@ -222,23 +229,24 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation if (!inTransaction) { if (result == null || result.isRight()) { log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } } - private TitanOperationStatus findAllInterfacesNotRecursively(String resourceId, Map interfaces) { + private JanusGraphOperationStatus findAllInterfacesNotRecursively(String resourceId, Map interfaces) { - Either>, TitanOperationStatus> interfaceNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.INTERFACE, + Either>, JanusGraphOperationStatus> interfaceNodes = janusGraphGenericDao + .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class); if (interfaceNodes.isRight()) { - TitanOperationStatus status = interfaceNodes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = interfaceNodes.right().value(); + if (status != JanusGraphOperationStatus.NOT_FOUND) { return status; } } else { @@ -246,15 +254,15 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation if (interfaceList != null) { for (ImmutablePair interfacePair : interfaceList) { String interfaceUniqueId = (String) interfacePair.getKey().getUniqueId(); - Either interfaceNameRes = getPropertyValueFromEdge(interfacePair.getValue(), GraphPropertiesDictionary.NAME); + Either interfaceNameRes = getPropertyValueFromEdge(interfacePair.getValue(), GraphPropertiesDictionary.NAME); if (interfaceNameRes.isRight()) { log.error("The requirement name is missing on the edge of requirement {}", interfaceUniqueId); return interfaceNameRes.right().value(); } String interfaceName = interfaceNameRes.left().value(); - Either interfaceDefRes = getNonRecursiveInterface(interfacePair.getKey()); + Either interfaceDefRes = getNonRecursiveInterface(interfacePair.getKey()); if (interfaceDefRes.isRight()) { - TitanOperationStatus status = interfaceDefRes.right().value(); + JanusGraphOperationStatus status = interfaceDefRes.right().value(); log.error("Failed to get interface actions of interface {}", interfaceUniqueId); return status; } @@ -271,24 +279,26 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } } } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } - public TitanOperationStatus findAllInterfacesRecursively(String resourceId, Map interfaces) { + public JanusGraphOperationStatus findAllInterfacesRecursively(String resourceId, Map interfaces) { - TitanOperationStatus findAllInterfacesNotRecursively = findAllInterfacesNotRecursively(resourceId, interfaces); - if (!findAllInterfacesNotRecursively.equals(TitanOperationStatus.OK)) { + JanusGraphOperationStatus + findAllInterfacesNotRecursively = findAllInterfacesNotRecursively(resourceId, interfaces); + if (!findAllInterfacesNotRecursively.equals(JanusGraphOperationStatus.OK)) { log.error("failed to get interfaces for resource {}. status is {}", resourceId, findAllInterfacesNotRecursively); } - Either, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, + Either, JanusGraphOperationStatus> parentNodes = janusGraphGenericDao + .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) { + JanusGraphOperationStatus parentNodesStatus = parentNodes.right().value(); + if (parentNodesStatus == JanusGraphOperationStatus.NOT_FOUND) { log.debug("Finish to lookup for parnet interfaces"); - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } else { log.error("Failed to find parent interfaces of resource {}. status is {}", resourceId, parentNodesStatus); return parentNodesStatus; @@ -296,42 +306,44 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } ImmutablePair parnetNodePair = parentNodes.left().value(); String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - TitanOperationStatus addParentIntStatus = findAllInterfacesRecursively(parentUniqueId, interfaces); + JanusGraphOperationStatus + addParentIntStatus = findAllInterfacesRecursively(parentUniqueId, interfaces); - if (addParentIntStatus != TitanOperationStatus.OK) { + if (addParentIntStatus != JanusGraphOperationStatus.OK) { log.error("Failed to fetch all interfaces of resource {}", parentUniqueId); return addParentIntStatus; } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } - private Either getPropertyValueFromEdge(GraphEdge edge, GraphPropertiesDictionary property) { + private Either getPropertyValueFromEdge(GraphEdge edge, GraphPropertiesDictionary property) { Map edgeProps = edge.getProperties(); String interfaceName = null; if (edgeProps != null) { interfaceName = (String) edgeProps.get(property.getProperty()); if (interfaceName == null) { - return Either.right(TitanOperationStatus.INVALID_ELEMENT); + return Either.right(JanusGraphOperationStatus.INVALID_ELEMENT); } } else { - return Either.right(TitanOperationStatus.INVALID_ELEMENT); + return Either.right(JanusGraphOperationStatus.INVALID_ELEMENT); } return Either.left(interfaceName); } - private Either getNonRecursiveInterface(InterfaceData interfaceData) { + private Either getNonRecursiveInterface(InterfaceData interfaceData) { log.debug("Going to fetch the operations associate to interface {}", interfaceData.getUniqueId()); InterfaceDefinition interfaceDefinition = new InterfaceDefinition(interfaceData.getInterfaceDataDefinition()); String interfaceId = interfaceData.getUniqueId(); - Either>, TitanOperationStatus> operationsRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), interfaceId, GraphEdgeLabels.INTERFACE_OPERATION, + Either>, JanusGraphOperationStatus> operationsRes = janusGraphGenericDao + .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), interfaceId, GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); if (operationsRes.isRight()) { - TitanOperationStatus status = operationsRes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = operationsRes.right().value(); + if (status != JanusGraphOperationStatus.NOT_FOUND) { return Either.right(status); } else { return Either.left(interfaceDefinition); @@ -342,7 +354,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation if (operationList != null && !operationList.isEmpty()) { for (ImmutablePair operationPair : operationList) { Operation operation = new Operation(operationPair.getKey().getOperationDataDefinition()); - Either operationNameRes = getPropertyValueFromEdge(operationPair.getValue(), GraphPropertiesDictionary.NAME); + Either operationNameRes = getPropertyValueFromEdge(operationPair.getValue(), GraphPropertiesDictionary.NAME); if (operationNameRes.isRight()) { log.error("The operation name is missing on the edge of operation {}", operationPair.getKey().getUniqueId()); return Either.right(operationNameRes.right().value()); @@ -401,7 +413,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation private Either updateOperationOnGraph(Operation operation, String resourceId, String interfaceName, String operationName) { - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, + Either>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao + .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class); if (childrenNodes.isRight()) { @@ -415,7 +428,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } private Either updateExistingOperation(String resourceId, Operation operation, String interfaceName, String operationName, - Either>, TitanOperationStatus> childrenNodes) { + Either>, JanusGraphOperationStatus> childrenNodes) { Operation newOperation = null; StorageOperationStatus storageOperationStatus = StorageOperationStatus.GENERAL_ERROR; @@ -426,11 +439,12 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation InterfaceData interfaceData = interfaceDataNode.getKey(); if (interfaceEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(interfaceName)) { - Either>, TitanOperationStatus> operationRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceDataNode.getLeft().getUniqueId(), + Either>, JanusGraphOperationStatus> operationRes = janusGraphGenericDao + .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceDataNode.getLeft().getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); if (operationRes.isRight()) { log.error("Failed to find operation {} on interface {}", operationName, interfaceName); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationRes.right().value())); } else { List> operations = operationRes.left().value(); for (ImmutablePair operationPairEdge : operations) { @@ -439,7 +453,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation Map opEdgeProp = opEdge.getProperties(); if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(operationName)) { ArtifactDefinition artifact = operation.getImplementationArtifact(); - Either, TitanOperationStatus> artifactRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) opData.getUniqueId(), GraphEdgeLabels.ARTIFACT_REF, + Either, JanusGraphOperationStatus> artifactRes = janusGraphGenericDao + .getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) opData.getUniqueId(), GraphEdgeLabels.ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class); Either artStatus; if (artifactRes.isRight()) { @@ -448,7 +463,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation artStatus = artifactOperation.updateArifactOnResource(artifact, (String) operationPairEdge.getLeft().getUniqueId(), (String) artifactRes.left().value().getLeft().getUniqueId(), NodeTypeEnum.InterfaceOperation, true); } if (artStatus.isRight()) { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); return Either.right(artStatus.right().value()); } else { @@ -461,18 +476,19 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } if (newOperation == null) { - Either parentInterfaceStatus = findInterfaceOnParentNode(resourceId, interfaceName); + Either parentInterfaceStatus = findInterfaceOnParentNode(resourceId, interfaceName); if (parentInterfaceStatus.isRight()) { log.debug("Interface {} not exist", interfaceName); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentInterfaceStatus.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentInterfaceStatus.right().value())); } InterfaceData parentInterfaceData = parentInterfaceStatus.left().value(); - Either>, TitanOperationStatus> opRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) parentInterfaceData.getUniqueId(), + Either>, JanusGraphOperationStatus> opRes = janusGraphGenericDao + .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) parentInterfaceData.getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); if (opRes.isRight()) { log.error("Failed to find operation {} on interface {}", operationName, interfaceName); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationRes.right().value())); } else { List> parentOperations = opRes.left().value(); @@ -503,21 +519,21 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } private Either copyAndCreateNewOperation(Operation operation, String interfaceName, String operationName, Operation newOperation, InterfaceData interfaceData, - Either>, TitanOperationStatus> operationRes, OperationData opData) { + Either>, JanusGraphOperationStatus> operationRes, OperationData opData) { OperationDataDefinition opDataInfo = opData.getOperationDataDefinition(); OperationDataDefinition newOperationInfo = new OperationDataDefinition(opDataInfo); newOperationInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(interfaceData.getUniqueId(), operationName.toLowerCase())); OperationData newopData = new OperationData(newOperationInfo); - Either operationStatus = createOperationNodeAndRelation(operationName, newopData, interfaceData); + Either operationStatus = createOperationNodeAndRelation(operationName, newopData, interfaceData); if (operationStatus.isRight()) { log.error("Failed to create operation {} on interface {}", operationName, interfaceName); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationRes.right().value())); } ArtifactDefinition artifact = operation.getImplementationArtifact(); if (artifact != null) { Either artStatus = artifactOperation.addArifactToComponent(artifact, (String) operationStatus.left().value().getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true); if (artStatus.isRight()) { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); } else { newOperation = this.convertOperationDataToOperation(opData); @@ -532,10 +548,10 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation // Operation newOperation = null; ResourceMetadataData resourceData = new ResourceMetadataData(); resourceData.getMetadataDataDefinition().setUniqueId(resourceId); - Either parentInterfaceStatus = findInterfaceOnParentNode(resourceId, interfaceName); + Either parentInterfaceStatus = findInterfaceOnParentNode(resourceId, interfaceName); if (parentInterfaceStatus.isRight()) { log.debug("Interface {} not exist", interfaceName); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentInterfaceStatus.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentInterfaceStatus.right().value())); } InterfaceData interfaceData = parentInterfaceStatus.left().value(); @@ -546,25 +562,27 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation newInterfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted)); InterfaceData updatedInterfaceData = new InterfaceData(newInterfaceInfo); - Either createStatus = createInterfaceNodeAndRelation(interfaceName, resourceId, updatedInterfaceData, resourceData); + Either createStatus = createInterfaceNodeAndRelation(interfaceName, resourceId, updatedInterfaceData, resourceData); if (createStatus.isRight()) { log.debug("failed to create interface node {} on resource {}", interfaceName, resourceId); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createStatus.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createStatus.right().value())); } InterfaceData newInterfaceNode = createStatus.left().value(); - Either createRelResult = titanGenericDao.createRelation(newInterfaceNode, interfaceData, GraphEdgeLabels.DERIVED_FROM, null); + Either createRelResult = janusGraphGenericDao + .createRelation(newInterfaceNode, interfaceData, GraphEdgeLabels.DERIVED_FROM, null); if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); + JanusGraphOperationStatus operationStatus = createRelResult.right().value(); log.error("Failed to associate interface {} to interface {} in graph. status is {}", interfaceData.getUniqueId(), newInterfaceNode.getUniqueId(), operationStatus); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationStatus)); } - Either>, TitanOperationStatus> operationRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceData.getUniqueId(), + Either>, JanusGraphOperationStatus> operationRes = janusGraphGenericDao + .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceData.getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); if (operationRes.isRight()) { log.error("Failed to find operation {} on interface {}", operationName, interfaceName); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationRes.right().value())); } else { List> operations = operationRes.left().value(); @@ -585,9 +603,10 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation return Either.right(StorageOperationStatus.GENERAL_ERROR); } - private Either findInterfaceOnParentNode(String resourceId, String interfaceName) { + private Either findInterfaceOnParentNode(String resourceId, String interfaceName) { - Either, TitanOperationStatus> parentRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, + Either, JanusGraphOperationStatus> parentRes = janusGraphGenericDao + .getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class); if (parentRes.isRight()) { log.debug("interface {} not found ", interfaceName); @@ -595,7 +614,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } ImmutablePair parenNode = parentRes.left().value(); - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), parenNode.getKey().getMetadataDataDefinition().getUniqueId(), + Either>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao + .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), parenNode.getKey().getMetadataDataDefinition().getUniqueId(), GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class); if (childrenNodes.isRight()) { return findInterfaceOnParentNode(parenNode.getKey().getMetadataDataDefinition().getUniqueId(), interfaceName); @@ -619,16 +639,16 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation @Override public Either createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction) { - Either status = addInterfaceToGraph(interf, interfaceName, resourceId); + Either status = addInterfaceToGraph(interf, interfaceName, resourceId); if (status.isRight()) { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); log.error("Failed to add interface {} to resource {}", interfaceName, resourceId); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status.right().value())); } else { if (!inTransaction) { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } InterfaceData interfaceData = status.left().value(); @@ -640,13 +660,13 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation for (String operationName : opNames) { Operation op = operations.get(operationName); - Either opStatus = addOperationToGraph(interf, operationName, op, interfaceData); + Either opStatus = addOperationToGraph(interf, operationName, op, interfaceData); if (status.isRight()) { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); log.error("Failed to add operation {} to interface {}", operationName, interfaceName); } else if (status.isLeft()) { if (!inTransaction) { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } OperationData opData = opStatus.left().value(); Operation newOperation = this.convertOperationDataToOperation(opData); @@ -655,7 +675,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation if (art != null) { Either artRes = artifactOperation.addArifactToComponent(art, (String) opData.getUniqueId(), NodeTypeEnum.InterfaceOperation, failIfExist, true); if (artRes.isRight()) { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); } else { newOperation.setImplementation(artRes.left().value()); @@ -675,16 +695,16 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation @Override public Either deleteInterfaceOperation(String resourceId, String interfaceName, String operationId, boolean inTransaction) { - Either status = removeOperationOnGraph(resourceId, interfaceName, operationId); + Either status = removeOperationOnGraph(resourceId, interfaceName, operationId); if (status.isRight()) { if (!inTransaction) { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } log.error("Failed to delete operation {} of interface {} resource {}", operationId, interfaceName, resourceId); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status.right().value())); } else { if (!inTransaction) { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } Operation opDefResult = status.left().value();// convertOperationDataToOperation(operationData); @@ -694,10 +714,11 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } - private Either removeOperationOnGraph(String resourceId, String interfaceName, String operationId) { + private Either removeOperationOnGraph(String resourceId, String interfaceName, String operationId) { log.debug("Before deleting operation from graph {}", operationId); - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, + Either>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao + .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class); if (childrenNodes.isRight()) { @@ -713,7 +734,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation String interfaceSplitedName = splitType(interfaceName); if (interfaceEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(interfaceSplitedName)) { - Either>, TitanOperationStatus> operationRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceDataNode.getLeft().getUniqueId(), + Either>, JanusGraphOperationStatus> operationRes = janusGraphGenericDao + .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceDataNode.getLeft().getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); if (operationRes.isRight()) { log.error("Failed to find operation {} on interface {}", operationId, interfaceName); @@ -726,7 +748,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation opData = operationPairEdge.getLeft(); if (opData.getUniqueId().equals(operationId)) { - Either, TitanOperationStatus> artifactRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) operationPairEdge.getLeft().getUniqueId(), + Either, JanusGraphOperationStatus> artifactRes = janusGraphGenericDao + .getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) operationPairEdge.getLeft().getUniqueId(), GraphEdgeLabels.ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class); Either arStatus = null; if (artifactRes.isLeft()) { @@ -734,13 +757,14 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation arStatus = artifactOperation.removeArifactFromResource((String) operationPairEdge.getLeft().getUniqueId(), (String) arData.getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true); if (arStatus.isRight()) { log.debug("failed to delete artifact {}", arData.getUniqueId()); - return Either.right(TitanOperationStatus.INVALID_ID); + return Either.right(JanusGraphOperationStatus.INVALID_ID); } } - Either deleteOpStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InterfaceOperation), opData.getUniqueId(), OperationData.class); + Either deleteOpStatus = janusGraphGenericDao + .deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InterfaceOperation), opData.getUniqueId(), OperationData.class); if (deleteOpStatus.isRight()) { log.debug("failed to delete operation {}", opData.getUniqueId()); - return Either.right(TitanOperationStatus.INVALID_ID); + return Either.right(JanusGraphOperationStatus.INVALID_ID); } opData = deleteOpStatus.left().value(); Operation operation = new Operation(opData.getOperationDataDefinition()); @@ -748,10 +772,11 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation operation.setImplementation(arStatus.left().value()); } if (operations.size() <= 1) { - Either deleteInterfaceStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDataNode.left.getUniqueId(), InterfaceData.class); + Either deleteInterfaceStatus = janusGraphGenericDao + .deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDataNode.left.getUniqueId(), InterfaceData.class); if (deleteInterfaceStatus.isRight()) { log.debug("failed to delete interface {}", interfaceDataNode.left.getUniqueId()); - return Either.right(TitanOperationStatus.INVALID_ID); + return Either.right(JanusGraphOperationStatus.INVALID_ID); } } @@ -764,7 +789,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } log.debug("Not found operation {}", interfaceName); - return Either.right(TitanOperationStatus.INVALID_ID); + return Either.right(JanusGraphOperationStatus.INVALID_ID); } private String splitType(String interfaceName) { @@ -783,10 +808,10 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation /** * FOR TEST ONLY * - * @param titanGenericDao + * @param janusGraphGenericDao */ - public void setTitanGenericDao(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; + public void setJanusGraphGenericDao(JanusGraphGenericDao janusGraphGenericDao) { + this.janusGraphGenericDao = janusGraphGenericDao; } public void setArtifactOperation(ArtifactOperation artifactOperation) { @@ -801,7 +826,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation InterfaceData interfaceData = new InterfaceData(interf); interf.setUniqueId(interf.getType().toLowerCase()); - Either existInterface = titanGenericDao.getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class); + Either existInterface = janusGraphGenericDao + .getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class); if (existInterface.isLeft()) { // already exist @@ -811,13 +837,14 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } log.debug("Before adding interface type to graph {}", interfaceData); - Either createNodeResult = titanGenericDao.createNode(interfaceData, InterfaceData.class); + Either createNodeResult = janusGraphGenericDao + .createNode(interfaceData, InterfaceData.class); log.debug("After adding property type to graph {}", interfaceData); if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); log.error("Failed to add interface {} to graph. status is {}", interf.getType(), operationStatus); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus)); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationStatus)); return result; } @@ -828,12 +855,12 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation Map newOperations = new HashMap<>(); for (Map.Entry operation : operations.entrySet()) { - Either opStatus = addOperationToGraph(interf, operation.getKey(), operation.getValue(), interfaceData); + Either opStatus = addOperationToGraph(interf, operation.getKey(), operation.getValue(), interfaceData); if (opStatus.isRight()) { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); log.error("Failed to add operation {} to interface {}", operation.getKey(), interf.getType()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(opStatus.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(opStatus.right().value())); return result; } else { OperationData opData = opStatus.left().value(); @@ -849,10 +876,10 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation if (!inTransaction) { if (result == null || result.isRight()) { log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } @@ -861,14 +888,15 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation @Override public Either getInterface(String interfaceId) { - Either getResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceId, InterfaceData.class); + Either getResult = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceId, InterfaceData.class); if (getResult.isLeft()) { InterfaceData interfaceData = getResult.left().value(); return Either.left(convertInterfaceDataToInterfaceDefinition(interfaceData)); } else { - TitanOperationStatus titanStatus = getResult.right().value(); - log.debug("Node with id {} was not found in the graph. status: {}", interfaceId, titanStatus); - StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); + JanusGraphOperationStatus janusGraphStatus = getResult.right().value(); + log.debug("Node with id {} was not found in the graph. status: {}", interfaceId, janusGraphStatus); + StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphStatus); return Either.right(storageOperationStatus); } } @@ -894,10 +922,11 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation @Override public Either, StorageOperationStatus> getAllInterfaceLifecycleTypes() { - Either, TitanOperationStatus> allInterfaceLifecycleTypes = - titanGenericDao.getByCriteria(NodeTypeEnum.Interface, Collections.emptyMap(), InterfaceData.class); + Either, JanusGraphOperationStatus> allInterfaceLifecycleTypes = + janusGraphGenericDao + .getByCriteria(NodeTypeEnum.Interface, Collections.emptyMap(), InterfaceData.class); if (allInterfaceLifecycleTypes.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus (allInterfaceLifecycleTypes.right().value())); } @@ -909,8 +938,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation .collect(Collectors.toList()); for (InterfaceDefinition interfaceDefinition : interfaceDefinitions) { - Either>, TitanOperationStatus> - childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), + Either>, JanusGraphOperationStatus> + childrenNodes = janusGraphGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), interfaceDefinition.getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); if (childrenNodes.isLeft()) { Map operationsDataDefinitionMap = new HashMap<>(); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OperationUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OperationUtils.java index a06d342d26..2266acf88f 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OperationUtils.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OperationUtils.java @@ -1,8 +1,8 @@ package org.openecomp.sdc.be.model.operations.impl; import fj.data.Either; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.operations.StorageException; @@ -14,32 +14,33 @@ import java.util.Map; @Component public class OperationUtils { - private final TitanDao titanDao; + private final JanusGraphDao janusGraphDao; private static final Logger logger = Logger.getLogger(OperationUtils.class.getName()); - public OperationUtils(TitanDao titanDao) { - this.titanDao = titanDao; + public OperationUtils(JanusGraphDao janusGraphDao) { + this.janusGraphDao = janusGraphDao; } - public T onTitanOperationFailure(TitanOperationStatus status) { - titanDao.rollback(); + public T onJanusGraphOperationFailure(JanusGraphOperationStatus status) { + janusGraphDao.rollback(); throw new StorageException(status); } - static Either, TitanOperationStatus> fillProperties(String uniqueId, - PropertyOperation propertyOperation, - NodeTypeEnum nodeTypeEnum) { + static Either, JanusGraphOperationStatus> fillProperties(String uniqueId, + PropertyOperation propertyOperation, + NodeTypeEnum nodeTypeEnum) { - Either, TitanOperationStatus> findPropertiesOfNode = + Either, JanusGraphOperationStatus> findPropertiesOfNode = propertyOperation.findPropertiesOfNode(nodeTypeEnum, uniqueId); if (findPropertiesOfNode.isRight()) { - TitanOperationStatus titanOperationStatus = findPropertiesOfNode.right().value(); - logger.debug("After looking for properties of vertex {}. status is {}", uniqueId, titanOperationStatus); - if (TitanOperationStatus.NOT_FOUND.equals(titanOperationStatus)) { - return Either.right(TitanOperationStatus.OK); + JanusGraphOperationStatus janusGraphOperationStatus = findPropertiesOfNode.right().value(); + logger.debug("After looking for properties of vertex {}. status is {}", uniqueId, + janusGraphOperationStatus); + if (JanusGraphOperationStatus.NOT_FOUND.equals(janusGraphOperationStatus)) { + return Either.right(JanusGraphOperationStatus.OK); } else { - return Either.right(titanOperationStatus); + return Either.right(janusGraphOperationStatus); } } else { return Either.left(findPropertiesOfNode.left().value()); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java index 76652e1cce..e8a74fe79d 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java @@ -20,12 +20,12 @@ package org.openecomp.sdc.be.model.operations.impl; -import com.thinkaurelius.titan.graphdb.query.TitanPredicate; +import org.janusgraph.graphdb.query.JanusGraphPredicate; import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.PolicyTypeDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.PolicyTypeDefinition; @@ -42,7 +42,7 @@ import org.springframework.stereotype.Component; import java.util.*; import java.util.stream.Collectors; -import static org.openecomp.sdc.be.dao.titan.TitanUtils.buildNotInPredicate; +import static org.openecomp.sdc.be.dao.janusgraph.JanusGraphUtils.buildNotInPredicate; @Component("policy-type-operation") public class PolicyTypeOperation extends AbstractOperation implements IPolicyTypeOperation { @@ -94,12 +94,13 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp @Override public List getAllPolicyTypes(Set excludedPolicyTypes) { - Map> predicateCriteria = buildNotInPredicate(GraphPropertiesDictionary.TYPE.getProperty(), excludedPolicyTypes); - return titanGenericDao.getByCriteriaWithPredicate(NodeTypeEnum.PolicyType, predicateCriteria, PolicyTypeData.class) + Map> predicateCriteria = buildNotInPredicate(GraphPropertiesDictionary.TYPE.getProperty(), excludedPolicyTypes); + return janusGraphGenericDao + .getByCriteriaWithPredicate(NodeTypeEnum.PolicyType, predicateCriteria, PolicyTypeData.class) .left() .map(this::convertPolicyTypesToDefinition) .left() - .on(operationUtils::onTitanOperationFailure); + .on(operationUtils::onJanusGraphOperationFailure); } private List convertPolicyTypesToDefinition(List policiesTypes) { @@ -113,18 +114,19 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp String ptUniqueId = UniqueIdBuilder.buildPolicyTypeUid(policyTypeDef.getType(), policyTypeDef.getVersion(), "policytype"); PolicyTypeData policyTypeData = buildPolicyTypeData(policyTypeDef, ptUniqueId); log.debug("Before adding policy type to graph. policyTypeData = {}", policyTypeData); - Either eitherPolicyTypeData = titanGenericDao.createNode(policyTypeData, PolicyTypeData.class); + Either eitherPolicyTypeData = janusGraphGenericDao + .createNode(policyTypeData, PolicyTypeData.class); log.debug("After adding policy type to graph. status is = {}", eitherPolicyTypeData); if (eitherPolicyTypeData.isRight()) { - TitanOperationStatus operationStatus = eitherPolicyTypeData.right().value(); + JanusGraphOperationStatus operationStatus = eitherPolicyTypeData.right().value(); log.error("Failed to add policy type {} to graph. status is {}", policyTypeDef.getType(), operationStatus); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationStatus)); } List properties = policyTypeDef.getProperties(); - Either, TitanOperationStatus> addPropertiesToPolicyType = propertyOperation.addPropertiesToElementType(ptUniqueId, NodeTypeEnum.PolicyType, properties); + Either, JanusGraphOperationStatus> addPropertiesToPolicyType = propertyOperation.addPropertiesToElementType(ptUniqueId, NodeTypeEnum.PolicyType, properties); if (addPropertiesToPolicyType.isRight()) { log.error("Failed add properties {} to policy {}", properties, policyTypeDef.getType()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertiesToPolicyType.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertiesToPolicyType.right().value())); } return addDerivedFromRelation(policyTypeDef, ptUniqueId) .left() @@ -139,9 +141,10 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp return result; } - Either, TitanOperationStatus> eitherPolicyData = titanGenericDao.getByCriteria(NodeTypeEnum.PolicyType, properties, PolicyTypeData.class); + Either, JanusGraphOperationStatus> eitherPolicyData = janusGraphGenericDao + .getByCriteria(NodeTypeEnum.PolicyType, properties, PolicyTypeData.class); if (eitherPolicyData.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherPolicyData.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherPolicyData.right().value())); } else { PolicyTypeDataDefinition dataDefinition = eitherPolicyData.left().value().stream().map(PolicyTypeData::getPolicyTypeDataDefinition).findFirst().get(); result = getPolicyTypeByUid(dataDefinition.getUniqueId()); @@ -152,9 +155,10 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp private Either getPolicyTypeByUid(String uniqueId) { log.debug("#getPolicyTypeByUid - fetching policy type with id {}", uniqueId); - return titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), uniqueId, PolicyTypeData.class) + return janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), uniqueId, PolicyTypeData.class) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus) + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus) .left() .bind(policyType -> createPolicyTypeDefinition(uniqueId, policyType)); } @@ -207,11 +211,11 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp return Either.right(err); } - Either, StorageOperationStatus> handlePolicyTypeHasNoProperties(TitanOperationStatus err) { - if (err == TitanOperationStatus.NOT_FOUND) { + Either, StorageOperationStatus> handlePolicyTypeHasNoProperties(JanusGraphOperationStatus err) { + if (err == JanusGraphOperationStatus.NOT_FOUND) { return Either.left(new HashMap<>()); } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(err)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(err)); } private PolicyTypeData setDerivedFrom(PolicyTypeDefinition policyTypeDefinition, PolicyTypeData derivedFrom) { @@ -238,9 +242,9 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp private Either updatePolicyTypeOnGraph(PolicyTypeDefinition updatedPolicyType, PolicyTypeDefinition currPolicyType) { updatePolicyTypeData(updatedPolicyType, currPolicyType); - return titanGenericDao.updateNode(new PolicyTypeData(updatedPolicyType), PolicyTypeData.class) + return janusGraphGenericDao.updateNode(new PolicyTypeData(updatedPolicyType), PolicyTypeData.class) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus) + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus) .left() .bind(updatedNode -> updatePolicyProperties(updatedPolicyType.getUniqueId(), updatedPolicyType.getProperties())) .left() @@ -291,7 +295,7 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp log.debug("#addPropertiesToPolicy - adding policy type properties for policy type with id {}", policyTypeId); return propertyOperation.addPropertiesToElementType(policyTypeId, NodeTypeEnum.PolicyType, properties) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); } private void updatePolicyTypeData(PolicyTypeDefinition updatedTypeDefinition, PolicyTypeDefinition currTypeDefinition) { 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 fb023c7f45..54fea421a0 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 @@ -33,9 +33,9 @@ import com.google.gson.JsonParseException; import com.google.gson.JsonParser; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; -import com.thinkaurelius.titan.core.TitanVertexProperty; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; +import org.janusgraph.core.JanusGraphVertexProperty; import fj.data.Either; import java.io.IOException; import java.lang.reflect.Type; @@ -66,11 +66,11 @@ 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.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.HealingTitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; @@ -132,8 +132,8 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } - public PropertyOperation(HealingTitanGenericDao titanGenericDao, DerivedFromOperation derivedFromOperation) { - this.titanGenericDao = titanGenericDao; + public PropertyOperation(HealingJanusGraphGenericDao janusGraphGenericDao, DerivedFromOperation derivedFromOperation) { + this.janusGraphGenericDao = janusGraphGenericDao; this.derivedFromOperation = derivedFromOperation; } @@ -331,9 +331,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe public Either addProperty(String propertyName, PropertyDefinition propertyDefinition, String resourceId) { - Either either = addPropertyToGraph(propertyName, propertyDefinition, resourceId); + Either either = addPropertyToGraph(propertyName, propertyDefinition, resourceId); if (either.isRight()) { - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value()); + StorageOperationStatus storageStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value()); return Either.right(storageStatus); } return Either.left(either.left().value()); @@ -366,7 +366,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } String innerType = null; - Either checkInnerType = getInnerType(type, propertyDefinition::getSchema); + Either checkInnerType = getInnerType(type, propertyDefinition::getSchema); if (checkInnerType.isRight()) { return StorageOperationStatus.INVALID_TYPE; } @@ -392,7 +392,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return StorageOperationStatus.OK; } - public Either addPropertyToGraph(String propertyName, PropertyDefinition propertyDefinition, String resourceId) { + public Either addPropertyToGraph(String propertyName, PropertyDefinition propertyDefinition, String resourceId) { ResourceMetadataData resourceData = new ResourceMetadataData(); resourceData.getMetadataDataDefinition().setUniqueId(resourceId); @@ -403,19 +403,21 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints)); log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData); - Either createNodeResult = titanGenericDao.createNode(propertyData, PropertyData.class); + Either createNodeResult = janusGraphGenericDao + .createNode(propertyData, PropertyData.class); log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData); if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus); return Either.right(operationStatus); } Map props = new HashMap<>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName); - Either createRelResult = titanGenericDao.createRelation(resourceData, propertyData, GraphEdgeLabels.PROPERTY, props); + Either createRelResult = janusGraphGenericDao + .createRelation(resourceData, propertyData, GraphEdgeLabels.PROPERTY, props); if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, resourceId, propertyName, operationStatus); return Either.right(operationStatus); } @@ -424,7 +426,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } - public TitanOperationStatus addPropertyToGraphByVertex(TitanVertex metadataVertex, String propertyName, PropertyDefinition propertyDefinition, String resourceId) { + public JanusGraphOperationStatus addPropertyToGraphByVertex(JanusGraphVertex metadataVertex, String propertyName, PropertyDefinition propertyDefinition, String resourceId) { List constraints = propertyDefinition.getConstraints(); @@ -432,19 +434,21 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints)); log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData); - Either createNodeResult = titanGenericDao.createNode(propertyData); + Either createNodeResult = janusGraphGenericDao.createNode(propertyData); log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData); if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); log.error("Failed to add property {} to graph. status is ", propertyName, operationStatus); return operationStatus; } Map props = new HashMap<>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName); - TitanVertex propertyVertex = createNodeResult.left().value(); - TitanOperationStatus createRelResult = titanGenericDao.createEdge(metadataVertex, propertyVertex, GraphEdgeLabels.PROPERTY, props); - if (!createRelResult.equals(TitanOperationStatus.OK)) { + JanusGraphVertex propertyVertex = createNodeResult.left().value(); + JanusGraphOperationStatus + createRelResult = janusGraphGenericDao + .createEdge(metadataVertex, propertyVertex, GraphEdgeLabels.PROPERTY, props); + if (!createRelResult.equals(JanusGraphOperationStatus.OK)) { log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, resourceId, propertyName, createRelResult); return createRelResult; } @@ -453,13 +457,14 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } - public TitanGenericDao getTitanGenericDao() { - return titanGenericDao; + public JanusGraphGenericDao getJanusGraphGenericDao() { + return janusGraphGenericDao; } - public Either deletePropertyFromGraph(String propertyId) { + public Either deletePropertyFromGraph(String propertyId) { log.debug("Before deleting property from graph {}", propertyId); - return titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class); + return janusGraphGenericDao + .deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class); } public Either updateProperty(String propertyId, PropertyDefinition newPropertyDefinition, Map dataTypes) { @@ -469,20 +474,21 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return Either.right(validateAndUpdateProperty); } - Either either = updatePropertyFromGraph(propertyId, newPropertyDefinition); + Either either = updatePropertyFromGraph(propertyId, newPropertyDefinition); if (either.isRight()) { - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value()); + StorageOperationStatus storageStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value()); return Either.right(storageStatus); } return Either.left(either.left().value()); } - public Either updatePropertyFromGraph(String propertyId, PropertyDefinition propertyDefinition) { + public Either updatePropertyFromGraph(String propertyId, PropertyDefinition propertyDefinition) { if (log.isDebugEnabled()) log.debug("Before updating property on graph {}", propertyId); // get the original property data - Either statusProperty = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class); + Either statusProperty = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class); if (statusProperty.isRight()) { log.debug("Problem while get property with id {}. Reason - {}", propertyId, statusProperty.right().value().name()); return Either.right(statusProperty.right().value()); @@ -518,19 +524,19 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } orgPropertyDataDefinition.setSchema(newPropertyDataDefinition.getSchema()); - return titanGenericDao.updateNode(orgPropertyData, PropertyData.class); + return janusGraphGenericDao.updateNode(orgPropertyData, PropertyData.class); } /** * FOR TEST ONLY * - * @param titanGenericDao + * @param janusGraphGenericDao */ - public void setTitanGenericDao(HealingTitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; + public void setJanusGraphGenericDao(HealingJanusGraphGenericDao janusGraphGenericDao) { + this.janusGraphGenericDao = janusGraphGenericDao; } - public Either addPropertyToNodeType(String propertyName, PropertyDefinition propertyDefinition, NodeTypeEnum nodeType, String uniqueId) { + public Either addPropertyToNodeType(String propertyName, PropertyDefinition propertyDefinition, NodeTypeEnum nodeType, String uniqueId) { List constraints = propertyDefinition.getConstraints(); @@ -539,11 +545,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (log.isDebugEnabled()) log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData); - Either createNodeResult = titanGenericDao.createNode(propertyData, PropertyData.class); + Either createNodeResult = janusGraphGenericDao + .createNode(propertyData, PropertyData.class); if (log.isDebugEnabled()) log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData); if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus); return Either.right(operationStatus); } @@ -553,9 +560,10 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe UniqueIdData uniqueIdData = new UniqueIdData(nodeType, uniqueId); log.debug("Before associating {} to property {}", uniqueIdData, propertyName); - Either createRelResult = titanGenericDao.createRelation(uniqueIdData, propertyData, GraphEdgeLabels.PROPERTY, props); + Either createRelResult = janusGraphGenericDao + .createRelation(uniqueIdData, propertyData, GraphEdgeLabels.PROPERTY, props); if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); + JanusGraphOperationStatus operationStatus = createNodeResult.right().value(); log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, uniqueId, propertyName, operationStatus); return Either.right(operationStatus); } @@ -564,15 +572,16 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } - public Either, TitanOperationStatus> findPropertiesOfNode(NodeTypeEnum nodeType, String uniqueId) { + public Either, JanusGraphOperationStatus> findPropertiesOfNode(NodeTypeEnum nodeType, String uniqueId) { Map resourceProps = new HashMap<>(); - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property, + Either>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao + .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property, PropertyData.class); if (childrenNodes.isRight()) { - TitanOperationStatus operationStatus = childrenNodes.right().value(); + JanusGraphOperationStatus operationStatus = childrenNodes.right().value(); return Either.right(operationStatus); } @@ -600,15 +609,15 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe .bind(err -> err == StorageOperationStatus.OK ? Either.left(Collections.emptyMap()) : Either.right(err)); } - public Either, TitanOperationStatus> mergePropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId, Map newProperties) { - Either, TitanOperationStatus> oldPropertiesRes = findPropertiesOfNode(nodeType, uniqueId); + public Either, JanusGraphOperationStatus> mergePropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId, Map newProperties) { + Either, JanusGraphOperationStatus> oldPropertiesRes = findPropertiesOfNode(nodeType, uniqueId); Map reallyNewProperties; Map unchangedPropsData; if (oldPropertiesRes.isRight()) { - TitanOperationStatus err = oldPropertiesRes.right().value(); - if (err == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus err = oldPropertiesRes.right().value(); + if (err == JanusGraphOperationStatus.NOT_FOUND) { reallyNewProperties = newProperties; unchangedPropsData = Collections.emptyMap(); } @@ -625,8 +634,8 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe PropertyDefinition newPropDef = newProperties != null? newProperties.get(key): null; PropertyDefinition oldPropDef = oldEntry.getValue(); - TitanOperationStatus status = updateOldProperty(newPropDef, oldPropDef); - if (status != TitanOperationStatus.OK) { + JanusGraphOperationStatus status = updateOldProperty(newPropDef, oldPropDef); + if (status != JanusGraphOperationStatus.OK) { return Either.right(status); } } @@ -654,9 +663,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * @param newPropDef * @param oldPropDef */ - private TitanOperationStatus updateOldProperty(PropertyDefinition newPropDef, PropertyDefinition oldPropDef) { + private JanusGraphOperationStatus updateOldProperty(PropertyDefinition newPropDef, PropertyDefinition oldPropDef) { if (!isUpdateAllowed(newPropDef, oldPropDef)) { - return TitanOperationStatus.MATCH_NOT_FOUND; + return JanusGraphOperationStatus.MATCH_NOT_FOUND; } if (isUpdateRequired(newPropDef, oldPropDef)) { @@ -664,14 +673,15 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe List constraints = oldPropDef.getConstraints(); PropertyData node = new PropertyData(oldPropDef, convertConstraintsToString(constraints)); - Either updateResult = titanGenericDao.updateNode(node, PropertyData.class); + Either updateResult = janusGraphGenericDao + .updateNode(node, PropertyData.class); if (updateResult.isRight()) { return updateResult.right().value(); } } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } /** @@ -703,7 +713,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe oldPropDef.setDescription(newPropDef.getDescription()); oldPropDef.setRequired(newPropDef.isRequired()); - // Type is updated to fix possible null type issue in TITAN DB + // Type is updated to fix possible null type issue in janusGraph DB oldPropDef.setType(newPropDef.getType()); } @@ -723,7 +733,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * @param unchangedPropsData * @return */ - private Either, TitanOperationStatus> addPropertiesToElementType(NodeTypeEnum nodeType, String uniqueId, Map newProperties, Map unchangedPropsData) { + private Either, JanusGraphOperationStatus> addPropertiesToElementType(NodeTypeEnum nodeType, String uniqueId, Map newProperties, Map unchangedPropsData) { return addPropertiesToElementType(uniqueId, nodeType, newProperties) .left() .map(m -> { @@ -735,28 +745,28 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe public Either, StorageOperationStatus> deleteAllPropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) { - Either, TitanOperationStatus> propertiesOfNodeRes = findPropertiesOfNode(nodeType, uniqueId); + Either, JanusGraphOperationStatus> propertiesOfNodeRes = findPropertiesOfNode(nodeType, uniqueId); if (propertiesOfNodeRes.isRight()) { - TitanOperationStatus status = propertiesOfNodeRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = propertiesOfNodeRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { return Either.right(StorageOperationStatus.OK); } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } Map value = propertiesOfNodeRes.left().value(); for (PropertyDefinition propertyDefinition : value.values()) { String propertyUid = propertyDefinition.getUniqueId(); - Either deletePropertyRes = deletePropertyFromGraph(propertyUid); + Either deletePropertyRes = deletePropertyFromGraph(propertyUid); if (deletePropertyRes.isRight()) { log.error("Failed to delete property with id {}", propertyUid); - TitanOperationStatus status = deletePropertyRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; + JanusGraphOperationStatus status = deletePropertyRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } } @@ -855,13 +865,13 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return rules; } - public ImmutablePair findPropertyValue(String resourceInstanceId, String propertyId) { + public ImmutablePair findPropertyValue(String resourceInstanceId, String propertyId) { log.debug("Going to check whether the property {} already added to resource instance {}", propertyId, resourceInstanceId); - Either, TitanOperationStatus> getAllRes = this.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceId); + Either, JanusGraphOperationStatus> getAllRes = this.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceId); if (getAllRes.isRight()) { - TitanOperationStatus status = getAllRes.right().value(); + JanusGraphOperationStatus status = getAllRes.right().value(); log.trace("After fetching all properties of resource instance {}. Status is {}", resourceInstanceId, status); return new ImmutablePair<>(status, null); } @@ -874,12 +884,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe log.trace("Go over property {} under resource instance {}. valueUniqueId = {}", propertyUniqueId, resourceInstanceId, valueUniqueUid); if (propertyId.equals(propertyUniqueId) && valueUniqueUid != null) { log.debug("The property {} already created under resource instance {}", propertyId, resourceInstanceId); - return new ImmutablePair<>(TitanOperationStatus.ALREADY_EXIST, valueUniqueUid); + return new ImmutablePair<>(JanusGraphOperationStatus.ALREADY_EXIST, valueUniqueUid); } } } - return new ImmutablePair<>(TitanOperationStatus.NOT_FOUND, null); + return new ImmutablePair<>(JanusGraphOperationStatus.NOT_FOUND, null); } @@ -960,45 +970,49 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * @param resourceInstanceUid * @return */ - public Either, TitanOperationStatus> getAllPropertiesOfResourceInstanceOnlyPropertyDefId(String resourceInstanceUid) { + public Either, JanusGraphOperationStatus> getAllPropertiesOfResourceInstanceOnlyPropertyDefId(String resourceInstanceUid) { return getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceUid, NodeTypeEnum.ResourceInstance); } - public Either removePropertyOfResourceInstance(String propertyValueUid, String resourceInstanceId) { + public Either removePropertyOfResourceInstance(String propertyValueUid, String resourceInstanceId) { - Either findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class); + Either findResInstanceRes = janusGraphGenericDao + .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; + JanusGraphOperationStatus status = findResInstanceRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } return Either.right(status); } - Either findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, PropertyValueData.class); + Either findPropertyDefRes = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, PropertyValueData.class); if (findPropertyDefRes.isRight()) { - TitanOperationStatus status = findPropertyDefRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; + JanusGraphOperationStatus status = findPropertyDefRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } return Either.right(status); } - Either relation = titanGenericDao.getRelation(findResInstanceRes.left().value(), findPropertyDefRes.left().value(), GraphEdgeLabels.PROPERTY_VALUE); + Either relation = janusGraphGenericDao + .getRelation(findResInstanceRes.left().value(), findPropertyDefRes.left().value(), GraphEdgeLabels.PROPERTY_VALUE); if (relation.isRight()) { // TODO: add error in case of error - TitanOperationStatus status = relation.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; + JanusGraphOperationStatus status = relation.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } return Either.right(status); } - Either deleteNode = titanGenericDao.deleteNode(findPropertyDefRes.left().value(), PropertyValueData.class); + Either deleteNode = janusGraphGenericDao + .deleteNode(findPropertyDefRes.left().value(), PropertyValueData.class); if (deleteNode.isRight()) { return Either.right(deleteNode.right().value()); } @@ -1013,11 +1027,11 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe try { - Either eitherStatus = this.removePropertyOfResourceInstance(propertyValueUid, resourceInstanceId); + Either eitherStatus = this.removePropertyOfResourceInstance(propertyValueUid, resourceInstanceId); if (eitherStatus.isRight()) { log.error("Failed to remove property value {} from resource instance {} in Graph. status is {}", propertyValueUid, resourceInstanceId, eitherStatus.right().value().name()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value())); return result; } else { PropertyValueData propertyValueData = eitherStatus.left().value(); @@ -1036,10 +1050,10 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (!inTransaction) { if (result == null || result.isRight()) { log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } @@ -1111,7 +1125,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (ToscaPropertyType.isValidType(property.getType()) == null) { - Either definedInDataTypes = isDefinedInDataTypes(property.getType()); + Either definedInDataTypes = isDefinedInDataTypes(property.getType()); if (definedInDataTypes.isRight()) { return false; @@ -1164,44 +1178,50 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } - public Either, TitanOperationStatus> getAllPropertiesOfResourceInstanceOnlyPropertyDefId(String resourceInstanceUid, NodeTypeEnum instanceNodeType) { + public Either, JanusGraphOperationStatus> getAllPropertiesOfResourceInstanceOnlyPropertyDefId(String resourceInstanceUid, NodeTypeEnum instanceNodeType) { - Either findResInstanceRes = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid); + Either findResInstanceRes = janusGraphGenericDao + .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid); if (findResInstanceRes.isRight()) { - TitanOperationStatus status = findResInstanceRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; + JanusGraphOperationStatus status = findResInstanceRes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } return Either.right(status); } - Either>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, GraphEdgeLabels.PROPERTY_VALUE); + Either>, JanusGraphOperationStatus> propertyImplNodes = janusGraphGenericDao + .getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, GraphEdgeLabels.PROPERTY_VALUE); if (propertyImplNodes.isRight()) { - TitanOperationStatus status = propertyImplNodes.right().value(); + JanusGraphOperationStatus status = propertyImplNodes.right().value(); return Either.right(status); } - List> list = propertyImplNodes.left().value(); + List> list = propertyImplNodes.left().value(); if (list == null || list.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); + return Either.right(JanusGraphOperationStatus.NOT_FOUND); } List result = new ArrayList<>(); - for (ImmutablePair propertyValue : list) { - TitanVertex propertyValueDataVertex = propertyValue.getLeft(); - String propertyValueUid = (String) titanGenericDao.getProperty(propertyValueDataVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - String value = (String) titanGenericDao.getProperty(propertyValueDataVertex, GraphPropertiesDictionary.VALUE.getProperty()); - - ImmutablePair propertyDefPair = titanGenericDao.getChildVertex(propertyValueDataVertex, GraphEdgeLabels.PROPERTY_IMPL); + for (ImmutablePair propertyValue : list) { + JanusGraphVertex propertyValueDataVertex = propertyValue.getLeft(); + String propertyValueUid = (String) janusGraphGenericDao + .getProperty(propertyValueDataVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + String value = (String) janusGraphGenericDao + .getProperty(propertyValueDataVertex, GraphPropertiesDictionary.VALUE.getProperty()); + + ImmutablePair propertyDefPair = janusGraphGenericDao + .getChildVertex(propertyValueDataVertex, GraphEdgeLabels.PROPERTY_IMPL); if (propertyDefPair == null) { - return Either.right(TitanOperationStatus.NOT_FOUND); + return Either.right(JanusGraphOperationStatus.NOT_FOUND); } - Map properties = titanGenericDao.getProperties(propertyValueDataVertex); + Map properties = janusGraphGenericDao.getProperties(propertyValueDataVertex); PropertyValueData propertyValueData = GraphElementFactory.createElement(NodeTypeEnum.PropertyValue.getName(), GraphElementTypeEnum.Node, properties, PropertyValueData.class); - String propertyUniqueId = (String) titanGenericDao.getProperty(propertyDefPair.left, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + String propertyUniqueId = (String) janusGraphGenericDao + .getProperty(propertyDefPair.left, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty(); // set property original unique id @@ -1230,7 +1250,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * @param defaultValue * @return */ - public Either findDefaultValueFromSecondPosition(List pathOfComponentInstances, String propertyUniqueId, String defaultValue) { + public Either findDefaultValueFromSecondPosition(List pathOfComponentInstances, String propertyUniqueId, String defaultValue) { log.trace("In find default value: path= {} propertyUniqId={} defaultValue= {}", pathOfComponentInstances, propertyUniqueId, defaultValue); @@ -1243,13 +1263,13 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe for (int i = 1; i < pathOfComponentInstances.size(); i++) { String compInstanceId = pathOfComponentInstances.get(i); - Either, TitanOperationStatus> propertyValuesResult = this.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(compInstanceId, NodeTypeEnum.ResourceInstance); + Either, JanusGraphOperationStatus> propertyValuesResult = this.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(compInstanceId, NodeTypeEnum.ResourceInstance); log.trace("After fetching properties values of component instance {}. {}", compInstanceId, propertyValuesResult); if (propertyValuesResult.isRight()) { - TitanOperationStatus status = propertyValuesResult.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = propertyValuesResult.right().value(); + if (status != JanusGraphOperationStatus.NOT_FOUND) { return Either.right(status); } else { continue; @@ -1459,7 +1479,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * @param dataTypeDefinition * @return */ - private Either addDataTypeToGraph(DataTypeDefinition dataTypeDefinition) { + private Either addDataTypeToGraph(DataTypeDefinition dataTypeDefinition) { log.debug("Got data type {}", dataTypeDefinition); @@ -1468,11 +1488,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe DataTypeData dataTypeData = buildDataTypeData(dataTypeDefinition, dtUniqueId); log.debug("Before adding data type to graph. dataTypeData = {}", dataTypeData); - Either createDataTypeResult = titanGenericDao.createNode(dataTypeData, DataTypeData.class); + Either createDataTypeResult = janusGraphGenericDao + .createNode(dataTypeData, DataTypeData.class); log.debug("After adding data type to graph. status is = {}", createDataTypeResult); if (createDataTypeResult.isRight()) { - TitanOperationStatus operationStatus = createDataTypeResult.right().value(); + JanusGraphOperationStatus operationStatus = createDataTypeResult.right().value(); log.debug("Failed to data type {} to graph. status is {}", dataTypeDefinition.getName(), operationStatus); BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("AddDataType", NodeTypeEnum.DataType.getName()); return Either.right(operationStatus); @@ -1480,7 +1501,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe DataTypeData resultCTD = createDataTypeResult.left().value(); List properties = dataTypeDefinition.getProperties(); - Either, TitanOperationStatus> addPropertiesToDataType = addPropertiesToDataType(resultCTD.getUniqueId(), properties); + Either, JanusGraphOperationStatus> addPropertiesToDataType = addPropertiesToDataType(resultCTD.getUniqueId(), properties); if (addPropertiesToDataType.isRight()) { log.debug("Failed add properties {} to data type {}", properties, dataTypeDefinition.getName()); return Either.right(addPropertiesToDataType.right().value()); @@ -1493,7 +1514,8 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe String deriveFromUid = UniqueIdBuilder.buildDataTypeUid(derivedFrom); UniqueIdData to = new UniqueIdData(NodeTypeEnum.DataType, deriveFromUid); - Either createRelation = titanGenericDao.createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null); + Either createRelation = janusGraphGenericDao + .createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null); log.debug("After create relation between capability type {} to its parent {}. status is {}", dtUniqueId, derivedFrom, createRelation); if (createRelation.isRight()) { return Either.right(createRelation.right().value()); @@ -1528,7 +1550,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * @param properties * @return */ - private Either, TitanOperationStatus> addPropertiesToDataType(String uniqueId, List properties) { + private Either, JanusGraphOperationStatus> addPropertiesToDataType(String uniqueId, List properties) { Map propertiesData = new HashMap<>(); @@ -1537,7 +1559,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe String propertyName = propertyDefinition.getName(); String propertyType = propertyDefinition.getType(); - Either validPropertyType = isValidPropertyType(propertyType); + Either validPropertyType = isValidPropertyType(propertyType); if (validPropertyType.isRight()) { log.debug("Data type {} contains invalid property type {}", uniqueId, propertyType); return Either.right(validPropertyType.right().value()); @@ -1545,12 +1567,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe Boolean isValid = validPropertyType.left().value(); if (isValid == null || !isValid.booleanValue()) { log.debug("Data type {} contains invalid property type {}", uniqueId, propertyType); - return Either.right(TitanOperationStatus.INVALID_TYPE); + return Either.right(JanusGraphOperationStatus.INVALID_TYPE); } - Either addPropertyToNodeType = this.addPropertyToNodeType(propertyName, propertyDefinition, NodeTypeEnum.DataType, uniqueId); + Either addPropertyToNodeType = this.addPropertyToNodeType(propertyName, propertyDefinition, NodeTypeEnum.DataType, uniqueId); if (addPropertyToNodeType.isRight()) { - TitanOperationStatus operationStatus = addPropertyToNodeType.right().value(); + JanusGraphOperationStatus operationStatus = addPropertyToNodeType.right().value(); log.debug("Failed to associate data type {} to property {} in graph. status is {}", uniqueId, propertyName, operationStatus); BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToDataType", "Failed to associate property to data type. Status is " + operationStatus, ErrorSeverity.ERROR); return Either.right(operationStatus); @@ -1563,9 +1585,10 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe long modificationTime = System.currentTimeMillis(); dataTypeData.getDataTypeDataDefinition().setModificationTime(modificationTime); - Either updateNode = titanGenericDao.updateNode(dataTypeData, DataTypeData.class); + Either updateNode = janusGraphGenericDao + .updateNode(dataTypeData, DataTypeData.class); if (updateNode.isRight()) { - TitanOperationStatus operationStatus = updateNode.right().value(); + JanusGraphOperationStatus operationStatus = updateNode.right().value(); log.debug("Failed to update modification time data type {} from graph. status is {}", uniqueId, operationStatus); BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToDataType", "Failed to fetch data type. Status is " + operationStatus, ErrorSeverity.ERROR); return Either.right(operationStatus); @@ -1585,14 +1608,15 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * @param uniqueId * @return */ - public Either getDataTypeByUid(String uniqueId) { + public Either getDataTypeByUid(String uniqueId) { - Either result = null; + Either result = null; - Either dataTypesRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class); + Either dataTypesRes = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class); if (dataTypesRes.isRight()) { - TitanOperationStatus status = dataTypesRes.right().value(); + JanusGraphOperationStatus status = dataTypesRes.right().value(); log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status); return Either.right(status); } @@ -1600,20 +1624,22 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe DataTypeData ctData = dataTypesRes.left().value(); DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition()); - TitanOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition); - if (propertiesStatus != TitanOperationStatus.OK) { + JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition); + if (propertiesStatus != JanusGraphOperationStatus.OK) { log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId); return Either.right(propertiesStatus); } - Either, TitanOperationStatus> parentNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType, + Either, JanusGraphOperationStatus> parentNode = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType, DataTypeData.class); log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode); if (parentNode.isRight()) { - TitanOperationStatus titanOperationStatus = parentNode.right().value(); - if (titanOperationStatus != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId, titanOperationStatus); - result = Either.right(titanOperationStatus); + JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value(); + if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) { + log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId, + janusGraphOperationStatus); + result = Either.right(janusGraphOperationStatus); return result; } } else { @@ -1622,7 +1648,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe DataTypeData parentCT = immutablePair.getKey(); String parentUniqueId = parentCT.getUniqueId(); - Either dataTypeByUid = getDataTypeByUid(parentUniqueId); + Either dataTypeByUid = getDataTypeByUid(parentUniqueId); if (dataTypeByUid.isRight()) { return Either.right(dataTypeByUid.right().value()); @@ -1638,16 +1664,17 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return result; } - private TitanOperationStatus fillProperties(String uniqueId, DataTypeDefinition dataTypeDefinition) { + private JanusGraphOperationStatus fillProperties(String uniqueId, DataTypeDefinition dataTypeDefinition) { - Either, TitanOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(NodeTypeEnum.DataType, uniqueId); + Either, JanusGraphOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(NodeTypeEnum.DataType, uniqueId); if (findPropertiesOfNode.isRight()) { - TitanOperationStatus titanOperationStatus = findPropertiesOfNode.right().value(); - log.debug("After looking for properties of vertex {}. status is {}", uniqueId, titanOperationStatus); - if (TitanOperationStatus.NOT_FOUND.equals(titanOperationStatus)) { - return TitanOperationStatus.OK; + JanusGraphOperationStatus janusGraphOperationStatus = findPropertiesOfNode.right().value(); + log.debug("After looking for properties of vertex {}. status is {}", uniqueId, + janusGraphOperationStatus); + if (JanusGraphOperationStatus.NOT_FOUND.equals(janusGraphOperationStatus)) { + return JanusGraphOperationStatus.OK; } else { - return titanOperationStatus; + return janusGraphOperationStatus; } } else { Map properties = findPropertiesOfNode.left().value(); @@ -1663,7 +1690,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } dataTypeDefinition.setProperties(listOfProps); } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } } @@ -1673,12 +1700,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe try { - Either eitherStatus = addDataTypeToGraph(dataTypeDefinition); + Either eitherStatus = addDataTypeToGraph(dataTypeDefinition); if (eitherStatus.isRight()) { log.debug("Failed to add data type {} to Graph. status is {}", dataTypeDefinition, eitherStatus.right().value().name()); BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("AddDataType", "DataType"); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value())); return result; } else { DataTypeData capabilityTypeData = eitherStatus.left().value(); @@ -1692,10 +1719,10 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (!inTransaction) { if (result == null || result.isRight()) { log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } @@ -1714,14 +1741,14 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe try { String dtUid = UniqueIdBuilder.buildDataTypeUid(name); - Either ctResult = this.getDataTypeByUid(dtUid); + Either ctResult = this.getDataTypeByUid(dtUid); if (ctResult.isRight()) { - TitanOperationStatus status = ctResult.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = ctResult.right().value(); + if (status != JanusGraphOperationStatus.NOT_FOUND) { log.error("Failed to retrieve information on capability type {} status is {}", name, status); } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(ctResult.right().value())); return result; } @@ -1732,10 +1759,10 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (!inTransaction) { if (result == null || result.isRight()) { log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } @@ -1758,14 +1785,14 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe try { String uid = UniqueIdBuilder.buildDataTypeUid(name); - Either ctResult = this.getDataTypeByUidWithoutDerivedDataTypes(uid); + Either ctResult = this.getDataTypeByUidWithoutDerivedDataTypes(uid); if (ctResult.isRight()) { - TitanOperationStatus status = ctResult.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = ctResult.right().value(); + if (status != JanusGraphOperationStatus.NOT_FOUND) { log.error("Failed to retrieve information on capability type {} status is {}", name, status); } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(ctResult.right().value())); return result; } @@ -1776,22 +1803,23 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (!inTransaction) { if (result == null || result.isRight()) { log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } } - public Either getDataTypeByUidWithoutDerivedDataTypes(String uniqueId) { + public Either getDataTypeByUidWithoutDerivedDataTypes(String uniqueId) { - Either dataTypesRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class); + Either dataTypesRes = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class); if (dataTypesRes.isRight()) { - TitanOperationStatus status = dataTypesRes.right().value(); + JanusGraphOperationStatus status = dataTypesRes.right().value(); log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status); return Either.right(status); } @@ -1799,8 +1827,8 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe DataTypeData ctData = dataTypesRes.left().value(); DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition()); - TitanOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition); - if (propertiesStatus != TitanOperationStatus.OK) { + JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition); + if (propertiesStatus != JanusGraphOperationStatus.OK) { log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId); return Either.right(propertiesStatus); } @@ -1821,7 +1849,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return new DataTypeDefinition(dataTypeData.getDataTypeDataDefinition()); } - private Either isValidPropertyType(String propertyType) { + private Either isValidPropertyType(String propertyType) { if (propertyType == null || propertyType.isEmpty()) { return Either.left(false); @@ -1835,13 +1863,13 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } } - public Either isDefinedInDataTypes(String propertyType) { + public Either isDefinedInDataTypes(String propertyType) { String dataTypeUid = UniqueIdBuilder.buildDataTypeUid(propertyType); - Either dataTypeByUid = getDataTypeByUid(dataTypeUid); + Either dataTypeByUid = getDataTypeByUid(dataTypeUid); if (dataTypeByUid.isRight()) { - TitanOperationStatus status = dataTypeByUid.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = dataTypeByUid.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { return Either.left(false); } return Either.right(status); @@ -1851,15 +1879,16 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } - public Either, TitanOperationStatus> getAllDataTypes() { + public Either, JanusGraphOperationStatus> getAllDataTypes() { Map dataTypes = new HashMap<>(); - Either, TitanOperationStatus> result = Either.left(dataTypes); + Either, JanusGraphOperationStatus> result = Either.left(dataTypes); - Either, TitanOperationStatus> getAllDataTypes = titanGenericDao.getByCriteria(NodeTypeEnum.DataType, null, DataTypeData.class); + Either, JanusGraphOperationStatus> getAllDataTypes = janusGraphGenericDao + .getByCriteria(NodeTypeEnum.DataType, null, DataTypeData.class); if (getAllDataTypes.isRight()) { - TitanOperationStatus status = getAllDataTypes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = getAllDataTypes.right().value(); + if (status != JanusGraphOperationStatus.NOT_FOUND) { return Either.right(status); } else { return result; @@ -1877,11 +1906,11 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe for (DataTypeData dataTypeData : list) { log.trace("Going to fetch data type {}. uid is {}", dataTypeData.getDataTypeDataDefinition().getName(), dataTypeData.getUniqueId()); - Either dataTypeByUid = this.getAndAddDataTypeByUid(dataTypeData.getUniqueId(), dataTypes); + Either dataTypeByUid = this.getAndAddDataTypeByUid(dataTypeData.getUniqueId(), dataTypes); if (dataTypeByUid.isRight()) { - TitanOperationStatus status = dataTypeByUid.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; + JanusGraphOperationStatus status = dataTypeByUid.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } return Either.right(status); } @@ -1909,18 +1938,19 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * @param uniqueId * @return */ - private Either getAndAddDataTypeByUid(String uniqueId, Map allDataTypes) { + private Either getAndAddDataTypeByUid(String uniqueId, Map allDataTypes) { - Either result = null; + Either result = null; if (allDataTypes.containsKey(uniqueId)) { return Either.left(allDataTypes.get(uniqueId)); } - Either dataTypesRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class); + Either dataTypesRes = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class); if (dataTypesRes.isRight()) { - TitanOperationStatus status = dataTypesRes.right().value(); + JanusGraphOperationStatus status = dataTypesRes.right().value(); log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status); return Either.right(status); } @@ -1928,8 +1958,8 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe DataTypeData ctData = dataTypesRes.left().value(); DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition()); - TitanOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition); - if (propertiesStatus != TitanOperationStatus.OK) { + JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition); + if (propertiesStatus != JanusGraphOperationStatus.OK) { log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId); return Either.right(propertiesStatus); } @@ -1945,14 +1975,16 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return Either.left(dataTypeDefinition); } - Either, TitanOperationStatus> parentNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType, + Either, JanusGraphOperationStatus> parentNode = janusGraphGenericDao + .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType, DataTypeData.class); log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode); if (parentNode.isRight()) { - TitanOperationStatus titanOperationStatus = parentNode.right().value(); - if (titanOperationStatus != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId, titanOperationStatus); - result = Either.right(titanOperationStatus); + JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value(); + if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) { + log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId, + janusGraphOperationStatus); + result = Either.right(janusGraphOperationStatus); return result; } } else { @@ -1961,7 +1993,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe DataTypeData parentCT = immutablePair.getKey(); String parentUniqueId = parentCT.getUniqueId(); - Either dataTypeByUid = getDataTypeByUid(parentUniqueId); + Either dataTypeByUid = getDataTypeByUid(parentUniqueId); if (dataTypeByUid.isRight()) { return Either.right(dataTypeByUid.right().value()); @@ -1977,12 +2009,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return result; } - private Either getDataTypeUsingName(String name) { + private Either getDataTypeUsingName(String name) { String uid = UniqueIdBuilder.buildDataTypeUid(name); return getDataTypeByUid(uid); } - public Either checkInnerType(PropertyDataDefinition propDataDef) { + public Either checkInnerType(PropertyDataDefinition propDataDef) { String propertyType = propDataDef.getType(); @@ -1991,12 +2023,13 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return getInnerType(type, propDataDef::getSchema); } - public Either, TitanOperationStatus> getAllDataTypeNodes() { - Either, TitanOperationStatus> getAllDataTypes = titanGenericDao.getByCriteria(NodeTypeEnum.DataType, null, DataTypeData.class); + public Either, JanusGraphOperationStatus> getAllDataTypeNodes() { + Either, JanusGraphOperationStatus> getAllDataTypes = janusGraphGenericDao + .getByCriteria(NodeTypeEnum.DataType, null, DataTypeData.class); if (getAllDataTypes.isRight()) { - TitanOperationStatus status = getAllDataTypes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; + JanusGraphOperationStatus status = getAllDataTypes.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.OK; return Either.right(status); } } @@ -2047,11 +2080,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe .bind(props -> getAllDerivedFromChainProperties(uniqueId, nodeType, clazz, props.values())); } - private Either, StorageOperationStatus> handleNotFoundProperties(TitanOperationStatus titanOperationStatus) { - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + private Either, StorageOperationStatus> handleNotFoundProperties(JanusGraphOperationStatus janusGraphOperationStatus) { + if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) { return Either.left(new HashMap<>()); } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + janusGraphOperationStatus)); } private Either, StorageOperationStatus> getAllDerivedFromChainProperties(String uniqueId, NodeTypeEnum nodeType, Class clazz, Collection nodeProps) { @@ -2060,10 +2094,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe Either derivedFrom; while ((derivedFrom = derivedFromOperation.getDerivedFromChild(currentNodeUid, nodeType, clazz)).isLeft()) { currentNodeUid = derivedFrom.left().value().getUniqueId(); - TitanOperationStatus titanOperationStatus = fillPropertiesList(currentNodeUid, nodeType, accumulatedProps::addAll); - if (titanOperationStatus != TitanOperationStatus.OK) { + JanusGraphOperationStatus + janusGraphOperationStatus = fillPropertiesList(currentNodeUid, nodeType, accumulatedProps::addAll); + if (janusGraphOperationStatus != JanusGraphOperationStatus.OK) { log.debug("failed to fetch properties for type {} with id {}", nodeType, currentNodeUid); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( + janusGraphOperationStatus)); } } StorageOperationStatus getDerivedResult = derivedFrom.right().value(); @@ -2077,8 +2113,8 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe /* * @Override public PropertyOperation getPropertyOperation() { return this; } */ - public TitanOperationStatus fillPropertiesList(String uniqueId, NodeTypeEnum nodeType, Consumer> propertySetter) { - Either, TitanOperationStatus> findPropertiesRes = findPropertiesifExist(uniqueId, nodeType); + public JanusGraphOperationStatus fillPropertiesList(String uniqueId, NodeTypeEnum nodeType, Consumer> propertySetter) { + Either, JanusGraphOperationStatus> findPropertiesRes = findPropertiesifExist(uniqueId, nodeType); if (findPropertiesRes.isRight()) { return findPropertiesRes.right().value(); } @@ -2087,14 +2123,14 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe List propertiesAsList = properties.entrySet().stream().map(Entry::getValue).collect(Collectors.toList()); propertySetter.accept(propertiesAsList); } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } - Either, TitanOperationStatus> findPropertiesifExist(String uniqueId, NodeTypeEnum nodeType){ - Either, TitanOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(nodeType, uniqueId); + Either, JanusGraphOperationStatus> findPropertiesifExist(String uniqueId, NodeTypeEnum nodeType){ + Either, JanusGraphOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(nodeType, uniqueId); if (findPropertiesOfNode.isRight()) { log.debug("After looking for properties of vertex {}. status is {}", uniqueId, findPropertiesOfNode.right().value()); - if(findPropertiesOfNode.right().value() == TitanOperationStatus.NOT_FOUND) + if(findPropertiesOfNode.right().value() == JanusGraphOperationStatus.NOT_FOUND) return Either.left(Maps.newHashMap()); return findPropertiesOfNode; } @@ -2111,7 +2147,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * * @return */ - protected Either, TitanOperationStatus> addPropertiesToElementType(String uniqueId, NodeTypeEnum nodeType, Map propertiesMap) { + protected Either, JanusGraphOperationStatus> addPropertiesToElementType(String uniqueId, NodeTypeEnum nodeType, Map propertiesMap) { Map propertiesData = new HashMap<>(); @@ -2120,10 +2156,10 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe for (Entry propertyDefinitionEntry : propertiesMap.entrySet()) { String propertyName = propertyDefinitionEntry.getKey(); - Either addPropertyToNodeType = this.addPropertyToNodeType(propertyName, propertyDefinitionEntry.getValue(), nodeType, uniqueId); + Either addPropertyToNodeType = this.addPropertyToNodeType(propertyName, propertyDefinitionEntry.getValue(), nodeType, uniqueId); if (addPropertyToNodeType.isRight()) { - TitanOperationStatus operationStatus = addPropertyToNodeType.right().value(); + JanusGraphOperationStatus operationStatus = addPropertyToNodeType.right().value(); log.error("Failed to associate {} {} to property {} in graph. status is {}", nodeType.getName(), uniqueId, propertyName, operationStatus); return Either.right(operationStatus); } @@ -2136,7 +2172,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } - public Either, TitanOperationStatus> addPropertiesToElementType(String uniqueId, NodeTypeEnum elementType, List properties) { + public Either, JanusGraphOperationStatus> addPropertiesToElementType(String uniqueId, NodeTypeEnum elementType, List properties) { Map propMap; if (properties == null) { @@ -2186,30 +2222,30 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if(MapUtils.isNotEmpty(newDescriptions)){ - TitanOperationStatus updatePropertiesStatus = updateDataTypePropertyDescriptions(oldDataTypeDefinition.getUniqueId(), newDescriptions); - if (updatePropertiesStatus != TitanOperationStatus.OK) { + JanusGraphOperationStatus updatePropertiesStatus = updateDataTypePropertyDescriptions(oldDataTypeDefinition.getUniqueId(), newDescriptions); + if (updatePropertiesStatus != JanusGraphOperationStatus.OK) { log.debug("#updateDataType - Failed to update the descriptions of the properties of the data type {}. Status is {}", oldDataTypeDefinition, updatePropertiesStatus); BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError(UPDATE_DATA_TYPE, PROPERTY); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updatePropertiesStatus)); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updatePropertiesStatus)); return result; } } - Either, TitanOperationStatus> addPropertiesToDataType = addPropertiesToDataType(oldDataTypeDefinition.getUniqueId(), propertiesToAdd); + Either, JanusGraphOperationStatus> addPropertiesToDataType = addPropertiesToDataType(oldDataTypeDefinition.getUniqueId(), propertiesToAdd); if (addPropertiesToDataType.isRight()) { log.debug("Failed to update data type {} to Graph. Status is {}", oldDataTypeDefinition, addPropertiesToDataType.right().value().name()); BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError(UPDATE_DATA_TYPE, PROPERTY); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertiesToDataType.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertiesToDataType.right().value())); return result; } else { - Either dataTypeByUid = this.getDataTypeByUid(oldDataTypeDefinition.getUniqueId()); + Either dataTypeByUid = this.getDataTypeByUid(oldDataTypeDefinition.getUniqueId()); if (dataTypeByUid.isRight()) { - TitanOperationStatus status = addPropertiesToDataType.right().value(); + JanusGraphOperationStatus status = addPropertiesToDataType.right().value(); log.debug("Failed to get data type {} after update. Status is {}", oldDataTypeDefinition.getUniqueId(), status.name()); BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(UPDATE_DATA_TYPE, PROPERTY, status.name()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } else { result = Either.left(dataTypeByUid.left().value()); } @@ -2221,10 +2257,10 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (!inTransaction) { if (result == null || result.isRight()) { log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } @@ -2364,14 +2400,15 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * @return */ public Either increaseAndGetObjInstancePropertyCounter(String instanceId, NodeTypeEnum nodeType) { - Either graphResult = titanGenericDao.getGraph(); + Either graphResult = janusGraphGenericDao.getGraph(); if (graphResult.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(graphResult.right().value())); } - Either vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), instanceId); + Either vertexService = janusGraphGenericDao + .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), instanceId); if (vertexService.isRight()) { log.debug("failed to fetch vertex of resource instance for id = {}", instanceId); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value())); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexService.right().value())); } Vertex vertex = vertexService.left().value(); @@ -2388,12 +2425,13 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } - public Either, TitanOperationStatus> validatePropertiesUniqueness(Map inheritedProperties, List properties) { - Either, TitanOperationStatus> result = Either.left(properties); + public Either, JanusGraphOperationStatus> validatePropertiesUniqueness(Map inheritedProperties, List properties) { + Either, JanusGraphOperationStatus> result = Either.left(properties); for (PropertyDefinition property : properties) { - TitanOperationStatus status = validatePropertyUniqueness(inheritedProperties, property); - if (status != TitanOperationStatus.OK) { + JanusGraphOperationStatus + status = validatePropertyUniqueness(inheritedProperties, property); + if (status != JanusGraphOperationStatus.OK) { result = Either.right(status); break; } @@ -2406,16 +2444,16 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * Validates uniqueness of examined property by comparing it with properties in propertiesOfType * and updates if need type and inner type of the property. */ - private TitanOperationStatus validatePropertyUniqueness(Map inheritedProperties, PropertyDefinition property) { + private JanusGraphOperationStatus validatePropertyUniqueness(Map inheritedProperties, PropertyDefinition property) { String propertyName = property.getName(); String propertyType = property.getType(); - TitanOperationStatus result = TitanOperationStatus.OK; + JanusGraphOperationStatus result = JanusGraphOperationStatus.OK; if (inheritedProperties.containsKey(propertyName)) { PropertyDefinition defaultProperty = inheritedProperties.get(propertyName); if (typesMismatch(propertyType, defaultProperty.getType())) { log.error("#validatePropertyUniqueness - Property with name {} and different type already exists.", propertyName); - result = TitanOperationStatus.PROPERTY_NAME_ALREADY_EXISTS; + result = JanusGraphOperationStatus.PROPERTY_NAME_ALREADY_EXISTS; } else { property.setType(defaultProperty.getType()); String innerType = defaultProperty.getSchemaType(); @@ -2435,22 +2473,23 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } - public Either, TitanOperationStatus> getAllTypePropertiesFromAllDerivedFrom(String nextParentUid, - NodeTypeEnum nodeType, - Class clazz) { + public Either, JanusGraphOperationStatus> getAllTypePropertiesFromAllDerivedFrom(String nextParentUid, + NodeTypeEnum nodeType, + Class clazz) { Map allProperies = new HashMap<>(); return getTypePropertiesFromDerivedFromRecursively(nextParentUid, allProperies, nodeType, clazz); } - private Either, TitanOperationStatus> getTypePropertiesFromDerivedFromRecursively(String nextParentUid, - Map allProperies, - NodeTypeEnum nodeType, - Class clazz) { - TitanOperationStatus error; - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), + private Either, JanusGraphOperationStatus> getTypePropertiesFromDerivedFromRecursively(String nextParentUid, + Map allProperies, + NodeTypeEnum nodeType, + Class clazz) { + JanusGraphOperationStatus error; + Either>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao + .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), nextParentUid, GraphEdgeLabels.DERIVED_FROM, nodeType, clazz); if (childrenNodes.isRight()) { - if (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND) { + if (childrenNodes.right().value() != JanusGraphOperationStatus.NOT_FOUND) { error = childrenNodes.right().value(); log.debug("#getTypePropertiesFromDerivedFromRecursively - Couldn't fetch derived from node with UID {}, error: {}", nextParentUid, error); return Either.right(error); @@ -2461,8 +2500,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } } else { - Either, TitanOperationStatus> allPropertiesOfTypeRes = findPropertiesOfNode(nodeType, nextParentUid); - if (allPropertiesOfTypeRes.isRight() && !allPropertiesOfTypeRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + Either, JanusGraphOperationStatus> allPropertiesOfTypeRes = findPropertiesOfNode(nodeType, nextParentUid); + if (allPropertiesOfTypeRes.isRight() && !allPropertiesOfTypeRes.right().value().equals( + JanusGraphOperationStatus.NOT_FOUND)) { error = allPropertiesOfTypeRes.right().value(); log.error("#getTypePropertiesFromDerivedFromRecursively - Failed to retrieve properties for node with UID {} from graph. status is {}", nextParentUid, error); return Either.right(error); @@ -2476,10 +2516,11 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return getTypePropertiesFromDerivedFromRecursively(childrenNodes.left().value().get(0).getLeft().getUniqueId(), allProperies, nodeType, clazz); } } - private TitanOperationStatus updateDataTypePropertyDescriptions(String uniqueId, Map newDescriptions) { + private JanusGraphOperationStatus updateDataTypePropertyDescriptions(String uniqueId, Map newDescriptions) { if (MapUtils.isNotEmpty(newDescriptions)) { - Either>, TitanOperationStatus> getDataTypePropertiesRes = titanGenericDao.getChildrenVertecies(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.PROPERTY); + Either>, JanusGraphOperationStatus> getDataTypePropertiesRes = janusGraphGenericDao + .getChildrenVertecies(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.PROPERTY); if(getDataTypePropertiesRes.isRight()){ log.debug("#updateDataTypePropertiesDescriptions - Failed to fetch the property verticies of the Data type {} ", uniqueId); @@ -2490,14 +2531,14 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe .forEach(pair -> setNewDescriptionToVertex(newDescriptions.get(getPropertyNameFromEdge(pair)), pair)); } - return TitanOperationStatus.OK; + return JanusGraphOperationStatus.OK; } - private TitanVertexProperty setNewDescriptionToVertex(String newDescription, ImmutablePair pair) { + private JanusGraphVertexProperty setNewDescriptionToVertex(String newDescription, ImmutablePair pair) { return pair.getLeft().property(GraphPropertiesDictionary.DESCRIPTION.getProperty(), newDescription); } - private String getPropertyNameFromEdge(ImmutablePair pair) { + private String getPropertyNameFromEdge(ImmutablePair pair) { return (String) pair.getRight().property(GraphPropertiesDictionary.NAME.getProperty()).value(); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RelationshipTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RelationshipTypeOperation.java index 13ad7a798c..0eaec1b805 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RelationshipTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RelationshipTypeOperation.java @@ -10,8 +10,8 @@ import org.apache.commons.collections.MapUtils; 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.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.RelationshipTypeDefinition; @@ -39,12 +39,12 @@ public class RelationshipTypeOperation extends AbstractOperation { private static final String FAILED_TO_FETCH_PROPERTIES_OF_RELATIONSHIP_TYPE = "Failed to fetch properties of " + "relationship type {}"; - public Either getRelationshipTypeByName(String name) { + public Either getRelationshipTypeByName(String name) { String uid = UniqueIdBuilder.buildRelationshipTypeUid(name); - Either result = getRelationshipTypeByUid(uid); + Either result = getRelationshipTypeByUid(uid); if (result.isRight()) { - TitanOperationStatus status = result.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = result.right().value(); + if (status != JanusGraphOperationStatus.NOT_FOUND) { logger.error("Failed to get information on relationship type {} status is {}", name, status); } return Either.right(status); @@ -52,16 +52,16 @@ public class RelationshipTypeOperation extends AbstractOperation { return Either.left(result.left().value()); } - public Either getRelationshipTypeByUid(String uniqueId) { + public Either getRelationshipTypeByUid(String uniqueId) { - Either result; + Either result; - Either relationshipTypesRes = - titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType( + Either relationshipTypesRes = + janusGraphGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType( NodeTypeEnum.RelationshipType), uniqueId, RelationshipTypeData.class); if (relationshipTypesRes.isRight()) { - TitanOperationStatus status = relationshipTypesRes.right().value(); + JanusGraphOperationStatus status = relationshipTypesRes.right().value(); logger.debug("Relationship type {} cannot be found in graph. status is {}", uniqueId, status); return Either.right(status); } @@ -70,9 +70,9 @@ public class RelationshipTypeOperation extends AbstractOperation { RelationshipTypeDefinition relationshipTypeDefinition = new RelationshipTypeDefinition(relationshipTypeData.getRelationshipTypeDataDefinition()); - Either, TitanOperationStatus> propertiesStatus = + Either, JanusGraphOperationStatus> propertiesStatus = OperationUtils.fillProperties(uniqueId, propertyOperation, NodeTypeEnum.RelationshipType); - if (propertiesStatus.isRight() && propertiesStatus.right().value() != TitanOperationStatus.OK) { + if (propertiesStatus.isRight() && propertiesStatus.right().value() != JanusGraphOperationStatus.OK) { logger.error("Failed to fetch properties of relationship type {}", uniqueId); return Either.right(propertiesStatus.right().value()); } @@ -81,17 +81,17 @@ public class RelationshipTypeOperation extends AbstractOperation { relationshipTypeDefinition.setProperties(propertiesStatus.left().value()); } - Either, TitanOperationStatus> parentNode = titanGenericDao + Either, JanusGraphOperationStatus> parentNode = janusGraphGenericDao .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.RelationshipType, RelationshipTypeData.class); logger.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode); if (parentNode.isRight()) { - TitanOperationStatus titanOperationStatus = parentNode.right().value(); - if (titanOperationStatus != TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value(); + if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) { logger.error("Failed to find the parent relationship of relationship type {}. status is {}", uniqueId, - titanOperationStatus); - result = Either.right(titanOperationStatus); + janusGraphOperationStatus); + result = Either.right(janusGraphOperationStatus); return result; } } else { @@ -107,27 +107,27 @@ public class RelationshipTypeOperation extends AbstractOperation { private Either validateUpdateProperties( RelationshipTypeDefinition relationshipTypeDefinition) { - TitanOperationStatus error = null; + JanusGraphOperationStatus error = null; if (MapUtils.isNotEmpty(relationshipTypeDefinition.getProperties()) && relationshipTypeDefinition.getDerivedFrom() != null) { - Either, TitanOperationStatus> allPropertiesRes = + Either, JanusGraphOperationStatus> allPropertiesRes = getAllRelationshipTypePropertiesFromAllDerivedFrom(relationshipTypeDefinition.getDerivedFrom()); - if (allPropertiesRes.isRight() && !TitanOperationStatus.NOT_FOUND.equals(allPropertiesRes.right().value())) { + if (allPropertiesRes.isRight() && !JanusGraphOperationStatus.NOT_FOUND.equals(allPropertiesRes.right().value())) { error = allPropertiesRes.right().value(); logger.debug("Couldn't fetch derived from property nodes for relationship type {}, error: {}", relationshipTypeDefinition.getType(), error); } - error = getTitanOperationStatus(relationshipTypeDefinition, error, allPropertiesRes); + error = getJanusGraphOperationStatus(relationshipTypeDefinition, error, allPropertiesRes); } if (error == null) { return Either.left(relationshipTypeDefinition); } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error)); } - private TitanOperationStatus getTitanOperationStatus(RelationshipTypeDefinition relationshipTypeDefinition, - TitanOperationStatus error, - Either, TitanOperationStatus> allPropertiesRes) { + private JanusGraphOperationStatus getJanusGraphOperationStatus(RelationshipTypeDefinition relationshipTypeDefinition, + JanusGraphOperationStatus error, + Either, JanusGraphOperationStatus> allPropertiesRes) { if (error == null && !allPropertiesRes.left().value().isEmpty()) { Map derivedFromProperties = allPropertiesRes.left().value(); relationshipTypeDefinition.getProperties().entrySet().stream() @@ -136,7 +136,7 @@ public class RelationshipTypeOperation extends AbstractOperation { List properties = new ArrayList<>(relationshipTypeDefinition.getProperties().values()); - Either, TitanOperationStatus> validatePropertiesRes = + Either, JanusGraphOperationStatus> validatePropertiesRes = propertyOperation.validatePropertiesUniqueness(allPropertiesRes.left().value(), properties); if (validatePropertiesRes.isRight()) { error = validatePropertiesRes.right().value(); @@ -145,7 +145,7 @@ public class RelationshipTypeOperation extends AbstractOperation { return error; } - private Either, TitanOperationStatus> getAllRelationshipTypePropertiesFromAllDerivedFrom( + private Either, JanusGraphOperationStatus> getAllRelationshipTypePropertiesFromAllDerivedFrom( String firstParentType) { return propertyOperation.getAllTypePropertiesFromAllDerivedFrom(firstParentType, NodeTypeEnum.RelationshipType, RelationshipTypeData.class); @@ -185,10 +185,10 @@ public class RelationshipTypeOperation extends AbstractOperation { if (!inTransaction) { if (result == null || result.isRight()) { logger.error("#addRelationshipType - Going to execute rollback on graph."); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { logger.debug("#addRelationshipType - Going to execute commit on graph."); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } @@ -200,15 +200,15 @@ public class RelationshipTypeOperation extends AbstractOperation { Either result; try { - Either ctResult = this.getRelationshipTypeByUid(uniqueId); + Either ctResult = this.getRelationshipTypeByUid(uniqueId); if (ctResult.isRight()) { - TitanOperationStatus status = ctResult.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = ctResult.right().value(); + if (status != JanusGraphOperationStatus.NOT_FOUND) { logger.error("Failed to retrieve information on relationship type {}. status is {}", uniqueId, status); } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value())); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(ctResult.right().value())); return result; } @@ -218,7 +218,7 @@ public class RelationshipTypeOperation extends AbstractOperation { } finally { if (!inTransaction) { logger.debug("Going to execute commit on graph."); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } @@ -232,26 +232,26 @@ public class RelationshipTypeOperation extends AbstractOperation { RelationshipTypeData relationshipTypeData = buildRelationshipTypeData(relationshipTypeDefinition, ctUniqueId); logger.debug("Before adding relationship type to graph. relationshipTypeData = {}", relationshipTypeData); - Either createCTResult = - titanGenericDao.createNode(relationshipTypeData, RelationshipTypeData.class); + Either createCTResult = + janusGraphGenericDao.createNode(relationshipTypeData, RelationshipTypeData.class); logger.debug("After adding relationship type to graph. status is = {}", createCTResult); if (createCTResult.isRight()) { - TitanOperationStatus operationStatus = createCTResult.right().value(); + JanusGraphOperationStatus operationStatus = createCTResult.right().value(); logger.error("Failed to relationship type {} to graph. status is {}", relationshipTypeDefinition.getType(), operationStatus); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationStatus)); } RelationshipTypeData resultCTD = createCTResult.left().value(); Map propertiesMap = relationshipTypeDefinition.getProperties(); - Either, TitanOperationStatus> addPropertiesToRelationshipType = propertyOperation + Either, JanusGraphOperationStatus> addPropertiesToRelationshipType = propertyOperation .addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.RelationshipType, propertiesMap); if (addPropertiesToRelationshipType.isRight()) { logger.error("Failed add properties {} to relationship {}", propertiesMap, relationshipTypeDefinition.getType()); return Either.right(DaoStatusConverter - .convertTitanStatusToStorageStatus(addPropertiesToRelationshipType.right().value())); + .convertJanusGraphStatusToStorageStatus(addPropertiesToRelationshipType.right().value())); } return addDerivedFromRelation(relationshipTypeDefinition, ctUniqueId) @@ -288,13 +288,13 @@ public class RelationshipTypeOperation extends AbstractOperation { + "{}", relationshipTypeDefinition.getType(), derivedFrom); return getRelationshipTypeByType(derivedFrom) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus) + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus) .left() .bind(derivedFromRelationship -> derivedFromOperation.addDerivedFromRelation(relationshipTypeUniqueId, derivedFromRelationship.getUniqueId(), NodeTypeEnum.RelationshipType)); } - private Either getRelationshipTypeByType( + private Either getRelationshipTypeByType( String relationshipType) { // Optimization: In case of Relationship Type its unique ID is the same as type return getRelationshipTypeByUid(relationshipType); @@ -312,9 +312,9 @@ public class RelationshipTypeOperation extends AbstractOperation { } finally { if (!inTransaction) { if (updateRelationshipEither == null || updateRelationshipEither.isRight()) { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } @@ -325,10 +325,10 @@ public class RelationshipTypeOperation extends AbstractOperation { RelationshipTypeDefinition newRelationshipTypeDefinition, RelationshipTypeDefinition oldRelationshipTypeDefinition) { updateRelationshipTypeData(newRelationshipTypeDefinition, oldRelationshipTypeDefinition); - return titanGenericDao + return janusGraphGenericDao .updateNode(new RelationshipTypeData(newRelationshipTypeDefinition), RelationshipTypeData.class) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus) + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus) .left() .bind(updatedNode -> updateRelationshipTypeProperties(newRelationshipTypeDefinition.getUniqueId(), newRelationshipTypeDefinition.getProperties())) @@ -379,7 +379,7 @@ public class RelationshipTypeOperation extends AbstractOperation { return propertyOperation .addPropertiesToElementType(relationshipTypeId, NodeTypeEnum.RelationshipType, properties) .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus); } private StorageOperationStatus deleteDerivedFromRelationshipType(String relationshipTypeId, @@ -393,19 +393,20 @@ public class RelationshipTypeOperation extends AbstractOperation { .either(derivedFromNode -> derivedFromOperation .removeDerivedFromRelation(relationshipTypeId, derivedFromNode.getUniqueId(), NodeTypeEnum.RelationshipType), - DaoStatusConverter::convertTitanStatusToStorageStatus); + DaoStatusConverter::convertJanusGraphStatusToStorageStatus); } - public Either, TitanOperationStatus> getAllRelationshipTypes() { + public Either, JanusGraphOperationStatus> getAllRelationshipTypes() { Map relationshipTypeDefinitionMap = new HashMap<>(); - Either, TitanOperationStatus> result = Either.left(relationshipTypeDefinitionMap); + Either, JanusGraphOperationStatus> result = Either.left(relationshipTypeDefinitionMap); - Either, TitanOperationStatus> getAllRelationshipTypes = - titanGenericDao.getByCriteria(NodeTypeEnum.RelationshipType, null, RelationshipTypeData.class); + Either, JanusGraphOperationStatus> getAllRelationshipTypes = + janusGraphGenericDao + .getByCriteria(NodeTypeEnum.RelationshipType, null, RelationshipTypeData.class); if (getAllRelationshipTypes.isRight()) { - TitanOperationStatus status = getAllRelationshipTypes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus status = getAllRelationshipTypes.right().value(); + if (status != JanusGraphOperationStatus.NOT_FOUND) { return Either.right(status); } else { return result; @@ -417,8 +418,8 @@ public class RelationshipTypeOperation extends AbstractOperation { logger.trace("Number of relationship types to load is {}", list.size()); //Set properties - Either, TitanOperationStatus> status = - getMapTitanOperationStatusEither(relationshipTypeDefinitionMap, list); + Either, JanusGraphOperationStatus> status = + getMapJanusGraphOperationStatusEither(relationshipTypeDefinitionMap, list); if (status != null) { return status; } @@ -427,7 +428,7 @@ public class RelationshipTypeOperation extends AbstractOperation { return result; } - private Either, TitanOperationStatus> getMapTitanOperationStatusEither( + private Either, JanusGraphOperationStatus> getMapJanusGraphOperationStatusEither( Map relationshipTypeDefinitionMap, List list) { for (RelationshipTypeData relationshipTypeData : list) { @@ -435,12 +436,12 @@ public class RelationshipTypeOperation extends AbstractOperation { logger.trace("Going to fetch relationship type {}. uid is {}", relationshipTypeData.getRelationshipTypeDataDefinition().getType(), relationshipTypeData.getUniqueId()); - Either relationshipTypesByUid = + Either relationshipTypesByUid = getAndAddPropertiesANdDerivedFrom(relationshipTypeData.getUniqueId(), relationshipTypeDefinitionMap); if (relationshipTypesByUid.isRight()) { - TitanOperationStatus status = relationshipTypesByUid.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; + JanusGraphOperationStatus status = relationshipTypesByUid.right().value(); + if (status == JanusGraphOperationStatus.NOT_FOUND) { + status = JanusGraphOperationStatus.INVALID_ID; } return Either.right(status); } @@ -448,18 +449,18 @@ public class RelationshipTypeOperation extends AbstractOperation { return null; } - private Either getAndAddPropertiesANdDerivedFrom( + private Either getAndAddPropertiesANdDerivedFrom( String uniqueId, Map relationshipTypeDefinitionMap) { if (relationshipTypeDefinitionMap.containsKey(uniqueId)) { return Either.left(relationshipTypeDefinitionMap.get(uniqueId)); } - Either relationshipTypesRes = - titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipType), uniqueId, + Either relationshipTypesRes = + janusGraphGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipType), uniqueId, RelationshipTypeData.class); if (relationshipTypesRes.isRight()) { - TitanOperationStatus status = relationshipTypesRes.right().value(); + JanusGraphOperationStatus status = relationshipTypesRes.right().value(); logger.debug(RELATIONSHIP_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status); return Either.right(status); } @@ -468,9 +469,9 @@ public class RelationshipTypeOperation extends AbstractOperation { RelationshipTypeDefinition relationshipTypeDefinition = new RelationshipTypeDefinition(ctData.getRelationshipTypeDataDefinition()); - Either, TitanOperationStatus> propertiesStatus = + Either, JanusGraphOperationStatus> propertiesStatus = OperationUtils.fillProperties(uniqueId, propertyOperation, NodeTypeEnum.RelationshipType); - if (propertiesStatus.isRight() && propertiesStatus.right().value() != TitanOperationStatus.OK) { + if (propertiesStatus.isRight() && propertiesStatus.right().value() != JanusGraphOperationStatus.OK) { logger.error(FAILED_TO_FETCH_PROPERTIES_OF_RELATIONSHIP_TYPE, uniqueId); return Either.right(propertiesStatus.right().value()); } 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 72c370ffe6..bea9df9639 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java @@ -20,7 +20,7 @@ package org.openecomp.sdc.be.model.operations.impl; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import org.apache.commons.lang3.BooleanUtils; import org.apache.tinkerpop.gremlin.structure.Direction; @@ -28,10 +28,10 @@ import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.VertexProperty; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; 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.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -52,11 +52,12 @@ import static org.apache.commons.collections.CollectionUtils.isEmpty; @Component("user-operation") public class UserAdminOperation implements IUserAdminOperation { - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; - public UserAdminOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) { + public UserAdminOperation(@Qualifier("janusgraph-generic-dao") + JanusGraphGenericDao janusGraphGenericDao) { super(); - this.titanGenericDao = titanGenericDao; + this.janusGraphGenericDao = janusGraphGenericDao; } @@ -93,7 +94,7 @@ public class UserAdminOperation implements IUserAdminOperation { return resultWrapper.getInnerElement(); } finally { if (!inTransaction) { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } log.debug("getUserData - end"); } @@ -127,7 +128,8 @@ public class UserAdminOperation implements IUserAdminOperation { return; } id = id.toLowerCase(); - Either either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class); + Either either = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class); if (either.isRight()) { resultWrapper.setInnerElement(getUserNotFoundError(id, either.right().value())); @@ -138,10 +140,10 @@ public class UserAdminOperation implements IUserAdminOperation { @Override public Either saveUserData(User user) { - Either result = null; + Either result = null; try { UserData userData = convertToUserData(user); - result = titanGenericDao.createNode(userData, UserData.class); + result = janusGraphGenericDao.createNode(userData, UserData.class); if (result.isRight()) { log.debug("Problem while saving User {}. Reason - {}", userData.getUserId(), result.right().value()); return Either.right(StorageOperationStatus.GENERAL_ERROR); @@ -153,21 +155,21 @@ public class UserAdminOperation implements IUserAdminOperation { if (result == null || result.isRight()) { log.error("saveUserData - Failed"); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug("saveUserData - end"); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } } @Override public Either updateUserData(User user) { - Either result = null; + Either result = null; try { log.debug("updateUserData - start"); UserData userData = convertToUserData(user); - result = titanGenericDao.updateNode(userData, UserData.class); + result = janusGraphGenericDao.updateNode(userData, UserData.class); if (result.isRight()) { if (log.isDebugEnabled()) { log.debug("Problem while updating User {}. Reason - {}", userData.toString(), result.right().value()); @@ -181,10 +183,10 @@ public class UserAdminOperation implements IUserAdminOperation { if (result == null || result.isRight()) { log.error("updateUserData - Failed"); - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } else { log.debug("updateUserData - end"); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } @@ -206,10 +208,11 @@ public class UserAdminOperation implements IUserAdminOperation { @Override public Either deleteUserData(String id) { Either result; - Either eitherGet = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class); + Either eitherGet = janusGraphGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class); if (eitherGet.isRight()) { log.debug("Problem while retriving user with userId {}",id); - if (eitherGet.right().value() == TitanOperationStatus.NOT_FOUND) { + if (eitherGet.right().value() == JanusGraphOperationStatus.NOT_FOUND) { result = Either.right(ActionStatus.USER_NOT_FOUND); } else { result = Either.right(ActionStatus.GENERAL_ERROR); @@ -228,13 +231,14 @@ public class UserAdminOperation implements IUserAdminOperation { deleteUser(resultWrapper, userData); } } finally { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } return resultWrapper.getInnerElement(); } private void deleteUser(Wrapper> resultWrapper, UserData userData) { - Either eitherDelete = titanGenericDao.deleteNode(userData, UserData.class); + Either eitherDelete = janusGraphGenericDao + .deleteNode(userData, UserData.class); if (eitherDelete.isRight()) { if (log.isDebugEnabled()) { log.debug("Problem while deleting User {}. Reason - {}", userData.toString(), eitherDelete.right().value()); @@ -249,7 +253,8 @@ public class UserAdminOperation implements IUserAdminOperation { private void validateUserHasNoConnections(Wrapper> resultWrapper, UserData userData) { if (resultWrapper.isEmpty()) { - Either, TitanOperationStatus> edgesForNode = titanGenericDao.getEdgesForNode(userData, Direction.BOTH); + Either, JanusGraphOperationStatus> edgesForNode = janusGraphGenericDao + .getEdgesForNode(userData, Direction.BOTH); if (edgesForNode.isRight()) { if (log.isDebugEnabled()) { log.debug("Problem while deleting User {}. Reason - {}", userData.getUserId(), edgesForNode.right().value()); @@ -266,21 +271,23 @@ public class UserAdminOperation implements IUserAdminOperation { public Either, StorageOperationStatus> getUserPendingTasksList(User user, Map properties) { - Either vertexUser = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), user.getUserId()); + Either vertexUser = janusGraphGenericDao + .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), user.getUserId()); if (vertexUser.isRight()) { - TitanOperationStatus tos = vertexUser.right().value(); + JanusGraphOperationStatus tos = vertexUser.right().value(); log.debug("Failed to get User {} from graph while retrieving pending tasks. Reason - {}", user.getUserId(), tos); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(tos)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(tos)); } List pendingTasks = new ArrayList<>(); - Either, TitanOperationStatus> edges = titanGenericDao.getOutgoingEdgesByCriteria(vertexUser.left().value(), GraphEdgeLabels.STATE, properties); + Either, JanusGraphOperationStatus> edges = janusGraphGenericDao + .getOutgoingEdgesByCriteria(vertexUser.left().value(), GraphEdgeLabels.STATE, properties); if (edges.isRight() || edges.left().value() == null) { - TitanOperationStatus tos = edges.right().value(); - if (tos == TitanOperationStatus.NOT_FOUND) { + JanusGraphOperationStatus tos = edges.right().value(); + if (tos == JanusGraphOperationStatus.NOT_FOUND) { return Either.left(pendingTasks); } else { log.debug("Failed while retrieving pending tasks for user {} . Reason - {}", user.getUserId(), tos); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(tos)); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(tos)); } } for (Edge edge : edges.left().value()) { @@ -322,21 +329,22 @@ public class UserAdminOperation implements IUserAdminOperation { propertiesToMatch.put(GraphPropertiesDictionary.USER_STATUS.getProperty(), status); } - Either, TitanOperationStatus> userNodes = titanGenericDao.getByCriteria(NodeTypeEnum.User, propertiesToMatch, UserData.class); + Either, JanusGraphOperationStatus> userNodes = janusGraphGenericDao + .getByCriteria(NodeTypeEnum.User, propertiesToMatch, UserData.class); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); return convertToUsers(role, userNodes); } finally { - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } } - private Either, ActionStatus> convertToUsers(String role, Either, TitanOperationStatus> userNodes) { + private Either, ActionStatus> convertToUsers(String role, Either, JanusGraphOperationStatus> userNodes) { if (userNodes.isRight()) { - // in case of NOT_FOUND from Titan return empty list - TitanOperationStatus tos = userNodes.right().value(); - if (tos.equals(TitanOperationStatus.NOT_FOUND)) { + // in case of NOT_FOUND from JanusGraph return empty list + JanusGraphOperationStatus tos = userNodes.right().value(); + if (tos.equals(JanusGraphOperationStatus.NOT_FOUND)) { return Either.left(Collections.emptyList()); } else { log.error("Problem while getting all users with role {}. Reason - {}", role, tos); @@ -361,8 +369,8 @@ public class UserAdminOperation implements IUserAdminOperation { return result; } - private Either getUserNotFoundError(String uid, TitanOperationStatus status) { - if (status == TitanOperationStatus.NOT_FOUND) { + private Either getUserNotFoundError(String uid, JanusGraphOperationStatus status) { + if (status == JanusGraphOperationStatus.NOT_FOUND) { log.debug("User with userId {} not found", uid); return Either.right(ActionStatus.USER_NOT_FOUND); } else { 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 d4cbc8d977..5c2212072c 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 @@ -25,7 +25,7 @@ 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.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java index 9efdc95bce..046161ab40 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.be.model; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; @@ -54,7 +54,7 @@ public class ModelTestBase { Configuration configuration = new Configuration(); - configuration.setTitanInMemoryGraph(true); + configuration.setJanusGraphInMemoryGraph(true); Map deploymentRIArtifacts = new HashMap<>(); ArtifactDataDefinition artifactInfo = new ArtifactDataDefinition(); @@ -66,13 +66,13 @@ public class ModelTestBase { configurationManager.getConfiguration().setDeploymentResourceInstanceArtifacts(deploymentRIArtifacts); } - protected void removeGraphVertices(Either graphResult) { - TitanGraph graph = graphResult.left().value(); - Iterable vertices = graph.query().vertices(); + protected void removeGraphVertices(Either graphResult) { + JanusGraph graph = graphResult.left().value(); + Iterable vertices = graph.query().vertices(); if (vertices != null) { - Iterator iterator = vertices.iterator(); + Iterator iterator = vertices.iterator(); while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); + JanusGraphVertex vertex = iterator.next(); vertex.remove(); } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCacheTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCacheTest.java index 48681867f9..82c8ae603d 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCacheTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCacheTest.java @@ -9,7 +9,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.be.resources.data.DataTypeData; @@ -54,7 +54,7 @@ public class ApplicationDataTypeCacheTest extends ModelConfDependentTest{ @Test public void testGetAllDataTypesFromGraph() throws Exception { - Either, TitanOperationStatus> result; + Either, JanusGraphOperationStatus> result; // default test result = Deencapsulation.invoke(testSubject, "getAllDataTypesFromGraph"); @@ -62,7 +62,7 @@ public class ApplicationDataTypeCacheTest extends ModelConfDependentTest{ @Test public void testGetAll() throws Exception { - Either, TitanOperationStatus> result; + Either, JanusGraphOperationStatus> result; // default test result = testSubject.getAll(); @@ -71,7 +71,7 @@ public class ApplicationDataTypeCacheTest extends ModelConfDependentTest{ @Test public void testGet() throws Exception { String uniqueId = ""; - Either result; + Either result; // default test result = testSubject.get(uniqueId); @@ -80,13 +80,13 @@ public class ApplicationDataTypeCacheTest extends ModelConfDependentTest{ @Test public void testGet2() throws Exception { String uniqueId = ""; - Either result; + Either result; HashMap a = new HashMap<>(); DataTypeDefinition value1 = new DataTypeDefinition(); value1.setUniqueId("mock"); a.put("mock", value1); - Either, TitanOperationStatus> value = Either.left(a); + Either, JanusGraphOperationStatus> value = Either.left(a); Mockito.when(propertyOperation.getAllDataTypes()).thenReturn(value); // default test Deencapsulation.invoke(testSubject, "replaceAllData"); @@ -100,7 +100,8 @@ public class ApplicationDataTypeCacheTest extends ModelConfDependentTest{ @Test public void testRun2() throws Exception { - Either, TitanOperationStatus> value = Either.right(TitanOperationStatus.GENERAL_ERROR); + Either, JanusGraphOperationStatus> value = Either.right( + JanusGraphOperationStatus.GENERAL_ERROR); Mockito.when(propertyOperation.getAllDataTypeNodes()).thenReturn(value); testSubject.run(); } @@ -109,14 +110,14 @@ public class ApplicationDataTypeCacheTest extends ModelConfDependentTest{ public void testRun3() throws Exception { LinkedList a = new LinkedList<>(); a.add(new DataTypeData()); - Either, TitanOperationStatus> value = Either.left(a); + Either, JanusGraphOperationStatus> value = Either.left(a); Mockito.when(propertyOperation.getAllDataTypeNodes()).thenReturn(value); HashMap a1 = new HashMap<>(); DataTypeDefinition value1 = new DataTypeDefinition(); value1.setUniqueId("mock"); a1.put("mock", value1); - Either, TitanOperationStatus> value2 = Either.left(a1); + Either, JanusGraphOperationStatus> value2 = Either.left(a1); Mockito.when(propertyOperation.getAllDataTypes()).thenReturn(value2); Deencapsulation.invoke(testSubject, "replaceAllData"); @@ -152,7 +153,7 @@ public class ApplicationDataTypeCacheTest extends ModelConfDependentTest{ DataTypeDefinition value1 = new DataTypeDefinition(); value1.setUniqueId("mock"); a.put("mock", value1); - Either, TitanOperationStatus> value = Either.left(a); + Either, JanusGraphOperationStatus> value = Either.left(a); Mockito.when(propertyOperation.getAllDataTypes()).thenReturn(value); // default test Deencapsulation.invoke(testSubject, "replaceAllData"); @@ -160,7 +161,8 @@ public class ApplicationDataTypeCacheTest extends ModelConfDependentTest{ @Test public void testReplaceAllData2() throws Exception { - Either, TitanOperationStatus> value = Either.right(TitanOperationStatus.GENERAL_ERROR); + Either, JanusGraphOperationStatus> value = Either.right( + JanusGraphOperationStatus.GENERAL_ERROR); Mockito.when(propertyOperation.getAllDataTypes()).thenReturn(value); // default test Deencapsulation.invoke(testSubject, "replaceAllData"); diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ComponentCacheTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ComponentCacheTest.java index 49e847acf6..62155e2be5 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ComponentCacheTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/ComponentCacheTest.java @@ -22,7 +22,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.Product; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.resources.data.ComponentCacheData; import org.openecomp.sdc.be.unittests.utils.ModelConfDependentTest; diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/DaoInfoTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/DaoInfoTest.java index 2e2f36b9c7..8c4d9d5378 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/DaoInfoTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/DaoInfoTest.java @@ -1,7 +1,7 @@ package org.openecomp.sdc.be.model.cache; import org.junit.Test; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; public class DaoInfoTest { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJobTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJobTest.java index 5347bc0d76..4e54ba7a29 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJobTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJobTest.java @@ -14,7 +14,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.cache.ComponentCache; import org.openecomp.sdc.be.model.cache.DaoInfo; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; 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; diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/config/ModelOperationsSpringConfig.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/config/ModelOperationsSpringConfig.java index d6b2dd61e7..7e0a72e474 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/config/ModelOperationsSpringConfig.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/config/ModelOperationsSpringConfig.java @@ -6,7 +6,8 @@ import org.springframework.context.annotation.PropertySource; @Configuration @ComponentScan({"org.openecomp.sdc.be.dao.cassandra", "org.openecomp.sdc.be.model.cache", - "org.openecomp.sdc.be.model.jsontitan.operations", "org.openecomp.sdc.be.model.jsontitan.utils", + "org.openecomp.sdc.be.model.jsonjanusgraph.operations", + "org.openecomp.sdc.be.model.jsonjanusgraph.utils", "org.openecomp.sdc.be.model.operations.impl"}) @PropertySource("classpath:dao.properties") public class ModelOperationsSpringConfig { } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeTypeTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeTypeTest.java new file mode 100644 index 0000000000..e4e377ff78 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeTypeTest.java @@ -0,0 +1,173 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.datamodel; + +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; + + +public class NodeTypeTest { + + private NodeType createTestSubject() { + return new NodeType(); + } + + + @Test + public void testGetDerivedList() throws Exception { + NodeType testSubject; + List result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getDerivedList(); + } + + + @Test + public void testSetDerivedList() throws Exception { + NodeType testSubject; + List derivedList = null; + + // default test + testSubject = createTestSubject(); + testSubject.setDerivedList(derivedList); + } + + + @Test + public void testGetDerivedFrom() throws Exception { + NodeType testSubject; + List result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getDerivedFrom(); + } + + + @Test + public void testSetDerivedFrom() throws Exception { + NodeType testSubject; + List derivedFrom = null; + + // default test + testSubject = createTestSubject(); + testSubject.setDerivedFrom(derivedFrom); + } + + + @Test + public void testGetAttributes() throws Exception { + NodeType testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getAttributes(); + } + + + @Test + public void testSetAttributes() throws Exception { + NodeType testSubject; + Map attributes = null; + + // default test + testSubject = createTestSubject(); + testSubject.setAttributes(attributes); + } + + + @Test + public void testGetCapabilties() throws Exception { + NodeType testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getCapabilities(); + } + + + @Test + public void testSetCapabilties() throws Exception { + NodeType testSubject; + Map capabilties = null; + + // default test + testSubject = createTestSubject(); + testSubject.setCapabilities(capabilties); + } + + + @Test + public void testGetRequirements() throws Exception { + NodeType testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getRequirements(); + } + + + @Test + public void testSetRequirements() throws Exception { + NodeType testSubject; + Map requirements = null; + + // default test + testSubject = createTestSubject(); + testSubject.setRequirements(requirements); + } + + + @Test + public void testGetCapabiltiesProperties() throws Exception { + NodeType testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getCapabilitiesProperties(); + } + + + @Test + public void testSetCapabiltiesProperties() throws Exception { + NodeType testSubject; + Map capabiltiesProperties = null; + + // default test + testSubject = createTestSubject(); + testSubject.setCapabilitiesProperties(capabiltiesProperties); + } + + + @Test + public void testGetInterfaceArtifacts() throws Exception { + NodeType testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getInterfaceArtifacts(); + } + + + @Test + public void testSetInterfaceArtifacts() throws Exception { + NodeType testSubject; + Map interfaceArtifacts = null; + + // default test + testSubject = createTestSubject(); + testSubject.setInterfaceArtifacts(interfaceArtifacts); + } +} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/TopologyTemplateTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/TopologyTemplateTest.java new file mode 100644 index 0000000000..4875ca69f7 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/TopologyTemplateTest.java @@ -0,0 +1,422 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.datamodel; + +import java.util.Map; + +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; + + +public class TopologyTemplateTest { + + private TopologyTemplate createTestSubject() { + return new TopologyTemplate(); + } + + + @Test + public void testGetInputs() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getInputs(); + } + + + @Test + public void testSetInputs() throws Exception { + TopologyTemplate testSubject; + Map inputs = null; + + // default test + testSubject = createTestSubject(); + testSubject.setInputs(inputs); + } + + + @Test + public void testGetInstInputs() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getInstInputs(); + } + + + @Test + public void testSetInstInputs() throws Exception { + TopologyTemplate testSubject; + Map instInputs = null; + + // default test + testSubject = createTestSubject(); + testSubject.setInstInputs(instInputs); + } + + + @Test + public void testGetHeatParameters() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getHeatParameters(); + } + + + @Test + public void testSetHeatParameters() throws Exception { + TopologyTemplate testSubject; + Map heatParameters = null; + + // default test + testSubject = createTestSubject(); + testSubject.setHeatParameters(heatParameters); + } + + + @Test + public void testGetInstAttributes() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getInstAttributes(); + } + + + @Test + public void testSetInstAttributes() throws Exception { + TopologyTemplate testSubject; + Map instAttributes = null; + + // default test + testSubject = createTestSubject(); + testSubject.setInstAttributes(instAttributes); + } + + + @Test + public void testGetInstProperties() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getInstProperties(); + } + + + @Test + public void testSetInstProperties() throws Exception { + TopologyTemplate testSubject; + Map instProperties = null; + + // default test + testSubject = createTestSubject(); + testSubject.setInstProperties(instProperties); + } + + + @Test + public void testGetGroups() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getGroups(); + } + + + @Test + public void testSetGroups() throws Exception { + TopologyTemplate testSubject; + Map groups = null; + + // default test + testSubject = createTestSubject(); + testSubject.setGroups(groups); + } + + + @Test + public void testGetInstGroups() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getInstGroups(); + } + + + @Test + public void testSetInstGroups() throws Exception { + TopologyTemplate testSubject; + Map instGroups = null; + + // default test + testSubject = createTestSubject(); + testSubject.setInstGroups(instGroups); + } + + + @Test + public void testGetServiceApiArtifacts() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getServiceApiArtifacts(); + } + + + @Test + public void testSetServiceApiArtifacts() throws Exception { + TopologyTemplate testSubject; + Map serviceApiArtifacts = null; + + // default test + testSubject = createTestSubject(); + testSubject.setServiceApiArtifacts(serviceApiArtifacts); + } + + + @Test + public void testGetCompositions() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getCompositions(); + } + + + @Test + public void testSetCompositions() throws Exception { + TopologyTemplate testSubject; + Map compositions = null; + + // default test + testSubject = createTestSubject(); + testSubject.setCompositions(compositions); + } + + + @Test + public void testGetCalculatedCapabilities() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getCalculatedCapabilities(); + } + + + @Test + public void testSetCalculatedCapabilities() throws Exception { + TopologyTemplate testSubject; + Map calculatedCapabilities = null; + + // default test + testSubject = createTestSubject(); + testSubject.setCalculatedCapabilities(calculatedCapabilities); + } + + + @Test + public void testGetCalculatedRequirements() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getCalculatedRequirements(); + } + + + @Test + public void testSetCalculatedRequirements() throws Exception { + TopologyTemplate testSubject; + Map calculatedRequirements = null; + + // default test + testSubject = createTestSubject(); + testSubject.setCalculatedRequirements(calculatedRequirements); + } + + + @Test + public void testGetFullfilledCapabilities() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getFullfilledCapabilities(); + } + + + @Test + public void testSetFullfilledCapabilities() throws Exception { + TopologyTemplate testSubject; + Map fullfilledCapabilities = null; + + // default test + testSubject = createTestSubject(); + testSubject.setFullfilledCapabilities(fullfilledCapabilities); + } + + + @Test + public void testGetFullfilledRequirements() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getFullfilledRequirements(); + } + + + @Test + public void testSetFullfilledRequirements() throws Exception { + TopologyTemplate testSubject; + Map fullfilledRequirements = null; + + // default test + testSubject = createTestSubject(); + testSubject.setFullfilledRequirements(fullfilledRequirements); + } + + + @Test + public void testGetInstDeploymentArtifacts() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getInstDeploymentArtifacts(); + } + + + @Test + public void testSetInstDeploymentArtifacts() throws Exception { + TopologyTemplate testSubject; + Map instDeploymentArtifacts = null; + + // default test + testSubject = createTestSubject(); + testSubject.setInstDeploymentArtifacts(instDeploymentArtifacts); + } + + + @Test + public void testGetCalculatedCapabilitiesProperties() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getCalculatedCapabilitiesProperties(); + } + + + @Test + public void testSetCalculatedCapabilitiesProperties() throws Exception { + TopologyTemplate testSubject; + Map calculatedCapabilitiesProperties = null; + + // default test + testSubject = createTestSubject(); + testSubject.setCalculatedCapabilitiesProperties(calculatedCapabilitiesProperties); + } + + + @Test + public void testGetInstanceArtifacts() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getInstanceArtifacts(); + } + + + @Test + public void testSetInstanceArtifacts() throws Exception { + TopologyTemplate testSubject; + Map instanceArtifacts = null; + + // default test + testSubject = createTestSubject(); + testSubject.setInstanceArtifacts(instanceArtifacts); + } + + + @Test + public void testGetDataTypes() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getDataTypes(); + } + + + @Test + public void testSetDataTypes() throws Exception { + TopologyTemplate testSubject; + Map dataTypes = null; + + // default test + testSubject = createTestSubject(); + testSubject.setDataTypes(dataTypes); + } + + + @Test + public void testGetComponentInstances() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getComponentInstances(); + } + + + @Test + public void testSetComponentInstances() throws Exception { + TopologyTemplate testSubject; + Map instances = null; + + // default test + testSubject = createTestSubject(); + testSubject.setComponentInstances(instances); + } + + + @Test + public void testGetRelations() throws Exception { + TopologyTemplate testSubject; + Map result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getRelations(); + } +} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElementTypeEnumTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElementTypeEnumTest.java new file mode 100644 index 0000000000..f175aa3d51 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElementTypeEnumTest.java @@ -0,0 +1,25 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.datamodel; + +import org.junit.Test; + + +public class ToscaElementTypeEnumTest { + + private ToscaElementTypeEnum createTestSubject() { + return ToscaElementTypeEnum.TOPOLOGY_TEMPLATE; + } + + + + + + @Test + public void testGetValue() throws Exception { + ToscaElementTypeEnum testSubject; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getValue(); + } +} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/enums/JsonConstantKeysEnumTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/enums/JsonConstantKeysEnumTest.java new file mode 100644 index 0000000000..a37a157428 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/enums/JsonConstantKeysEnumTest.java @@ -0,0 +1,22 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.enums; + +import org.junit.Test; + + +public class JsonConstantKeysEnumTest { + + private JsonConstantKeysEnum createTestSubject() { + return JsonConstantKeysEnum.COMPOSITION; + } + + + @Test + public void testGetValue() throws Exception { + JsonConstantKeysEnum testSubject; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getValue(); + } +} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperationTest.java new file mode 100644 index 0000000000..ce208d9b3a --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperationTest.java @@ -0,0 +1,495 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.GraphTestUtils; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Created by yavivi on 21/03/2018. + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(value = {"classpath:application-context-test.xml", "classpath:healing-context-test.xml"}) +public class ArchiveOperationTest extends ModelTestBase { + + private static final String CI_UID_RES1_CP = "cp_uid"; + private static final String CI_UID_RES2_VL = "vl_uid"; + private static final String CI_UID_SVC_PROXY = "svc_proxy_uid"; + + @Resource + private ArchiveOperation archiveOperation; + + @Resource + private JanusGraphDao janusGraphDao; + + private boolean isInitialized; + + private GraphVertex serviceVertex1; + private GraphVertex archivedVertex1; + + GraphVertex archiveVertex; + GraphVertex catalogVertex; + + private GraphVertex serviceVertex1_0; + private GraphVertex serviceVertex1_1; + private GraphVertex serviceVertex2_0; + private GraphVertex serviceVertex3_0; + private GraphVertex serviceVertex3_1; + + private GraphVertex serviceVertex0_1; + private GraphVertex serviceVertex0_2; + private GraphVertex serviceVertex0_3; + private GraphVertex serviceVertex0_4; + private GraphVertex serviceVertex0_5; + + //Composition Elements + private GraphVertex compositionService; + private GraphVertex compositionResource1; + private GraphVertex compositionResource2; + private GraphVertex compositionServiceProxy; + private GraphVertex compositionAnotherService; + + //For VSP Archive Notification + private GraphVertex vfResource0_1; + private GraphVertex vfResource0_2; + private GraphVertex vfResource1_0; + private String csarUuid = "123456789";; + + @BeforeClass + public static void initTest(){ + ModelTestBase.init(); + } + + @Before + public void beforeTest() { + if (!isInitialized) { + GraphTestUtils.clearGraph(janusGraphDao); + initGraphForTest(); + isInitialized = true; + } + } + + @Test + public void testArchiveComponentSingleVersion(){ + String componentId = serviceVertex1.getUniqueId(); + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(componentId); + assertThat(actionStatus.isLeft()).isTrue(); + assertArchived(serviceVertex1.getUniqueId()); + } + + @Test + public void testArchiveComponentFailsWhenInCheckoutSingleVersion(){ + checkoutComponent(serviceVertex1); + String componentId = serviceVertex1.getUniqueId(); + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(componentId); + assertThat(actionStatus.isLeft()).isFalse(); + assertThat(actionStatus.right().value()).isEqualTo(ActionStatus.INVALID_SERVICE_STATE); + } + + @Test + public void testArchiveWithWrongId() { + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent("fakeComponentId"); + assertThat(actionStatus.isLeft()).isFalse(); + assertThat(actionStatus.right().value()).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND); + } + + @Test + public void testAlreadyArchived() { + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(archivedVertex1.getUniqueId()); + assertThat(actionStatus.isLeft()).isTrue(); + assertThat(actionStatus.left().value()).containsExactly(archivedVertex1.getUniqueId()); + } + + @Test + public void testScenario2_archive_1_0(){ + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex1_0.getUniqueId()); + assertThat(actionStatus.isLeft()).isTrue(); + assertThat(actionStatus.left().value()).containsExactlyInAnyOrder(serviceVertex1_0.getUniqueId(), serviceVertex1_1.getUniqueId()); + assertArchived(serviceVertex1_0.getUniqueId()); + assertArchived(serviceVertex1_1.getUniqueId()); + } + + @Test + public void testScenario2_archive_1_1(){ + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex1_1.getUniqueId()); + assertThat(actionStatus.left().value()).containsExactlyInAnyOrder(serviceVertex1_0.getUniqueId(), serviceVertex1_1.getUniqueId()); + assertArchived(serviceVertex1_0.getUniqueId()); + assertArchived(serviceVertex1_1.getUniqueId()); + } + + @Test + public void testScenario4_oneLowOneHighestVersion(){ + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex0_2.getUniqueId()); + assertThat(actionStatus.left().value()).containsExactlyInAnyOrder(serviceVertex0_2.getUniqueId(), serviceVertex0_1.getUniqueId(), serviceVertex0_3.getUniqueId(), serviceVertex0_4.getUniqueId(), serviceVertex0_5.getUniqueId()); + assertArchived(serviceVertex0_1.getUniqueId()); + assertArchived(serviceVertex0_2.getUniqueId()); + assertArchived(serviceVertex0_3.getUniqueId()); + assertArchived(serviceVertex0_4.getUniqueId()); + assertArchived(serviceVertex0_5.getUniqueId()); + + actionStatus = this.archiveOperation.restoreComponent(serviceVertex0_2.getUniqueId()); + assertThat(actionStatus.isLeft()).isTrue(); + assertThat(actionStatus.left().value()).containsExactlyInAnyOrder(serviceVertex0_2.getUniqueId(), serviceVertex0_1.getUniqueId(), serviceVertex0_3.getUniqueId(), serviceVertex0_4.getUniqueId(), serviceVertex0_5.getUniqueId()); + } + + + /////////////// Continue Here ////////////////// + @Test + public void testScenario4_archiveFromNonHighest(){ + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex0_2.getUniqueId()); + assertArchived(serviceVertex0_1.getUniqueId()); + assertArchived(serviceVertex0_2.getUniqueId()); + assertArchived(serviceVertex0_3.getUniqueId()); + assertArchived(serviceVertex0_4.getUniqueId()); + assertArchived(serviceVertex0_5.getUniqueId()); + + actionStatus = this.archiveOperation.restoreComponent(serviceVertex0_3.getUniqueId()); + assertRestored(serviceVertex0_1.getUniqueId()); + assertRestored(serviceVertex0_2.getUniqueId()); + assertRestored(serviceVertex0_3.getUniqueId()); + assertRestored(serviceVertex0_4.getUniqueId()); + assertRestored(serviceVertex0_5.getUniqueId()); + } + + @Test + public void testArchiveFailsWhenHighestVersionIsInCheckoutState(){ + checkoutComponent(serviceVertex0_5); + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex0_2.getUniqueId()); + assertThat(actionStatus.right().value()).isEqualTo(ActionStatus.INVALID_SERVICE_STATE); + } + + @Test + public void testScenario3_archive_3_0(){ + Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex3_0.getUniqueId()); + assertArchived(serviceVertex3_0.getUniqueId()); + assertArchived(serviceVertex3_1.getUniqueId()); + assertArchivedProps(serviceVertex2_0.getUniqueId()); + } + + @Test + public void testArchivedOriginsCalculation(){ + + //Archive the CP resource + this.archiveOperation.archiveComponent(this.compositionResource1.getUniqueId()); + this.archiveOperation.archiveComponent(this.compositionServiceProxy.getUniqueId()); + + List ciWithArchivedOrigins = this.archiveOperation.setArchivedOriginsFlagInComponentInstances(this.compositionService); + + //Validate that method returns the CI of CP + assertThat(ciWithArchivedOrigins).containsExactlyInAnyOrder(CI_UID_RES1_CP, CI_UID_SVC_PROXY); + + Map compositionsJson = (Map) this.compositionService.getJson(); + + assertThat(compositionsJson).isNotNull(); + assertThat(compositionsJson.get(JsonConstantKeysEnum.COMPOSITION.getValue())).isNotNull(); + + CompositionDataDefinition composition = compositionsJson.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + + //Get all component instances from composition + Map componentInstances = composition.getComponentInstances(); + for (ComponentInstanceDataDefinition ci : componentInstances.values()) { + //Verify that exactly 2 CIs are marked as archived + if (ci.getUniqueId().equals(CI_UID_RES1_CP) || ci.getUniqueId().equals(CI_UID_SVC_PROXY)) { + assertThat(ci.isOriginArchived()).isTrue(); + } + } + + } + + @Test + public void testNoArchivedOriginsCalculation(){ + List ciWithArchivedOrigins = this.archiveOperation.setArchivedOriginsFlagInComponentInstances(this.compositionService); + + //Validate that method returns the CI of CP + assertThat(ciWithArchivedOrigins).isEmpty(); + } + + @Test + public void testOnVspArchivedAndRestored(){ + this.archiveOperation.onVspArchived(csarUuid); + //assertOnCommit(); + + assertOnVspArchived(true); + + this.archiveOperation.onVspRestored(csarUuid); + //assertOnCommit(); + assertOnVspArchived(false); + + //Not Found CSAR UUID + ActionStatus result = this.archiveOperation.onVspRestored("fakeUuid"); + //assertOnCommit(); + assertThat(result).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND); + } + + private void assertOnVspArchived(boolean expectedValue) { + GraphVertex v = janusGraphDao.getVertexById(vfResource0_1.getUniqueId()).left().value(); + assertThat(v.getMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED)).isEqualTo(expectedValue); + + v = janusGraphDao.getVertexById(vfResource0_2.getUniqueId()).left().value(); + assertThat(v.getMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED)).isEqualTo(expectedValue); + + v = janusGraphDao.getVertexById(vfResource1_0.getUniqueId()).left().value(); + assertThat(v.getMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED)).isEqualTo(expectedValue); + } + + /************************** + * Utility Methods + *************************/ + + private void checkoutComponent(GraphVertex serviceVertex0_5) { + Either vE = janusGraphDao.getVertexById(serviceVertex0_5.getUniqueId()); + GraphVertex v = vE.left().value(); + v.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + v.setJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + janusGraphDao.updateVertex(v); + assertOnCommit(); + } + + private void assertOnCommit(){ + final JanusGraphOperationStatus commit = this.janusGraphDao.commit(); + assertThat(commit).isEqualTo(JanusGraphOperationStatus.OK); + } + + private void assertArchived(String componentUniqueId) { + assertArchivedOrRestored(ArchiveOperation.Action.ARCHIVE, componentUniqueId); + } + + private void assertRestored(String componentUniqueId) { + assertArchivedOrRestored(ArchiveOperation.Action.RESTORE, componentUniqueId); + } + + private void assertArchivedOrRestored(ArchiveOperation.Action action, String componentUniqueId) { + GraphVertex v = janusGraphDao.getVertexById(componentUniqueId).left().value(); + + EdgeLabelEnum requiredEdge = action == ArchiveOperation.Action.ARCHIVE ? EdgeLabelEnum.ARCHIVE_ELEMENT : EdgeLabelEnum.CATALOG_ELEMENT; + EdgeLabelEnum otherEdge = action == ArchiveOperation.Action.ARCHIVE ? EdgeLabelEnum.CATALOG_ELEMENT : EdgeLabelEnum.ARCHIVE_ELEMENT; + + GraphVertex parent = null; + Either otherLookup = null; + Boolean isHighest = (Boolean) v.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); + if (isHighest != null && isHighest) { + //Highest version are linked to Archive/Catalog Root + parent = janusGraphDao.getParentVertex(v, requiredEdge, JsonParseFlagEnum.NoParse).left().value(); + otherLookup = janusGraphDao.getParentVertex(v, otherEdge, JsonParseFlagEnum.NoParse); + assertThat(otherLookup.isRight()).isTrue(); //Verify that component is not linked to Catalog/Archive Root + assertThat(parent.getUniqueId()).isEqualTo(action == ArchiveOperation.Action.ARCHIVE ? this.archiveVertex.getUniqueId() : this.catalogVertex.getUniqueId()); //Verify that parent is indeed Archive Root + } + + assertArchivedOrRestoredProps(action, v); + } + + private void assertArchivedProps(String uniqueId) { + GraphVertex v = + janusGraphDao.getVertexById(uniqueId).left().value(); + assertArchivedOrRestoredProps(ArchiveOperation.Action.ARCHIVE, v); + } + + private void assertRestoredProps(String uniqueId) { + GraphVertex v = + janusGraphDao.getVertexById(uniqueId).left().value(); + assertArchivedOrRestoredProps(ArchiveOperation.Action.RESTORE, v); + } + + private void assertArchivedOrRestoredProps(ArchiveOperation.Action action, GraphVertex v) { + Object isArchived = v.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED); + Object archiveTime = v.getMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME); + assertThat(isArchived).isNotNull().isEqualTo(action == ArchiveOperation.Action.ARCHIVE ? true : false); + assertThat(archiveTime).isNotNull(); + } + + /******************************* + * Preperation Methods + *******************************/ + private void initGraphForTest() { + //Create Catalog Root + this.catalogVertex = GraphTestUtils.createRootCatalogVertex(janusGraphDao); + //Create Archive Root + this.archiveVertex = GraphTestUtils.createRootArchiveVertex(janusGraphDao); + + createScenario1_SingleVersionNode(); + createScenario2_TwoHighestVersions(); + createScenario3_TwoHighestVersionsOneLowest(); + createMiscServices(); + createServiceCompositionForCalculatingArchivedOrigins(); + createScenario4_1Highest4LowestVersions(); + createResourcesForArchivedVsp(); + + assertOnCommit(); + } + + private void createScenario1_SingleVersionNode() { + //Create Service for Scenario 1 Tests (1 Service) + this.serviceVertex1 = GraphTestUtils.createServiceVertex(janusGraphDao, propsForHighestVersion()); + + //Connect Service to Catalog Root + janusGraphDao.createEdge(catalogVertex, serviceVertex1, EdgeLabelEnum.CATALOG_ELEMENT, null); + } + + private void createScenario2_TwoHighestVersions() { + //Create Service for Scenario 2 Tests (1 Service) + this.serviceVertex1_0 = GraphTestUtils.createServiceVertex(janusGraphDao, propsForHighestVersion()); + this.serviceVertex1_1 = GraphTestUtils.createServiceVertex(janusGraphDao, propsForHighestVersion()); + + janusGraphDao.createEdge(serviceVertex1_0, serviceVertex1_1, EdgeLabelEnum.VERSION, null); + + //Connect 1.0 and 1.1 to Catalog Root + janusGraphDao + .createEdge(catalogVertex, serviceVertex1_0, EdgeLabelEnum.CATALOG_ELEMENT, null); + janusGraphDao + .createEdge(catalogVertex, serviceVertex1_1, EdgeLabelEnum.CATALOG_ELEMENT, null); + } + + private void createScenario3_TwoHighestVersionsOneLowest() { + //Create Service for Scenario 1 Tests (1 Service) + this.serviceVertex2_0 = GraphTestUtils.createServiceVertex(janusGraphDao, propsForNonHighestVersion()); //NonHighestVersion + this.serviceVertex3_0 = GraphTestUtils.createServiceVertex(janusGraphDao, propsForHighestVersion()); + this.serviceVertex3_1 = GraphTestUtils.createServiceVertex(janusGraphDao, propsForHighestVersion()); + + //Connect version edges + janusGraphDao.createEdge(serviceVertex2_0, serviceVertex3_0, EdgeLabelEnum.VERSION, null); + janusGraphDao.createEdge(serviceVertex3_0, serviceVertex3_1, EdgeLabelEnum.VERSION, null); + + //Connect 3.0 and 3.1 to Catalog Root + janusGraphDao + .createEdge(catalogVertex, serviceVertex3_0, EdgeLabelEnum.CATALOG_ELEMENT, null); + janusGraphDao + .createEdge(catalogVertex, serviceVertex3_1, EdgeLabelEnum.CATALOG_ELEMENT, null); + } + + private void createScenario4_1Highest4LowestVersions() { + //2 Lowest version only + this.serviceVertex0_1 = GraphTestUtils.createServiceVertex(janusGraphDao, propsForNonHighestVersion()); + this.serviceVertex0_2 = GraphTestUtils.createServiceVertex(janusGraphDao, propsForNonHighestVersion()); + this.serviceVertex0_3 = GraphTestUtils.createServiceVertex(janusGraphDao, propsForNonHighestVersion()); + this.serviceVertex0_4 = GraphTestUtils.createServiceVertex(janusGraphDao, propsForNonHighestVersion()); + this.serviceVertex0_5 = GraphTestUtils.createServiceVertex(janusGraphDao, propsForHighestVersion()); + + janusGraphDao.createEdge(serviceVertex0_1, serviceVertex0_2, EdgeLabelEnum.VERSION, null); + janusGraphDao.createEdge(serviceVertex0_2, serviceVertex0_3, EdgeLabelEnum.VERSION, null); + janusGraphDao.createEdge(serviceVertex0_3, serviceVertex0_4, EdgeLabelEnum.VERSION, null); + janusGraphDao.createEdge(serviceVertex0_4, serviceVertex0_5, EdgeLabelEnum.VERSION, null); + + janusGraphDao + .createEdge(catalogVertex, serviceVertex0_5, EdgeLabelEnum.CATALOG_ELEMENT, null); + } + + private void createResourcesForArchivedVsp(){ + Map vfPropsNonHighest = propsForNonHighestVersion(); + Map vfPropsHighest = propsForNonHighestVersion(); + + vfPropsNonHighest.put(GraphPropertyEnum.CSAR_UUID, csarUuid); + vfPropsNonHighest.put(GraphPropertyEnum.IS_VSP_ARCHIVED, false); + vfPropsHighest.put(GraphPropertyEnum.CSAR_UUID, csarUuid); + vfPropsHighest.put(GraphPropertyEnum.IS_VSP_ARCHIVED, false); + + this.vfResource0_1 = GraphTestUtils.createResourceVertex(janusGraphDao, vfPropsNonHighest, ResourceTypeEnum.VF); + this.vfResource0_2 = GraphTestUtils.createResourceVertex(janusGraphDao, vfPropsNonHighest, ResourceTypeEnum.VF); + this.vfResource1_0 = GraphTestUtils.createResourceVertex(janusGraphDao, vfPropsHighest, ResourceTypeEnum.VF); + + janusGraphDao.createEdge(vfResource0_1, vfResource0_2, EdgeLabelEnum.VERSION, null); + janusGraphDao.createEdge(vfResource0_2, vfResource1_0, EdgeLabelEnum.VERSION, null); + } + + private void createMiscServices() { + //Create Service for Scenario 1 Tests (1 Service) + this.archivedVertex1 = GraphTestUtils.createServiceVertex(janusGraphDao, new HashMap<>()); + + //Connect Service to Catalog Root + janusGraphDao.createEdge(archiveVertex, archivedVertex1, EdgeLabelEnum.ARCHIVE_ELEMENT, null); + } + + private void createServiceCompositionForCalculatingArchivedOrigins(){ + //Service that point to another service in composition + this.compositionService = GraphTestUtils.createServiceVertex(janusGraphDao, propsForHighestVersion()); + this.compositionAnotherService = GraphTestUtils.createServiceVertex(janusGraphDao, propsForHighestVersion()); + + this.compositionResource1 = GraphTestUtils.createResourceVertex(janusGraphDao, propsForHighestVersion(), ResourceTypeEnum.CP); + this.compositionResource2 = GraphTestUtils.createResourceVertex(janusGraphDao, propsForHighestVersion(), ResourceTypeEnum.VL); + this.compositionServiceProxy = GraphTestUtils.createResourceVertex(janusGraphDao, propsForHighestVersion(), ResourceTypeEnum.ServiceProxy); + + janusGraphDao + .createEdge(compositionService, compositionResource1, EdgeLabelEnum.INSTANCE_OF, null); + janusGraphDao + .createEdge(compositionService, compositionResource2, EdgeLabelEnum.INSTANCE_OF, null); + janusGraphDao + .createEdge(compositionService, compositionServiceProxy, EdgeLabelEnum.INSTANCE_OF, null); + janusGraphDao + .createEdge(compositionService, compositionAnotherService, EdgeLabelEnum.PROXY_OF, null); + + createAndAttachCompositionJson(compositionService); + } + + private void createAndAttachCompositionJson(GraphVertex compositionService) { + //Full composition json + Map compositions = new HashMap<>(); + //Single composition data + CompositionDataDefinition composition = new CompositionDataDefinition(); + //Instances Map + Map instances = new HashMap<>(); + + //Prepare Instances Map + ComponentInstanceDataDefinition instance = new ComponentInstanceDataDefinition(); + instance.setUniqueId(CI_UID_RES1_CP); + instance.setComponentUid(compositionResource1.getUniqueId()); + instances.put(CI_UID_RES1_CP, instance); + + instance = new ComponentInstanceDataDefinition(); + instance.setUniqueId(CI_UID_RES2_VL); + instance.setComponentUid(compositionResource2.getUniqueId()); + instances.put(CI_UID_RES2_VL, instance); + + instance = new ComponentInstanceDataDefinition(); + instance.setUniqueId(CI_UID_SVC_PROXY); + instance.setComponentUid(compositionServiceProxy.getUniqueId()); + instances.put(CI_UID_SVC_PROXY, instance); + + //Add Instances to Composition + composition.setComponentInstances(instances); + //Add to full composition + compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), composition); + //Add Full Json to vertex + compositionService.setJson(compositions); + //System.out.println(JsonParserUtils.toJson(compositions)); + janusGraphDao.updateVertex(compositionService); + } + + private Map propsForHighestVersion(){ + Map props = new HashMap(); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + return props; + } + + private Map propsForNonHighestVersion(){ + Map props = new HashMap(); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, false); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + return props; + } + +} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperationsTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperationsTest.java new file mode 100644 index 0000000000..160957d1f6 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperationsTest.java @@ -0,0 +1,83 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +import org.junit.Test; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +public class ArtifactsOperationsTest { + + private static final String SERVICE_ID = "serviceId"; + private static final String INSTANCE_ID = "instanceId"; + private ArtifactsOperations testInstance = mock(ArtifactsOperations.class, CALLS_REAL_METHODS); + + @Test + public void getInstanceArtifacts_collectAllInstanceArtifacts() throws Exception { + Map instanceArtifacts = Collections.singletonMap(INSTANCE_ID, getArtifactsByInstance("name1")); + + Map instanceDeploymentArtifacts = new HashMap<>(); + instanceDeploymentArtifacts.put(INSTANCE_ID, getArtifactsByInstance("name2", "name3")); + instanceDeploymentArtifacts.put("instanceId2", getArtifactsByInstance("name4")); + + doReturn(Either.left(instanceArtifacts)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS); + doReturn(Either.left(instanceDeploymentArtifacts)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + Either, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, INSTANCE_ID); + + assertTrue(allInstArtifacts.isLeft()); + assertEquals(allInstArtifacts.left().value().size(), 3); + assertTrue(allInstArtifacts.left().value().containsKey("name1")); + assertTrue(allInstArtifacts.left().value().containsKey("name2")); + assertTrue(allInstArtifacts.left().value().containsKey("name3")); + assertFalse(allInstArtifacts.left().value().containsKey("name4"));//this key is of different instance + } + + @Test + public void getInstanceArtifacts_noArtifactsForInstance() throws Exception { + Map instanceArtifacts = Collections.singletonMap(INSTANCE_ID, getArtifactsByInstance("name1")); + + doReturn(Either.left(instanceArtifacts)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS); + doReturn(Either.left(new HashMap<>())).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + Either, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, "someOtherInstance"); + + assertTrue(allInstArtifacts.isLeft()); + assertTrue(allInstArtifacts.left().value().isEmpty()); + } + + @Test + public void getInstanceArtifacts_errorGettingInstanceArtifacts() throws Exception { + doReturn(Either.right(JanusGraphOperationStatus.GENERAL_ERROR)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS); + Either, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, INSTANCE_ID); + verify(testInstance, times(0)).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + assertTrue(allInstArtifacts.isRight()); + } + + @Test + public void getAllInstanceArtifacts_errorGettingDeploymentArtifacts() throws Exception { + doReturn(Either.left(new HashMap<>())).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS); + doReturn(Either.right(JanusGraphOperationStatus.GENERAL_ERROR)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + Either, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, INSTANCE_ID); + assertTrue(allInstArtifacts.isRight()); + } + + private ToscaDataDefinition getArtifactsByInstance(String ... artifactsNames) { + MapArtifactDataDefinition artifactsByInstance = new MapArtifactDataDefinition(); + Map artifactsByName = new HashMap<>(); + for (String artifactName : artifactsNames) { + artifactsByName.put(artifactName, new ArtifactDataDefinition()); + } + artifactsByInstance.setMapToscaDataDefinition(artifactsByName); + return artifactsByInstance; + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CapabilitiesOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CapabilitiesOperationTest.java new file mode 100644 index 0000000000..5fc2ef2cae --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CapabilitiesOperationTest.java @@ -0,0 +1,87 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * 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. + */ + +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.CapabilityTestUtils; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +public class CapabilitiesOperationTest { + + @InjectMocks + CapabilitiesOperation operation = new CapabilitiesOperation(); + @Mock + private JanusGraphDao mockJanusGraphDao; + @Mock + private TopologyTemplateOperation topologyTemplateOperation; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + + when(mockJanusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK); + when(mockJanusGraphDao.getVertexById(anyString(), any())).thenReturn(Either.left(new GraphVertex())); + + when(topologyTemplateOperation.updateFullToscaData(any(), any(), any(), anyMap())).thenReturn(StorageOperationStatus.OK); + TopologyTemplate topologyTemplate = new TopologyTemplate(); + + Map capPropsForTopologyTemplate = CapabilityTestUtils + .createCapPropsForTopologyTemplate(topologyTemplate); + topologyTemplate.setCapabilitiesProperties(capPropsForTopologyTemplate); + + when(topologyTemplateOperation.getToscaElement(anyString(), any())).thenReturn(Either.left(topologyTemplate)); + } + + @Test + public void testCreateOrUpdateCapabilitiesProperties() { + + Map mapToscaDataDefinition = new HashMap<>(); + PropertyDataDefinition propertyDataDefinition = new PropertyDataDefinition(); + propertyDataDefinition.setUniqueId("ComponentInput1_uniqueId"); + propertyDataDefinition.setName("propName"); + mapToscaDataDefinition.put(propertyDataDefinition.getUniqueId(), propertyDataDefinition); + MapPropertiesDataDefinition mapPropertiesDataDefinition = new MapPropertiesDataDefinition(mapToscaDataDefinition); + + Map propertiesMap = new HashMap<>(); + propertiesMap.put(propertyDataDefinition.getUniqueId(), mapPropertiesDataDefinition); + + StorageOperationStatus operationStatus = operation.createOrUpdateCapabilityProperties("componentId", + propertiesMap); + + Assert.assertEquals(StorageOperationStatus.OK, operationStatus); + } +} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperationTest.java new file mode 100644 index 0000000000..8900377bb2 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperationTest.java @@ -0,0 +1,227 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.datatypes.elements.MapComponentInstanceExternalRefs; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.GraphTestUtils; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.IdMapper; +import org.openecomp.sdc.be.model.operations.StorageException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import javax.annotation.Resource; +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +/** + * Created by yavivi on 26/01/2018. + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class ExternalReferencesOperationTest extends ModelTestBase { + + private static final String COMPONENT_ID = "ci-MyComponentName"; + private static final String COMPONENT2_ID = "ci-MyComponentName2"; + private static final String MONITORING_OBJECT_TYPE = "monitoring"; + private static final String WORKFLOW_OBJECT_TYPE = "workflow"; + private static final String REF_1 = "ref1"; + private static final String REF_2 = "ref2"; + private static final String REF_3 = "ref3"; + private static final String REF_4 = "ref4"; + private static final String REF_5 = "ref5"; + //workflow + private static final String REF_6 = "ref6"; + + @Resource + private ExternalReferencesOperation externalReferenceOperation; + + @Resource + private JanusGraphDao janusGraphDao; + + private boolean isInitialized; + + private GraphVertex serviceVertex; + private GraphVertex serviceVertex2; + private GraphVertex serviceVertex3; + + private String serviceVertexUuid; + private String serviceVertex2Uuid; + private String serviceVertex3Uuid; + + private IdMapper idMapper; + + @BeforeClass + public static void initTest(){ + ModelTestBase.init(); + } + + @Before + public void beforeTest() { + idMapper = Mockito.mock(IdMapper.class); + this.externalReferenceOperation.setIdMapper(idMapper); + when(idMapper.mapComponentNameToUniqueId(Mockito.anyString(), Mockito.any(GraphVertex.class))).thenReturn(COMPONENT_ID); + if (!isInitialized) { + GraphTestUtils.clearGraph(janusGraphDao); + initGraphForTest(); + isInitialized = true; + } + } + + @Test + public void testAddComponentInstanceExternalRef(){ + Either addResult = externalReferenceOperation.addExternalReference(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_4); + assertThat(addResult.isLeft()).isEqualTo(true); + + //commit changes to janusgraph + final JanusGraphOperationStatus commit = this.janusGraphDao.commit(); + assertThat(commit).isEqualTo(JanusGraphOperationStatus.OK); + + assertThat(getServiceExternalRefs()).contains(REF_1, REF_2, REF_3, REF_4); + } + + @Test + public void testAddExternalReferences_success() { + Map> refsMap = Collections.singletonMap(MONITORING_OBJECT_TYPE, Arrays.asList(REF_1, REF_2)); + externalReferenceOperation.addAllExternalReferences(serviceVertex3Uuid, COMPONENT_ID, refsMap); + Map> allExternalReferences = externalReferenceOperation.getAllExternalReferences(serviceVertex3Uuid, COMPONENT_ID); + assertThat(allExternalReferences.size()).isEqualTo(1); + assertThat(allExternalReferences).flatExtracting(MONITORING_OBJECT_TYPE).containsExactly(REF_1, REF_2); + externalReferenceOperation.addAllExternalReferences(serviceVertex3Uuid, COMPONENT2_ID, refsMap); + Map> allExternalReferences2 = externalReferenceOperation.getAllExternalReferences(serviceVertex3Uuid, COMPONENT2_ID); + assertThat(allExternalReferences2.size()).isEqualTo(1); + assertThat(allExternalReferences2).flatExtracting(MONITORING_OBJECT_TYPE).containsExactly(REF_1, REF_2); + } + + @Test + public void testGetAllCIExternalRefs_success() { + Map> allExternalReferences = externalReferenceOperation.getAllExternalReferences(serviceVertexUuid, COMPONENT_ID); + assertThat(allExternalReferences.size()).isEqualTo(2); + assertThat(allExternalReferences).flatExtracting(WORKFLOW_OBJECT_TYPE).containsExactly(REF_6); + assertThat(allExternalReferences).flatExtracting(MONITORING_OBJECT_TYPE).containsExactly(REF_1, REF_2, REF_3, REF_5); + } + + @Test + public void testGetAllCIExternalRefs_noRefsExist() { + Map> allExternalReferences = externalReferenceOperation.getAllExternalReferences(serviceVertex2Uuid, COMPONENT_ID); + assertThat(allExternalReferences.size()).isZero(); + } + + @Test + public void testGetAllCIExternalRefs_noSuchComponentInstance() { + Map> allExternalReferences = externalReferenceOperation.getAllExternalReferences(serviceVertex2Uuid, "FAKE"); + assertThat(allExternalReferences.size()).isZero(); + } + + @Test(expected=StorageException.class) + public void testGetAllCIExternalRefs_nonExitingService_throwsException() { + externalReferenceOperation.getAllExternalReferences("FAKE", COMPONENT_ID); + } + + @Test + public void testGetComponentInstanceExternalRef(){ + assertThat(externalReferenceOperation.getExternalReferences(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE).left().value()).contains(REF_1, REF_2, REF_3, REF_5); + assertThat(externalReferenceOperation.getExternalReferences(this.serviceVertexUuid, COMPONENT_ID, WORKFLOW_OBJECT_TYPE).left().value()).containsExactly(REF_6); + } + + @Test + public void testGetComponentInstanceExternalRefForNonExistingObjectId(){ + assertThat(externalReferenceOperation.getExternalReferences(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE).left().value()).contains(REF_1, REF_2, REF_3, REF_5); + Either, ActionStatus> getResult = externalReferenceOperation.getExternalReferences(this.serviceVertexUuid, COMPONENT_ID, "FAKE_OBJECT_TYPE"); + assertThat(getResult.left().value()).isEmpty(); + } + + @Test + public void testDeleteComponentInstanceExternalRef(){ + //Test the precondition + assertThat(getServiceExternalRefs()).contains(REF_5); + + //Remove REF 5 + Either deleteStatus = externalReferenceOperation.deleteExternalReference(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5); + assertThat(deleteStatus.isLeft()).isEqualTo(true); + + //commit changes to janusgraph + final JanusGraphOperationStatus commit = this.janusGraphDao.commit(); + assertThat(commit).isEqualTo(JanusGraphOperationStatus.OK); + + //Check that ref does not exist anymore + assertThat(getServiceExternalRefs()).doesNotContain(REF_5).contains(REF_1, REF_2, REF_3); + } + + @Test + public void testUpdateComponentInstanceExternalRef(){ + //Test the precondition + assertThat(getServiceExternalRefs()).contains(REF_5).doesNotContain(REF_4); + + //Update REF 5 with REF_4 + Either updateResult = externalReferenceOperation.updateExternalReference(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5, REF_4); + + assertThat(updateResult.isLeft()).isEqualTo(true); + + //commit changes to janusgraph + final JanusGraphOperationStatus commit = this.janusGraphDao.commit(); + assertThat(commit).isEqualTo(JanusGraphOperationStatus.OK); + + //Check that ref does not exist anymore + assertThat(getServiceExternalRefs()).doesNotContain(REF_5).contains(REF_1, REF_2, REF_3, REF_4); + } + + private List getServiceExternalRefs(){ + //Get service vertex + final Either externalRefsVertexResult = this.janusGraphDao + .getChildVertex(this.serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, JsonParseFlagEnum.ParseJson); + assertThat(externalRefsVertexResult.isLeft()).isEqualTo(true); + + GraphVertex externalRefVertex = externalRefsVertexResult.left().value(); + + //Get the full map + Map componentInstancesMap = (Map) externalRefVertex.getJson(); + assertThat(componentInstancesMap).isNotNull(); + + //Get Map of external refs by object type + final MapComponentInstanceExternalRefs mapComponentInstanceExternalRefs = componentInstancesMap.get(COMPONENT_ID); + + //Get List of references + //final List externalRefsByObjectType = mapComponentInstanceExternalRefs.externalRefsByObjectType(objectType); + + return mapComponentInstanceExternalRefs.getExternalRefsByObjectType(MONITORING_OBJECT_TYPE); + } + + private void initGraphForTest() { + //create a service + this.serviceVertex = GraphTestUtils.createServiceVertex(janusGraphDao, new HashMap<>()); + this.serviceVertexUuid = this.serviceVertex.getUniqueId(); + + //monitoring references + externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_1); + externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_2); + externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_3); + externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5); + + //workflow references + externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, WORKFLOW_OBJECT_TYPE, REF_6); + + //create a service without refs + serviceVertex2 = GraphTestUtils.createServiceVertex(janusGraphDao, new HashMap<>()); + serviceVertex2Uuid = serviceVertex2.getUniqueId(); + + //create a service for adding all references + serviceVertex3 = GraphTestUtils.createServiceVertex(janusGraphDao, new HashMap<>()); + serviceVertex3Uuid = serviceVertex3.getUniqueId(); + + final JanusGraphOperationStatus commit = this.janusGraphDao.commit(); + assertThat(commit).isEqualTo(JanusGraphOperationStatus.OK); + } +} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperationTest.java new file mode 100644 index 0000000000..e93ec3c616 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperationTest.java @@ -0,0 +1,105 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; + +import fj.data.Either; +import java.util.List; +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.config.JanusGraphSpringConfig; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {JanusGraphSpringConfig.class, ModelOperationsSpringConfig.class}) +public class GroupsOperationTest extends ModelTestBase { + + @Autowired + private GroupsOperation groupsOperation; + + @Autowired + HealingJanusGraphDao janusGraphDao; + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + private Component container; + + @BeforeClass + public static void initClass() { + ModelTestBase.init(); + } + + @Before + public void setUp() throws Exception { + container = new Resource(); + container.setUniqueId(CONTAINER_ID); + Either createdCmpt = janusGraphDao.createVertex(createBasicContainerGraphVertex()); + assertThat(createdCmpt.isLeft()).isTrue(); + + } + + @After + public void tearDown() throws Exception { + janusGraphDao.rollback(); + } + + @Test + public void addGroups_whenContainerHasNoGroups_associateContainerWithGroup() { + GroupDefinition g1 = createGroupDefinition("g1"); + GroupDefinition g2 = createGroupDefinition("g2"); + Either, StorageOperationStatus> createGroups = groupsOperation.addGroups(container, asList(g1, g2)); + assertThat(createGroups.isLeft()).isTrue(); + + ComponentParametersView getGroupsFilter = new ComponentParametersView(true); + getGroupsFilter.setIgnoreGroups(false); + Component cmptWithGroups = toscaOperationFacade.getToscaElement(CONTAINER_ID, getGroupsFilter).left().value(); + assertThat(cmptWithGroups.getGroups()) + .usingElementComparatorOnFields("name", "uniqueId") + .containsExactlyInAnyOrder(g1, g2); + } + + @Test + public void addGroups_whenContainerHasGroups_addTheGivenGroupsToTheGroupsList() { + GroupDefinition g1 = createGroupDefinition("g1"); + GroupDefinition g2 = createGroupDefinition("g2"); + groupsOperation.addGroups(container, asList(g1, g2)).left().value(); + + GroupDefinition g3 = createGroupDefinition("g3"); + GroupDefinition g4 = createGroupDefinition("g4"); + + groupsOperation.addGroups(container, asList(g3, g4)).left().value(); + + ComponentParametersView getGroupsFilter = new ComponentParametersView(true); + getGroupsFilter.setIgnoreGroups(false); + Component cmptWithGroups = toscaOperationFacade.getToscaElement(CONTAINER_ID, getGroupsFilter).left().value(); + assertThat(cmptWithGroups.getGroups()) + .usingElementComparatorOnFields("name", "uniqueId") + .containsExactlyInAnyOrder(g1, g2, g3, g4); + + } + + private GroupDefinition createGroupDefinition(String id) { + GroupDefinition groupDefinition = new GroupDefinition(); + groupDefinition.setUniqueId(id); + groupDefinition.setName("name" + id); + return groupDefinition; + } + + +} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InterfaceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InterfaceOperationTest.java new file mode 100644 index 0000000000..31d3f86967 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InterfaceOperationTest.java @@ -0,0 +1,497 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Resource; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.Component; +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.Service; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.NodeType; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.GraphTestUtils; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class InterfaceOperationTest extends ModelTestBase { + + private static final String RESOURCE_NAME = "Resource Name"; + private static final String RESOURCE_ID = "resourceID"; + private static final String SERVICE_NAME = "Service Name"; + private static final String SERVICE_ID = "serviceID"; + private final String categoryName = "category"; + private final String subcategory = "mycategory"; + private final Service service = createService(); + private final org.openecomp.sdc.be.model.Resource resource = createResource(); + @Resource + protected JanusGraphDao janusGraphDao; + @Resource + protected NodeTypeOperation nodeTypeOperation; + @Resource + protected TopologyTemplateOperation topologyTemplateOperation; + @Resource + private InterfaceOperation interfaceOperation; + @Resource + private ToscaElementLifecycleOperation lifecycleOperation; + private GraphVertex ownerVertex; + + @BeforeClass + public static void initInterfacesOperation() { + init(); + } + + @Before + public void setupBefore() { + GraphTestUtils.clearGraph(janusGraphDao); + createUsers(); + createResourceCategory(); + createServiceCategory(); + GraphTestUtils.createRootCatalogVertex(janusGraphDao); + createRootNodeType(); + createNodeType("resource", RESOURCE_ID); + createNodeType("service", SERVICE_ID); + createTopologyTemplate("firstService"); + } + + private void createUsers() { + GraphVertex ownerV = new GraphVertex(VertexTypeEnum.USER); + ownerV.setUniqueId("user1"); + + Map metadataProperties = new HashMap<>(); + metadataProperties.put(GraphPropertyEnum.USERID, ownerV.getUniqueId()); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.USER.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, "user1"); + ownerV.setMetadataProperties(metadataProperties); + ownerV.updateMetadataJsonWithCurrentMetadataProperties(); + ownerV.setJson(new HashMap<>()); + Either createUserRes = janusGraphDao.createVertex(ownerV); + + ownerVertex = createUserRes.left().value(); + + GraphVertex modifierV = new GraphVertex(VertexTypeEnum.USER); + modifierV.setUniqueId("user2"); + + metadataProperties = new HashMap<>(); + metadataProperties.put(GraphPropertyEnum.USERID, modifierV.getUniqueId()); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.USER.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, "user2"); + modifierV.setMetadataProperties(metadataProperties); + modifierV.updateMetadataJsonWithCurrentMetadataProperties(); + modifierV.setJson(new HashMap<>()); + createUserRes = janusGraphDao.createVertex(modifierV); + createUserRes.left().value(); + + lifecycleOperation.findUser(ownerVertex.getUniqueId()); + } + + private void createResourceCategory() { + GraphVertex cat = new GraphVertex(VertexTypeEnum.RESOURCE_CATEGORY); + Map metadataProperties = new HashMap<>(); + String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.RESOURCE_CATEGORY); + cat.setUniqueId(catId); + metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.RESOURCE_CATEGORY.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, categoryName); + metadataProperties + .put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); + cat.setMetadataProperties(metadataProperties); + cat.updateMetadataJsonWithCurrentMetadataProperties(); + + GraphVertex subCat = new GraphVertex(VertexTypeEnum.RESOURCE_SUBCATEGORY); + metadataProperties = new HashMap<>(); + String subCatId = UniqueIdBuilder.buildSubCategoryUid(cat.getUniqueId(), subcategory); + subCat.setUniqueId(subCatId); + metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, subCatId); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.RESOURCE_SUBCATEGORY.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, subcategory); + metadataProperties + .put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(subcategory)); + subCat.setMetadataProperties(metadataProperties); + subCat.updateMetadataJsonWithCurrentMetadataProperties(); + + Either catRes = janusGraphDao.createVertex(cat); + Either subCatRes = janusGraphDao.createVertex(subCat); + janusGraphDao.createEdge(catRes.left().value().getVertex(), subCatRes.left().value().getVertex(), + EdgeLabelEnum.SUB_CATEGORY, new HashMap<>()); + } + + private void createServiceCategory() { + GraphVertex cat = new GraphVertex(VertexTypeEnum.SERVICE_CATEGORY); + Map metadataProperties = new HashMap<>(); + String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.SERVICE_CATEGORY); + cat.setUniqueId(catId); + metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.SERVICE_CATEGORY.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, categoryName); + metadataProperties + .put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); + cat.setMetadataProperties(metadataProperties); + cat.updateMetadataJsonWithCurrentMetadataProperties(); + janusGraphDao.createVertex(cat); + } + + private void createRootNodeType() { + NodeType vf = new NodeType(); + String uniqueId = UniqueIdBuilder.buildResourceUniqueId(); + vf.setUniqueId(uniqueId); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + vf.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); + vf.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), "root"); + vf.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); + vf.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "1.0"); + vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VFC.name()); + vf.getMetadata() + .put(JsonPresentationFields.LIFECYCLE_STATE.getPresentation(), LifecycleStateEnum.CERTIFIED.name()); + vf.getMetadata().put(JsonPresentationFields.TOSCA_RESOURCE_NAME.getPresentation(), "root"); + vf.getMetadata().put(JsonPresentationFields.HIGHEST_VERSION.getPresentation(), true); + + List categories = new ArrayList<>(); + CategoryDefinition cat = new CategoryDefinition(); + categories.add(cat); + cat.setName(categoryName); + List subCategories = new ArrayList<>(); + SubCategoryDefinition subCat = new SubCategoryDefinition(); + subCat.setName(subcategory); + subCategories.add(subCat); + cat.setSubcategories(subCategories); + vf.setCategories(categories); + + List derivedFrom = new ArrayList<>(); + vf.setDerivedFrom(derivedFrom); + + Map properties = new HashMap<>(); + PropertyDataDefinition prop1 = new PropertyDataDefinition(); + prop1.setName("derived1"); + prop1.setDefaultValue("deriveddef1"); + properties.put("derived1", prop1); + + PropertyDataDefinition prop2 = new PropertyDataDefinition(); + prop2.setUniqueId("derived2"); + prop2.setName("deriveddef2"); + properties.put("derived2", prop2); + + PropertyDataDefinition prop3 = new PropertyDataDefinition(); + prop3.setName("derived3"); + prop3.setDefaultValue("deriveddef3"); + properties.put("derived3", prop3); + + vf.setProperties(properties); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + Either createVFRes = nodeTypeOperation.createNodeType(vf); + + Either getNodeTyeRes = + janusGraphDao.getVertexById(createVFRes.left().value().getUniqueId()); + getNodeTyeRes.left().value(); + } + + private void createNodeType(String nodeTypeName, String uniqueId) { + NodeType vf = new NodeType(); + vf.setUniqueId(uniqueId); + vf.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); + vf.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), nodeTypeName); + vf.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); + vf.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "0.1"); + vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VF.name()); + vf.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), ComponentTypeEnum.RESOURCE); + List categories = new ArrayList<>(); + CategoryDefinition cat = new CategoryDefinition(); + categories.add(cat); + cat.setName(categoryName); + List subCategories = new ArrayList<>(); + SubCategoryDefinition subCat = new SubCategoryDefinition(); + subCat.setName(subcategory); + subCategories.add(subCat); + cat.setSubcategories(subCategories); + vf.setCategories(categories); + + List derivedFrom = new ArrayList<>(); + derivedFrom.add("root"); + vf.setDerivedFrom(derivedFrom); + + vf.setComponentType(ComponentTypeEnum.RESOURCE); + + List addProperties = new ArrayList<>(); + PropertyDataDefinition prop11 = new PropertyDataDefinition(); + prop11.setName("prop11"); + prop11.setDefaultValue("def11"); + + addProperties.add(prop11); + + PropertyDataDefinition prop22 = new PropertyDataDefinition(); + prop22.setName("prop22"); + prop22.setDefaultValue("def22"); + addProperties.add(prop22); + + Either createVFRes = nodeTypeOperation.createNodeType(vf); + Either getNodeTyeRes = + janusGraphDao.getVertexById(createVFRes.left().value().getUniqueId()); + GraphVertex vfVertex = getNodeTyeRes.left().value(); + StorageOperationStatus status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, + VertexTypeEnum.PROPERTIES, addProperties, JsonPresentationFields.NAME); + assertSame(StorageOperationStatus.OK, status); + + PropertyDataDefinition prop33 = new PropertyDataDefinition(); + prop33.setName("prop33"); + prop33.setDefaultValue("def33"); + + status = nodeTypeOperation + .addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, + prop33, JsonPresentationFields.NAME); + assertSame(StorageOperationStatus.OK, status); + + PropertyDataDefinition prop44 = new PropertyDataDefinition(); + prop44.setName("prop44"); + prop44.setDefaultValue("def44"); + + status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex.getUniqueId(), EdgeLabelEnum.PROPERTIES, + VertexTypeEnum.PROPERTIES, prop44, JsonPresentationFields.NAME); + assertSame(StorageOperationStatus.OK, status); + + PropertyDataDefinition capProp = new PropertyDataDefinition(); + capProp.setName("capProp"); + capProp.setDefaultValue("capPropDef"); + + MapDataDefinition dataToCreate = new MapPropertiesDataDefinition(); + dataToCreate.put("capProp", capProp); + + Map capProps = new HashMap<>(); + capProps.put("capName", dataToCreate); + + nodeTypeOperation.associateElementToData(vfVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, + EdgeLabelEnum.CAPABILITIES_PROPERTIES, capProps); + + List pathKeys = new ArrayList<>(); + pathKeys.add("capName"); + capProp.setDefaultValue("BBBB"); + nodeTypeOperation.updateToscaDataDeepElementOfToscaElement(vfVertex, EdgeLabelEnum.CAPABILITIES_PROPERTIES, + VertexTypeEnum.CAPABILITIES_PROPERTIES, capProp, pathKeys, JsonPresentationFields.NAME); + } + + private void createTopologyTemplate(String name) { + TopologyTemplate service = new TopologyTemplate(); + String uniqueId = UniqueIdBuilder.buildResourceUniqueId(); + service.setUniqueId(uniqueId); + service.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); + service.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), name); + service.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); + service.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "0.1"); + service.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VF.name()); + service.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), ComponentTypeEnum.RESOURCE); + List categories = new ArrayList<>(); + CategoryDefinition cat = new CategoryDefinition(); + categories.add(cat); + cat.setName(categoryName); + service.setCategories(categories); + + service.setComponentType(ComponentTypeEnum.SERVICE); + Either createRes = + topologyTemplateOperation.createTopologyTemplate(service); + Either getNodeTyeRes = + janusGraphDao.getVertexById(createRes.left().value().getUniqueId()); + + getNodeTyeRes.left().value(); + } + + @After + public void cleanAfter() { + GraphTestUtils.clearGraph(janusGraphDao); + } + + @Test + public void testAddInterface_Service() { + testAddSingleInterface(service); + } + + private void testAddSingleInterface(Component component) { + InterfaceDefinition interfaceDefinition = buildInterfaceDefinition("1"); + Either, StorageOperationStatus> res = interfaceOperation + .addInterfaces(component.getUniqueId(), + Collections.singletonList( + interfaceDefinition)); + Assert.assertTrue(res.isLeft()); + Assert.assertEquals("1", res.left().value().get(0).getUniqueId()); + } + + private InterfaceDefinition buildInterfaceDefinition(String uniqueId) { + InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); + interfaceDefinition.setType("tosca.interfaces.standard"); + interfaceDefinition.setUniqueId(uniqueId); + interfaceDefinition.setOperationsMap(createMockOperationMap()); + return interfaceDefinition; + } + + private Map createMockOperationMap() { + Map operationMap = new HashMap<>(); + operationMap.put("op1", createMockOperation()); + return operationMap; + } + + private Operation createMockOperation() { + Operation operation = new Operation(); + operation.setDefinition(false); + operation.setName("create"); + operation.setUniqueId("op1"); + return operation; + } + + @Test + public void testAddInterface_Resource() { + testAddMultipleInterface(resource); + } + + private void testAddMultipleInterface(Component component) { + InterfaceDefinition interfaceDefinition1 = buildInterfaceDefinition("1"); + InterfaceDefinition interfaceDefinition2 = buildInterfaceDefinition("2"); + List interfaceDefinitions = new ArrayList<>(); + interfaceDefinitions.add(interfaceDefinition1); + interfaceDefinitions.add(interfaceDefinition2); + Either, StorageOperationStatus> res = + interfaceOperation.addInterfaces(component.getUniqueId(), interfaceDefinitions); + Assert.assertTrue(res.isLeft()); + Assert.assertEquals(2, res.left().value().size()); + } + + @Test + public void testUpdateInterface_Service() { + testUpdateInterface(service); + } + + private void testUpdateInterface(Component component) { + InterfaceDefinition interfaceDefinition = buildInterfaceDefinition("1"); + Either, StorageOperationStatus> res = interfaceOperation + .addInterfaces(component.getUniqueId(), + Collections.singletonList( + interfaceDefinition)); + Assert.assertTrue(res.isLeft()); + List value = res.left().value(); + InterfaceDefinition createdInterfaceDef = value.get(0); + String newDescription = "New Description"; + createdInterfaceDef.setDescription(newDescription); + res = interfaceOperation + .updateInterfaces(component.getUniqueId(), Collections.singletonList(createdInterfaceDef)); + assertTrue(res.isLeft()); + assertEquals(newDescription, res.left().value().get(0).getDescription()); + } + + @Test + public void testUpdateInterface_Resource() { + testUpdateInterface(resource); + } + + @Test + public void testDeleteInterface_Service() { + testDeleteInterface(service); + } + + private void testDeleteInterface(Component component) { + InterfaceDefinition interfaceDefinition = buildInterfaceDefinition("1"); + Either, StorageOperationStatus> res = interfaceOperation + .addInterfaces(component.getUniqueId(), + Collections.singletonList( + interfaceDefinition)); + Assert.assertTrue(res.isLeft()); + List value = res.left().value(); + Either deleteInterfaceOperationRes = + interfaceOperation.deleteInterface(component.getUniqueId(), value.get(0).getUniqueId()); + assertTrue(deleteInterfaceOperationRes.isLeft()); + } + + @Test + public void testDeleteInterface_Resource() { + testDeleteInterface(resource); + } + + @Test + public void testUpdateInterfaceShouldFailWhenNOtCreatedFirst() { + Component component = createResource(); + InterfaceDefinition interfaceDefinition = buildInterfaceDefinitionWithoutOperation(); + interfaceDefinition.setOperationsMap(createMockOperationMap()); + Either, StorageOperationStatus> res = interfaceOperation.updateInterfaces( + component.getUniqueId(), Collections.singletonList(interfaceDefinition)); + Assert.assertTrue(res.isRight()); + } + + private InterfaceDefinition buildInterfaceDefinitionWithoutOperation() { + InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); + interfaceDefinition.setType("tosca.interfaces.standard"); + return interfaceDefinition; + } + + private org.openecomp.sdc.be.model.Resource createResource() { + org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource(); + resource.setUniqueId(RESOURCE_ID); + resource.setName(RESOURCE_NAME); + resource.setDescription("My short description"); + resource.setInterfaces(createMockInterfaceDefinition()); + return resource; + } + + private Service createService() { + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + service.setName(SERVICE_NAME); + service.setDescription("My short description"); + service.setInterfaces(createMockInterfaceDefinition()); + return service; + } + + private Map createMockInterfaceDefinition() { + Map operationMap = createMockOperationMap(); + Map interfaceDefinitionMap = new HashMap<>(); + interfaceDefinitionMap.put("int1", createInterface("int1", "Interface 1", "lifecycle", "tosca", operationMap)); + return interfaceDefinitionMap; + } + + private InterfaceDefinition createInterface(String uniqueId, String description, String type, + String toscaResourceName, Map op) { + InterfaceDefinition id = new InterfaceDefinition(); + id.setType(type); + id.setDescription(description); + id.setUniqueId(uniqueId); + id.setToscaResourceName(toscaResourceName); + id.setOperationsMap(op); + return id; + } + + @After + public void teardown() { + GraphTestUtils.clearGraph(janusGraphDao); + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperationGraphTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperationGraphTest.java new file mode 100644 index 0000000000..0131783bea --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperationGraphTest.java @@ -0,0 +1,244 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; +import fj.data.Either; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import javax.annotation.Resource; +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.io.IoCore; +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.config.JanusGraphSpringConfig; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {JanusGraphSpringConfig.class, ModelOperationsSpringConfig.class}) +public class NodeTemplateOperationGraphTest extends ModelTestBase{ + @Resource + private HealingJanusGraphDao janusGraphDao; + @Resource + private NodeTemplateOperation nodeTemplateOperation; + + private JanusGraph graphT; + private GraphVertex containerVertex; + private String containeId; + + @BeforeClass + public static void setupBeforeClass() { + + ModelTestBase.init(); + } + @Before + public void before(){ + + Either graph = janusGraphDao.getGraph(); + graphT = graph.left().value(); + + containerVertex = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); + containeId = "containerId"; + containerVertex.setUniqueId(containeId); + Either createVertex = janusGraphDao.createVertex(containerVertex); + assertTrue(createVertex.isLeft()); + } + + @After + public void after(){ + janusGraphDao.rollback(); + + } + + + String outputDirectory = "C:\\Output"; + + @Test + public void testCreateInstanceEdge(){ + + Map> mapOriginToInstId = new HashMap<>(); + createIntancesFromSameResource(mapOriginToInstId, 1, 3); + createIntancesFromSameResource(mapOriginToInstId, 2, 4); + createIntancesFromSameResource(mapOriginToInstId, 3, 1); + +// exportGraphMl(graphT); + + validateOnGraph(mapOriginToInstId, 3); + } + + @Test + public void testRemoveInstanceEdge(){ + //create 3 instances from same resource orig1 + Map> mapOriginToInstId = new HashMap<>(); + String originId = createIntancesFromSameResource(mapOriginToInstId, 1, 3); + validateOnGraph(mapOriginToInstId, 1); + + //remove instance 2 + String instanceId = removeInstanceEdge(containerVertex, originId, 1, 1); + mapOriginToInstId.get(originId).remove(instanceId); + validateOnGraph(mapOriginToInstId, 1); + + //create new instance from orig1 + instanceId = createInstanceEdge(containerVertex, originId, 1, 4, false, null); + mapOriginToInstId.get(originId).add(instanceId); + validateOnGraph(mapOriginToInstId, 1); + + //create 1 instance from same resource orig2 + originId = createIntancesFromSameResource(mapOriginToInstId, 2, 1); + validateOnGraph(mapOriginToInstId, 2); + + //remove instance of orig 2 + instanceId = removeInstanceEdge(containerVertex, originId, 2, 1); + mapOriginToInstId.get(originId).remove(instanceId); + validateOnGraph(mapOriginToInstId, 1); + + } + + @Test + public void testProxyInstanceEdge(){ + Map> mapOriginToInstId = new HashMap<>(); + String proxyId = createOrigin(2); + createIntancesFromSameResource(mapOriginToInstId, 1, 1, true, proxyId); + + validateOnGraph(mapOriginToInstId, 1); + } + private void validateOnGraph(Map> mapOriginToInstId, int expectedEdgeCount) { + validateOnGraph(mapOriginToInstId, expectedEdgeCount, false); + } + private void validateOnGraph(Map> mapOriginToInstId, int expectedEdgeCount, boolean validateProxy) { + Iterable vertices = graphT.query().has(GraphPropertyEnum.UNIQUE_ID.getProperty(), containeId).vertices(); + assertNotNull(vertices); + Iterator iterator = vertices.iterator(); + assertTrue(iterator.hasNext()); + Vertex containerV = iterator.next(); + validatePerEdgeType(mapOriginToInstId, expectedEdgeCount, containerV, EdgeLabelEnum.INSTANCE_OF); + if ( validateProxy ){ + validatePerEdgeType(mapOriginToInstId, expectedEdgeCount, containerV, EdgeLabelEnum.PROXY_OF); + } + } + private void validatePerEdgeType(Map> mapOriginToInstId, int expectedEdgeCount, Vertex containerV, EdgeLabelEnum edgeLabel) { + Iterator edges = containerV.edges(Direction.OUT, edgeLabel.name()); + assertNotNull(edges); + + int counter = 0; + while (edges.hasNext()){ + Edge edge = edges.next(); + counter++; + validateEdge(edge, mapOriginToInstId); + } + assertEquals("check edge size", expectedEdgeCount, counter); + } + + + private String createIntancesFromSameResource(Map> mapOriginToInstId, int originIndex, int countInstances) { + return createIntancesFromSameResource(mapOriginToInstId, originIndex, countInstances, false, null); + } + + private String createIntancesFromSameResource(Map> mapOriginToInstId, int originIndex, int countInstances, boolean isProxy, String proxyId) { + + List exp = new ArrayList(); + String originId = createOrigin(originIndex); + + for ( int i = 0; i < countInstances; i++){ + String instanceId = createInstanceEdge(containerVertex, originId, originIndex, i+1, isProxy, proxyId); + exp.add(instanceId); + } + mapOriginToInstId.put(originId, exp); + if ( isProxy ){ + mapOriginToInstId.put(proxyId, exp); + } + return originId; + } + + private String createInstanceEdge(GraphVertex containerVertex, String originId, int originIndex, int insIndex, boolean isProxy, String proxyId) { + ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(); + componentInstance.setComponentUid(originId); + String instanceId = buildInstanceId(originIndex, insIndex); + componentInstance.setUniqueId(instanceId); + componentInstance.setIsProxy(isProxy); + componentInstance.setSourceModelUid(proxyId); + StorageOperationStatus edgeStatus = nodeTemplateOperation.createInstanceEdge(containerVertex, componentInstance); + assertEquals("assertion createInstanceEdge", StorageOperationStatus.OK, edgeStatus); + return instanceId; + } + + private String buildInstanceId(int originIndex, int insIndex) { + StringBuffer sb = new StringBuffer("instanceId_"); + sb.append(originIndex).append("-").append(insIndex); + return sb.toString(); + } + private String removeInstanceEdge(GraphVertex containerVertex, String originId, int originIndex, int insIndex) { + ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(); + componentInstance.setComponentUid(originId); + String instanceId = buildInstanceId(originIndex, insIndex); + componentInstance.setUniqueId(instanceId); + StorageOperationStatus edgeStatus = nodeTemplateOperation.removeInstanceEdge(containerVertex, componentInstance); + assertEquals("assertion removeInstanceEdge", StorageOperationStatus.OK, edgeStatus); + return instanceId; + } + + + private String createOrigin(int index) { + Either createVertex; + GraphVertex originVertex = new GraphVertex(VertexTypeEnum.NODE_TYPE); + String originId = "originId_" + index; + originVertex.setUniqueId(originId); + createVertex = janusGraphDao.createVertex(originVertex); + assertTrue(createVertex.isLeft()); + return originId; + } + private void validateEdge(Edge edge, Map> mapOriginToInstId) { + List expextedInList; + + Vertex originV = edge.inVertex(); + String id = (String) janusGraphDao.getProperty((JanusGraphVertex)originV, GraphPropertyEnum.UNIQUE_ID.getProperty()); + expextedInList = mapOriginToInstId.get(id); + + List list = (List) janusGraphDao.getProperty(edge, EdgePropertyEnum.INSTANCES); + assertThat(list).hasSameSizeAs(expextedInList); + assertThat(list).containsOnlyElementsOf(expextedInList); + } + + private String exportGraphMl(JanusGraph graph) { + String result = null; + String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml"; + try { + try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) { + graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph); + } + result = outputFile; + } catch (Exception e) { + e.printStackTrace(); + } + return result; + + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperationTest.java new file mode 100644 index 0000000000..1455d1e984 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperationTest.java @@ -0,0 +1,366 @@ +/* + + * Copyright (c) 2018 AT&T Intellectual Property. + + * + + * 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. + + */ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import com.google.common.collect.Lists; +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class NodeTemplateOperationTest extends ModelTestBase { + + private final static String COMPONENT_ID = "componentId"; + private final static String TO_INSTANCE_ID = "toInstanceId"; + private final static String FROM_INSTANCE_ID = "fromInstanceId"; + private final static String RELATION_ID = "relationId"; + private final static String CAPABILITY_OWNER_ID = "capabilityOwnerId"; + private final static String CAPABILITY_UID = "capabilityUid"; + private final static String CAPABILITY_NAME = "capabilityName"; + private final static String REQUIREMENT_OWNER_ID = "requirementOwnerId"; + private final static String REQUIREMENT_UID = "requirementUid"; + private final static String REQUIREMENT_NAME = "requirementName"; + private final static String RELATIONSHIP_TYPE = "relationshipType"; + + private static Map fulfilledCapability; + private static Map fulfilledRequirement; + private static CapabilityDataDefinition capability; + private static RequirementDataDefinition requirement; + private static RequirementCapabilityRelDef relation; + + @InjectMocks + private static NodeTemplateOperation operation; + + @Mock + private static JanusGraphDao janusGraphDao; + + @Mock + private static TopologyTemplateOperation topologyTemplateOperation; + + @BeforeClass + public static void setup() { + init(); + janusGraphDao = Mockito.mock(JanusGraphDao.class); + operation = new NodeTemplateOperation(); + operation.setJanusGraphDao(janusGraphDao); + buildDataDefinition(); + } + + private static void buildDataDefinition() { + buildCapabiltyDataDefinition(); + buildRequirementDataDefinition(); + buildRelation(); + } + + @Test + public void testGetFulfilledCapabilityByRelationSuccess(){ + GraphVertex vertex = Mockito.mock(GraphVertex.class); + Either vertexRes = Either.left(vertex); + when(janusGraphDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); + + GraphVertex dataVertex = new GraphVertex(); + dataVertex.setJson(fulfilledCapability); + Either childVertexRes = Either.left(dataVertex); + when(janusGraphDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_CAPABILITIES), eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); + Either result = operation.getFulfilledCapabilityByRelation(COMPONENT_ID, TO_INSTANCE_ID, relation, this::isBelongingCapability); + assertTrue(result.isLeft()); + assertEquals(result.left().value(), capability); + } + + @Test + public void testGetFulfilledRequirementByRelationSuccess(){ + GraphVertex vertex = Mockito.mock(GraphVertex.class); + Either vertexRes = Either.left(vertex); + when(janusGraphDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); + + GraphVertex dataVertex = new GraphVertex(); + dataVertex.setJson(fulfilledRequirement); + Either childVertexRes = Either.left(dataVertex); + when(janusGraphDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_REQUIREMENTS), eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); + Either result = operation.getFulfilledRequirementByRelation(COMPONENT_ID, FROM_INSTANCE_ID, relation, this::isBelongingRequirement); + assertTrue(result.isLeft()); + assertEquals(result.left().value(), requirement); + } + + @Test + public void testGetFulfilledCapabilityByRelationNotFoundFailure(){ + GraphVertex vertex = Mockito.mock(GraphVertex.class); + Either vertexRes = Either.left(vertex); + when(janusGraphDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); + + Either childVertexRes = Either.right( + JanusGraphOperationStatus.NOT_FOUND); + when(janusGraphDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_CAPABILITIES), eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); + Either result = operation.getFulfilledCapabilityByRelation(COMPONENT_ID, TO_INSTANCE_ID, relation, this::isBelongingCapability); + assertTrue(result.isRight()); + assertSame(result.right().value(), StorageOperationStatus.NOT_FOUND); + } + + @Test + public void testGetFulfilledRequirementByRelationNotFoundFailure(){ + GraphVertex vertex = Mockito.mock(GraphVertex.class); + Either vertexRes = Either.left(vertex); + when(janusGraphDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); + + Either childVertexRes = Either.right( + JanusGraphOperationStatus.NOT_FOUND); + when(janusGraphDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_REQUIREMENTS), eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); + Either result = operation.getFulfilledRequirementByRelation(COMPONENT_ID, FROM_INSTANCE_ID, relation, this::isBelongingRequirement); + assertTrue(result.isRight()); + assertSame(result.right().value(), StorageOperationStatus.NOT_FOUND); + } + + @Test + public void testUpdateCIMetadataOfTopologyTemplate() { + Either, StorageOperationStatus> result; + String id = "id"; + TopologyTemplate container = new TopologyTemplate(); + ToscaElement toscaElement = new TopologyTemplate(); + toscaElement.setResourceType(ResourceTypeEnum.VF); + ComponentInstance componentInstance = new ComponentInstance(); + componentInstance.setName(id); + componentInstance.setComponentUid(id); + container.setUniqueId(id); + GraphVertex graphVertex = new GraphVertex(); + when(janusGraphDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(graphVertex)); + when(janusGraphDao.updateVertex(graphVertex)).thenReturn(Either.left(graphVertex)); + when(topologyTemplateOperation.getToscaElement(anyString())).thenReturn(Either.left(toscaElement)); + + result = operation.updateComponentInstanceMetadataOfTopologyTemplate(container, toscaElement, componentInstance); + assertTrue(result.isLeft()); + } + + @Test + public void testGetDefaultHeatTimeout() { + Integer result; + + // default test + result = NodeTemplateOperation.getDefaultHeatTimeout(); + } + + @Test + public void testPrepareInstDeploymentArtifactPerInstance() { + Map deploymentResourceArtifacts = new HashMap<>(); + Map deploymentArtifacts = new HashMap<>(); + ArtifactDataDefinition artifactDataDefinition = new ArtifactDataDefinition(); + artifactDataDefinition.setArtifactType("HEAT"); + artifactDataDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + deploymentArtifacts.put("1", artifactDataDefinition); + deploymentResourceArtifacts.put("1", artifactDataDefinition); + String componentInstanceId = "componentInstanceId"; + User user = new User(); + user.setUserId("userId"); + user.setFirstName("first"); + user.setLastName("last"); + String envType = "VfHeatEnv"; + MapArtifactDataDefinition result; + + result = operation.prepareInstDeploymentArtifactPerInstance(deploymentArtifacts, componentInstanceId, user, + envType); + Assert.assertEquals(2, result.getMapToscaDataDefinition().size()); + } + + @Test + public void testCreateCapPropertyKey() throws Exception { + String key = ""; + String instanceId = ""; + String result; + + // default test + result = NodeTemplateOperation.createCapPropertyKey(key, instanceId); + } + + @Test + public void testPrepareCalculatedCapabiltyForNodeType() { + Map capabilities = new HashMap<>(); + ListCapabilityDataDefinition listCapDataDefinition = new ListCapabilityDataDefinition(); + List listToscaDataDefinition = new ArrayList<>(); + CapabilityDataDefinition capabilityDataDefinition = new CapabilityDefinition(); + capabilityDataDefinition.setMaxOccurrences("1"); + listToscaDataDefinition.add(capabilityDataDefinition); + listCapDataDefinition.setListToscaDataDefinition(listToscaDataDefinition); + capabilities.put("1", listCapDataDefinition); + ComponentInstance componentInstance = createCompInstance(); + MapListCapabilityDataDefinition result; + + result = operation.prepareCalculatedCapabiltyForNodeType(capabilities, componentInstance); + Assert.assertEquals(1, result.getMapToscaDataDefinition().size()); + } + + @Test + public void testPrepareCalculatedReqForNodeType() { + Map requirements = new HashMap<>(); + ListRequirementDataDefinition listReqDataDef = new ListRequirementDataDefinition(); + List listToscaDataDefinition = new ArrayList<>(); + RequirementDataDefinition reqDataDefinition = new RequirementDataDefinition(); + reqDataDefinition.setMaxOccurrences("1"); + listToscaDataDefinition.add(reqDataDefinition); + listReqDataDef.setListToscaDataDefinition(listToscaDataDefinition); + requirements.put("1", listReqDataDef); + ComponentInstance componentInstance = createCompInstance(); + MapListRequirementDataDefinition result; + + result = operation.prepareCalculatedRequirementForNodeType(requirements, componentInstance); + Assert.assertEquals(1, result.getMapToscaDataDefinition().size()); + } + + @Test + public void testAddGroupInstancesToComponentInstance() throws Exception { + Component containerComponent = null; + ComponentInstanceDataDefinition componentInstance = null; + List groups = null; + Map> groupInstancesArtifacts = null; + StorageOperationStatus result; + + result = operation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, + groupInstancesArtifacts); + Assert.assertEquals(StorageOperationStatus.OK, result); + } + + @Test + public void testGenerateCustomizationUUIDOnInstanceGroup() throws Exception { + String componentId = ""; + String instanceId = ""; + List groupInstances = null; + StorageOperationStatus result; + + result = operation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances); + Assert.assertEquals(StorageOperationStatus.OK, result); + } + + private ComponentInstance createCompInstance() { + ComponentInstance componentInstance = new ComponentInstance(); + String id = "id"; + componentInstance.setComponentUid(id); + componentInstance.setUniqueId(id); + componentInstance.setName(id); + return componentInstance; + } + private static void buildRequirementDataDefinition() { + buildRequirement(); + fulfilledRequirement = new HashMap<>(); + MapListRequirementDataDefinition mapListRequirementDataDefinition = new MapListRequirementDataDefinition(); + mapListRequirementDataDefinition.add(requirement.getCapability(), requirement); + fulfilledRequirement.put(FROM_INSTANCE_ID, mapListRequirementDataDefinition); + + } + + private static void buildRequirement() { + requirement = new RequirementDataDefinition(); + requirement.setOwnerId(REQUIREMENT_OWNER_ID); + requirement.setUniqueId(REQUIREMENT_UID); + requirement.setName(REQUIREMENT_NAME); + requirement.setRelationship(RELATIONSHIP_TYPE); + } + + private static void buildCapabiltyDataDefinition() { + buildCapability(); + fulfilledCapability = new HashMap<>(); + MapListCapabilityDataDefinition mapListCapabiltyDataDefinition = new MapListCapabilityDataDefinition(); + mapListCapabiltyDataDefinition.add(capability.getType(), capability); + fulfilledCapability.put(TO_INSTANCE_ID, mapListCapabiltyDataDefinition); + } + + private static void buildCapability() { + capability = new CapabilityDataDefinition(); + capability.setOwnerId(CAPABILITY_OWNER_ID); + capability.setUniqueId(CAPABILITY_UID); + capability.setName(CAPABILITY_NAME); + } + + private static void buildRelation() { + + relation = new RequirementCapabilityRelDef(); + CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship(); + RelationshipInfo relationInfo = new RelationshipInfo(); + relationInfo.setId(RELATION_ID); + relationship.setRelation(relationInfo); + + relation.setRelationships(Lists.newArrayList(relationship)); + relation.setToNode(TO_INSTANCE_ID); + relation.setFromNode(FROM_INSTANCE_ID); + + relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID); + relationInfo.setCapabilityUid(CAPABILITY_UID); + relationInfo.setCapability(CAPABILITY_NAME); + relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID); + relationInfo.setRequirementUid(REQUIREMENT_UID); + relationInfo.setRequirement(REQUIREMENT_NAME); + RelationshipImpl relationshipImpl = new RelationshipImpl(); + relationshipImpl.setType(RELATIONSHIP_TYPE); + relationInfo.setRelationships(relationshipImpl); + } + + private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) { + return req.getRelationship().equals(relationshipInfo.getRelationship().getType()) && + req.getName().equals(relationshipInfo.getRequirement()) && + req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && + req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId()); + } + + private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) { + return cap.getName().equals(relationshipInfo.getCapability()) && + cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && + cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId()); + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperationIntegrationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperationIntegrationTest.java new file mode 100644 index 0000000000..2740551b5c --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperationIntegrationTest.java @@ -0,0 +1,133 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +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.config.JanusGraphSpringConfig; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import javax.annotation.Resource; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static org.apache.commons.collections.ListUtils.union; +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {JanusGraphSpringConfig.class, ModelOperationsSpringConfig.class}) +public class PolicyOperationIntegrationTest extends ModelTestBase { + + private static final String CONTAINER_ID = "container"; + public static final String POLICY_ID = "policy"; + @Resource + private TopologyTemplateOperation topologyTemplateOperation; + @Resource + private HealingJanusGraphDao janusGraphDao; + @Resource + private PolicyOperation policyOperation; + private PropertyDataDefinition prop1, prop2; + private PolicyDefinition policy; + + @BeforeClass + public static void setupBeforeClass() { + + ModelTestBase.init(); + } + + @Before + public void setUp() throws Exception { + prop1 = new PropertyDataDefinition(); + prop1.setUniqueId("prop1"); + prop1.setName("prop1"); + prop1.setValue("prop1"); + + prop2 = new PropertyDataDefinition(); + prop2.setUniqueId("prop2"); + prop2.setName("prop2"); + prop2.setValue("prop2"); + + policy = new PolicyDefinition(); + policy.setUniqueId(POLICY_ID); + + policy.setProperties(Arrays.asList(prop1, prop2)); + + GraphVertex resource = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); + resource.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, CONTAINER_ID); + janusGraphDao.createVertex(resource); + GraphVertex loadedResource = janusGraphDao.getVertexById(CONTAINER_ID).left().value(); + topologyTemplateOperation.addToscaDataToToscaElement(loadedResource, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policy, JsonPresentationFields.UNIQUE_ID); +// janusGraphDao.commit(); + } + + @After + public void tearDown() { + janusGraphDao.rollback(); + } + + @Test + public void testUpdatePolicyProperties_singleProperty() { + PropertyDataDefinition prop1Copy = new PropertyDataDefinition(prop1); + prop1Copy.setValue("prop1NewValue"); + testUpdatePolicyProperties(Collections.singletonList(prop1Copy), Collections.singletonList(prop2)); + } + + @Test + public void testUpdatePolicyProperties_multipleProperties() { + PropertyDataDefinition prop1Copy = new PropertyDataDefinition(prop1); + prop1Copy.setValue("prop1NewValue"); + + PropertyDataDefinition prop2Copy = new PropertyDataDefinition(prop2); + prop2Copy.setValue("prop2NewValue"); + + testUpdatePolicyProperties(Arrays.asList(prop1Copy, prop2Copy), Collections.emptyList()); + } + + private void testUpdatePolicyProperties(List updatedProperties, List nonUpdatedPropeties) { + Component cmpt = new org.openecomp.sdc.be.model.Resource(); + cmpt.setUniqueId(CONTAINER_ID); + cmpt.setPolicies(Collections.singletonMap(POLICY_ID, policy)); + StorageOperationStatus storageOperationStatus = policyOperation.updatePolicyProperties(cmpt, POLICY_ID, updatedProperties); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnorePolicies(false); + Either loadedCmptEither = topologyTemplateOperation.getToscaElement(CONTAINER_ID, componentParametersView); + + assertThat(loadedCmptEither.isLeft()).isTrue(); + ToscaElement loadedCmpt = loadedCmptEither.left().value(); + assertThat(loadedCmpt).isInstanceOf(TopologyTemplate.class); + @SuppressWarnings("unchecked") List allProperties = union(updatedProperties, nonUpdatedPropeties); + verifyPolicyPropertiesValuesUpdated((TopologyTemplate) loadedCmpt, allProperties); + } + + private void verifyPolicyPropertiesValuesUpdated(TopologyTemplate toscaElement, List expectedUpdatedProperties) { + Map policies = toscaElement.getPolicies(); + PolicyDataDefinition policy = policies.get(POLICY_ID); + List policyProperties = policy.getProperties(); + assertThat(policyProperties).usingElementComparatorOnFields("value") + .containsAll(expectedUpdatedProperties); + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperationTest.java new file mode 100644 index 0000000000..1df6721612 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperationTest.java @@ -0,0 +1,94 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.Arrays; +import java.util.Collections; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyOperationTest { + + private static final String CONTAINER_ID = "containerId"; + private static final String POLICY_ID = "policyId"; + @InjectMocks + private PolicyOperation testInstance; + @Mock + private JanusGraphDao janusGraphDao; + @Mock + private TopologyTemplateOperation topologyTemplateOperation; + @Captor + private ArgumentCaptor policyDefCaptor; + private Component component; + private PolicyDefinition policyDefinition; + private PropertyDataDefinition prop1, prop2; + + @Before + public void setUp() throws Exception { + component = new Resource(); + component.setUniqueId(CONTAINER_ID); + policyDefinition = new PolicyDefinition(); + policyDefinition.setUniqueId(POLICY_ID); + prop1 = new PropertyDataDefinition(); + prop1.setName("prop1"); + prop1.setValue("prop1"); + + prop2 = new PropertyDataDefinition(); + prop2.setName("prop2"); + prop2.setValue("prop2"); + policyDefinition.setProperties(Arrays.asList(prop1, prop2)); + component.setPolicies(Collections.singletonMap(POLICY_ID, policyDefinition)); + } + + @Test + public void updatePolicyProperties_failedToFetchContainer() { + when(janusGraphDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.right( + JanusGraphOperationStatus.NOT_FOUND)); + StorageOperationStatus storageOperationStatus = testInstance.updatePolicyProperties(component, POLICY_ID, Collections.emptyList()); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.NOT_FOUND); + verifyZeroInteractions(topologyTemplateOperation); + } + + @Test + public void updatePolicyProperties_updateFailed() { + GraphVertex cmptVertex = new GraphVertex(); + when(janusGraphDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(cmptVertex)); + when(topologyTemplateOperation.updatePolicyOfToscaElement(cmptVertex, policyDefinition)).thenReturn(StorageOperationStatus.GENERAL_ERROR); + StorageOperationStatus storageOperationStatus = testInstance.updatePolicyProperties(component, POLICY_ID, Collections.emptyList()); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.GENERAL_ERROR); + } + + @Test + public void updatePolicyProperties() { + GraphVertex cmptVertex = new GraphVertex(); + when(janusGraphDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(cmptVertex)); + when(topologyTemplateOperation.updatePolicyOfToscaElement(eq(cmptVertex), policyDefCaptor.capture())).thenReturn(StorageOperationStatus.OK); + PropertyDataDefinition prop1Copy = new PropertyDataDefinition(prop1); + prop1Copy.setValue("prop1Copy"); + StorageOperationStatus storageOperationStatus = testInstance.updatePolicyProperties(component, POLICY_ID, Collections.singletonList(prop1Copy)); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); + assertThat(policyDefCaptor.getValue().getProperties()).usingElementComparatorOnFields("value") + .containsExactlyInAnyOrder(prop1Copy, prop2); + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperationCapabilityIntegrationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperationCapabilityIntegrationTest.java new file mode 100644 index 0000000000..f5dd3a0346 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperationCapabilityIntegrationTest.java @@ -0,0 +1,197 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +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.config.JanusGraphSpringConfig; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import javax.annotation.Resource; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {JanusGraphSpringConfig.class, ModelOperationsSpringConfig.class}) +public class TopologyTemplateOperationCapabilityIntegrationTest extends ModelTestBase { + + private static final String CONTAINER_ID = "id"; + private Map capabilitiesPropsMap; + private List capabilitiesProperties; + + @Resource + private TopologyTemplateOperation topologyTemplateOperation; + + @Resource + private HealingJanusGraphDao janusGraphDao; + private CapabilityPropertyDataObject capabilityProperty1; + private CapabilityPropertyDataObject capabilityProperty2; + private CapabilityPropertyDataObject capabilityProperty3; + + @BeforeClass + public static void setupBeforeClass() { + + ModelTestBase.init(); + } + + @Before + public void setUp() throws Exception { + + capabilitiesPropsMap = new HashMap<>(); + capabilityProperty1 = new CapabilityPropertyDataObject("instance1", "capability1", "prop1", "val1"); + capabilityProperty2 = new CapabilityPropertyDataObject("instance1", "capability2", "prop2", "val2"); + capabilityProperty3 = new CapabilityPropertyDataObject("instance2", "capability3", "prop3", "val3"); + capabilitiesProperties = Arrays.asList(capabilityProperty1, capabilityProperty2, capabilityProperty3); + + + //capablities props == Map>> + capabilitiesProperties.forEach(capabilitiesProperty -> { + capabilitiesPropsMap.computeIfAbsent(capabilitiesProperty.getInstanceId(), k -> new MapCapabilityProperty(new HashMap<>())) + .getMapToscaDataDefinition().computeIfAbsent(capabilitiesProperty.getCapabilityId(), k -> new MapPropertiesDataDefinition(new HashMap<>())) + .getMapToscaDataDefinition().computeIfAbsent(capabilitiesProperty.getPropName(), k -> new PropertyDefinition(createPropWithValue(capabilitiesProperty.getPropValue()))); + }); + + GraphVertex resource = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); + resource.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, CONTAINER_ID); + janusGraphDao.createVertex(resource); + GraphVertex loadedResource = janusGraphDao.getVertexById(CONTAINER_ID).left().value(); + topologyTemplateOperation.associateElementToData(loadedResource, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilitiesPropsMap).left().value(); + } + + @After + public void tearDown() { + janusGraphDao.rollback(); + } + + @Test + public void overrideCalculatedCapabilityProperties() { + Map loadedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID); + compareCapabilitiesProperties(capabilitiesProperties, loadedCapPropsMap); + capabilityProperty1.setPropValue("newVal1"); + capabilityProperty3.setPropValue("newVal3"); + setPropertyValue(capabilitiesPropsMap, capabilityProperty1); + setPropertyValue(capabilitiesPropsMap, capabilityProperty3); + StorageOperationStatus storageOperationStatus = topologyTemplateOperation.overrideToscaDataOfToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilitiesPropsMap); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); + Map updatedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID); + compareCapabilitiesProperties(capabilitiesProperties, updatedCapPropsMap); + } + + @Test + public void updateToscaDataDeepElementsBlockToToscaElement() { + assertCapabilityPropValue(capabilityProperty1, "val1"); + assertCapabilityPropValue(capabilityProperty2, "val2"); + assertCapabilityPropValue(capabilityProperty3, "val3"); + + MapCapabilityProperty instance1Props = capabilitiesPropsMap.get("instance1"); + capabilityProperty1.setPropValue("newVal1"); + setPropertyValue(capabilitiesPropsMap, capabilityProperty1); + + capabilityProperty3.setPropValue("newVal3"); + setPropertyValue(capabilitiesPropsMap, capabilityProperty3); + + Component component = new org.openecomp.sdc.be.model.Resource(); + component.setUniqueId(CONTAINER_ID); + StorageOperationStatus updateStatus = topologyTemplateOperation.updateToscaDataDeepElementsBlockToToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, instance1Props, "instance1"); + + assertThat(updateStatus).isEqualTo(StorageOperationStatus.OK); + assertCapabilityPropValue(capabilityProperty1, "newVal1"); + assertCapabilityPropValue(capabilityProperty2, "val2"); + assertCapabilityPropValue(capabilityProperty3, "val3");//only instance1 props should be updated + } + + private Map fetchCapabilitiesProps(String containerId) { + ComponentParametersView capabilityPropsFilter = new ComponentParametersView(true); + capabilityPropsFilter.setIgnoreCapabiltyProperties(false); + return ((TopologyTemplate) topologyTemplateOperation.getToscaElement(containerId, capabilityPropsFilter).left().value()).getCalculatedCapabilitiesProperties(); + } + + private void compareCapabilitiesProperties(List expected, Map actual) { + expected.forEach(expectedCapabilityProp -> { + assertThat(getPropertyValue(actual, expectedCapabilityProp.instanceId, expectedCapabilityProp.capabilityId, expectedCapabilityProp.propName)) + .isEqualTo(expectedCapabilityProp.propValue); + }); + } + + private String getPropertyValue(Map capabilityPropertyMap, String instance, String capability, String prop) { + return capabilityPropertyMap.get(instance).getMapToscaDataDefinition().get(capability).getMapToscaDataDefinition().get(prop).getValue(); + } + + private void setPropertyValue(Map capabilityPropertyMap, CapabilityPropertyDataObject capabilityProperty) { + setPropertyValue(capabilityPropertyMap.get(capabilityProperty.getInstanceId()), capabilityProperty); + + } + + private void setPropertyValue(MapCapabilityProperty capabilitiesInstanceProperties, CapabilityPropertyDataObject capabilityProperty) { + capabilitiesInstanceProperties.getMapToscaDataDefinition().get(capabilityProperty.getCapabilityId()) + .getMapToscaDataDefinition().get(capabilityProperty.getPropName()) + .setValue(capabilityProperty.getPropValue()); + } + + private void assertCapabilityPropValue(CapabilityPropertyDataObject prop, String expectedValue) { + Map loadedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID); + String propertyValue = getPropertyValue(loadedCapPropsMap, prop.getInstanceId(), prop.getCapabilityId(), prop.getPropName()); + assertThat(propertyValue).isEqualTo(expectedValue); + } + + + private PropertyDefinition createPropWithValue(String val) { + PropertyDefinition propertyDefinition = new PropertyDefinition(); + propertyDefinition.setValue(val); + return propertyDefinition; + } + + private static class CapabilityPropertyDataObject { + private String instanceId; + private String capabilityId; + private String propName; + private String propValue; + + CapabilityPropertyDataObject(String instanceId, String capabilityId, String propName, String propValue) { + this.instanceId = instanceId; + this.capabilityId = capabilityId; + this.propName = propName; + this.propValue = propValue; + } + + String getInstanceId() { + return instanceId; + } + + String getCapabilityId() { + return capabilityId; + } + + String getPropName() { + return propName; + } + + String getPropValue() { + return propValue; + } + + void setPropValue(String propValue) { + this.propValue = propValue; + } + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperationTest.java new file mode 100644 index 0000000000..bc3c7cc8bd --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperationTest.java @@ -0,0 +1,185 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import org.janusgraph.core.JanusGraphVertex; +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; + +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +//error scenarios +public class TopologyTemplateOperationTest { + + private static final String CONTAINER_ID = "containerId"; + @InjectMocks + private TopologyTemplateOperation topologyTemplateOperation; + @Mock + private JanusGraphDao janusGraphDao; + + @Test + public void overrideToscaDataOfToscaElement_failedToFetchContainerVertex() { + when(janusGraphDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.right( + JanusGraphOperationStatus.INVALID_ID)); + StorageOperationStatus storageOperationStatus = topologyTemplateOperation.overrideToscaDataOfToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, Collections.emptyMap()); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.INVALID_ID); + } + + @Test + public void overrideToscaDataOfToscaElement_failedToFetchDataVertex() { + GraphVertex containerVertex = new GraphVertex(); + when(janusGraphDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(containerVertex)); + when(janusGraphDao.getChildVertex(containerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, JsonParseFlagEnum.ParseJson)).thenReturn(Either.right( + JanusGraphOperationStatus.NOT_FOUND)); + StorageOperationStatus storageOperationStatus = topologyTemplateOperation.overrideToscaDataOfToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, Collections.emptyMap()); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.NOT_FOUND); + } + + @Test + public void updateToscaDataDeepElements_failedToFetchContainerVertex() { + when(janusGraphDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.right( + JanusGraphOperationStatus.INVALID_ID)); + StorageOperationStatus storageOperationStatus = topologyTemplateOperation.updateToscaDataDeepElementsBlockToToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, new MapCapabilityProperty(), ""); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.INVALID_ID); + } + + @Test + public void updateToscaDataDeepElements_failedToFetchDataVertex() { + GraphVertex containerVertex = new GraphVertex(); + when(janusGraphDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(containerVertex)); + when(janusGraphDao.getChildVertex(containerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, JsonParseFlagEnum.ParseJson)).thenReturn(Either.right( + JanusGraphOperationStatus.NOT_FOUND)); + StorageOperationStatus storageOperationStatus = topologyTemplateOperation.updateToscaDataDeepElementsBlockToToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, new MapCapabilityProperty(), ""); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.NOT_FOUND); + } + + @Test + public void addPolicyToToscaElementSuccessTest(){ + JanusGraphOperationStatus status = JanusGraphOperationStatus.OK; + StorageOperationStatus result = addPolicyToToscaElementWithStatus(status); + assertThat(result).isEqualTo(StorageOperationStatus.OK); + } + + @Test + public void addPolicyToToscaElementFailureTest(){ + JanusGraphOperationStatus status = JanusGraphOperationStatus.ALREADY_EXIST; + StorageOperationStatus result = addPolicyToToscaElementWithStatus(status); + assertThat(result).isEqualTo(StorageOperationStatus.ENTITY_ALREADY_EXISTS); + } + + @Test + public void testAssociateOrAddCalcCapReqToComponent() { + StorageOperationStatus result; + GraphVertex graphVertex = new GraphVertex(); + Map calcRequirements = new HashMap<>(); + Map calcCapabilty = new HashMap<>(); + Map calCapabilitiesProps = new HashMap<>(); + addPolicyToToscaElementWithStatus(JanusGraphOperationStatus.OK); + result = topologyTemplateOperation.associateOrAddCalcCapReqToComponent(graphVertex, calcRequirements, calcCapabilty, calCapabilitiesProps); + assertEquals(StorageOperationStatus.OK, result); + } + + @Test + public void testSetDataTypesFromGraph() { + GraphVertex containerVertex = new GraphVertex(); + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreComponentInstancesInterfaces(true); + filter.setIgnoreDataType(false); + String componentName = "componentName"; + String componentId = UniqueIdBuilder.buildResourceUniqueId(); + containerVertex.setVertex(Mockito.mock(JanusGraphVertex.class)); + containerVertex.setJsonMetadataField(JsonPresentationFields.NAME, componentName); + containerVertex.setUniqueId(componentId); + containerVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); + when(janusGraphDao.getChildVertex(any(GraphVertex.class), any(EdgeLabelEnum.class), any(JsonParseFlagEnum.class))).thenReturn(Either.right( + JanusGraphOperationStatus.GENERAL_ERROR)); + Either storageOperationStatus = topologyTemplateOperation.getToscaElement(containerVertex, filter); + assertThat(storageOperationStatus).isEqualTo(Either.right(StorageOperationStatus.GENERAL_ERROR)); + } + + @Test + public void testUpdateDistributionStatus() { + Either result; + String uniqueId = "uniqueId"; + User user = new User(); + String userId = "userId"; + user.setUserId(userId); + Iterator edgeIterator = new Iterator() { + @Override + public boolean hasNext() { + return false; + } + + @Override + public Edge next() { + return null; + } + }; + GraphVertex graphVertex = Mockito.mock(GraphVertex.class); + JanusGraphVertex janusGraphVertex = Mockito.mock(JanusGraphVertex.class); + when(graphVertex.getVertex()).thenReturn(janusGraphVertex); + when(janusGraphVertex.edges(Direction.IN, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER.name())).thenReturn(edgeIterator); + when(janusGraphDao + .getVertexByPropertyAndLabel(GraphPropertyEnum.USERID, userId, VertexTypeEnum.USER, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex)); + when(janusGraphDao.getVertexById(uniqueId, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(graphVertex)); + when(janusGraphDao.createEdge(graphVertex, graphVertex, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER, null)).thenReturn( + JanusGraphOperationStatus.OK); + when(janusGraphDao.updateVertex(graphVertex)).thenReturn(Either.left(graphVertex)); + result = topologyTemplateOperation.updateDistributionStatus(uniqueId, user, DistributionStatusEnum.DISTRIBUTED); + assertThat(result.isLeft()); + } + + @SuppressWarnings("unchecked") + private StorageOperationStatus addPolicyToToscaElementWithStatus(JanusGraphOperationStatus status) { + GraphVertex componentV = new GraphVertex(); + componentV.setVertex(Mockito.mock(JanusGraphVertex.class)); + GraphVertex dataV = new GraphVertex(); + dataV.setVertex(Mockito.mock(JanusGraphVertex.class)); + String componentName = "componentName"; + String componentId = UniqueIdBuilder.buildResourceUniqueId(); + String policyTypeName = "org.openecomp.policies.placement.valet.Affinity"; + componentV.setJsonMetadataField(JsonPresentationFields.NAME, componentName); + componentV.setUniqueId(componentId); + PolicyDefinition policy = new PolicyDefinition(); + policy.setPolicyTypeName(policyTypeName); + int counter = 0; + Either toscaDataVertexRes = Either.right( + JanusGraphOperationStatus.NOT_FOUND); + when(janusGraphDao.getChildVertex(eq(componentV), eq(EdgeLabelEnum.POLICIES), eq(JsonParseFlagEnum.ParseJson))).thenReturn(toscaDataVertexRes); + Either createVertex = Either.left(dataV); + when(janusGraphDao.createVertex(any(GraphVertex.class))).thenReturn(createVertex); + when(janusGraphDao.createEdge(any(JanusGraphVertex.class), any(JanusGraphVertex.class), any(EdgeLabelEnum.class), any(HashMap.class))).thenReturn(status); + return topologyTemplateOperation.addPolicyToToscaElement(componentV, policy, counter); + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperationCatalogTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperationCatalogTest.java new file mode 100644 index 0000000000..eeb7e17323 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperationCatalogTest.java @@ -0,0 +1,73 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.model.catalog.CatalogComponent; + +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; + +@RunWith(MockitoJUnitRunner.class) +public class ToscaElementOperationCatalogTest { + + private ArrayList vertexList = new ArrayList<>(); + + @Mock + Vertex vertex; + @Mock + JanusGraphDao janusGraphDao; + @Mock + VertexProperty property; + + @InjectMocks + private ToscaElementOperation toscaOperation = new TopologyTemplateOperation(); + + @Before + public void setUp() { + vertexList.add(vertex); + when(janusGraphDao.getCatalogOrArchiveVerticies(true)).thenReturn(Either.left(vertexList.iterator())); + when(janusGraphDao.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse)) + .thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); + when(vertex.property(GraphPropertiesDictionary.METADATA.getProperty())).thenReturn(property); + } + + @Test + public void getComponentFromCatalogWhenDeleteIsTrue() { + final String vertexJsonIsDeletedTrue = "{\"lifecycleState\":\"CERTIFIED\",\"componentType\":\"RESOURCE\",\"vendorRelease\":\"1\",\"contactId\":\"ah7840\",\"lastUpdateDate\":1496119811038,\"icon\":\"att\",\"description\":\"Cloud\",\"creationDate\":1459432094781,\"vendorName\":\"AT&T\",\"mandatory\":false,\"version\":\"1.0\",\"tags\":[\"Cloud\"],\"highestVersion\":true,\"systemName\":\"Cloud\",\"name\":\"Cloud\",\"isDeleted\":true,\"invariantUuid\":\"ab5263fd-115c-41f2-8d0c-8b9279bce2b2\",\"UUID\":\"208cf7df-68a1-4ae7-afc9-409ea8012332\",\"normalizedName\":\"cloud\",\"toscaResourceName\":\"org.openecomp.resource.Endpoint.Cloud\",\"uniqueId\":\"9674e7e1-bc1a-41fe-b503-fbe996801475\",\"resourceType\":\"VFC\"}"; + when(property.value()).thenReturn(vertexJsonIsDeletedTrue); + List componentList = toscaOperation.getElementCatalogData(true, null).left().value(); + assertTrue(componentList.isEmpty()); + } + + @Test + public void getComponentFromCatalogWhenDeleteNotFound() { + final String vertexJsonIsDeletedNotFound = "{\"lifecycleState\":\"CERTIFIED\",\"componentType\":\"RESOURCE\",\"vendorRelease\":\"1\",\"contactId\":\"ah7840\",\"lastUpdateDate\":1496119811038,\"icon\":\"att\",\"description\":\"Cloud\",\"creationDate\":1459432094781,\"vendorName\":\"AT&T\",\"mandatory\":false,\"version\":\"1.0\",\"tags\":[\"Cloud\"],\"highestVersion\":true,\"systemName\":\"Cloud\",\"name\":\"Cloud\",\"invariantUuid\":\"ab5263fd-115c-41f2-8d0c-8b9279bce2b2\",\"UUID\":\"208cf7df-68a1-4ae7-afc9-409ea8012332\",\"normalizedName\":\"cloud\",\"toscaResourceName\":\"org.openecomp.resource.Endpoint.Cloud\",\"uniqueId\":\"9674e7e1-bc1a-41fe-b503-fbe996801475\",\"resourceType\":\"VFC\"}"; + when(property.value()).thenReturn(vertexJsonIsDeletedNotFound); + List componentList = toscaOperation.getElementCatalogData(true, null).left().value(); + assertEquals(1, componentList.size()); + } + + @Test + public void getComponentFromCatalogWhenDeleteIsFalse() { + final String vertexJsonIsDeletedFalse = "{\"lifecycleState\":\"CERTIFIED\",\"componentType\":\"RESOURCE\",\"vendorRelease\":\"1\",\"contactId\":\"ah7840\",\"lastUpdateDate\":1496119811038,\"icon\":\"att\",\"description\":\"Cloud\",\"creationDate\":1459432094781,\"vendorName\":\"AT&T\",\"mandatory\":false,\"version\":\"1.0\",\"tags\":[\"Cloud\"],\"highestVersion\":true,\"systemName\":\"Cloud\",\"name\":\"Cloud\",\"isDeleted\":false,\"invariantUuid\":\"ab5263fd-115c-41f2-8d0c-8b9279bce2b2\",\"UUID\":\"208cf7df-68a1-4ae7-afc9-409ea8012332\",\"normalizedName\":\"cloud\",\"toscaResourceName\":\"org.openecomp.resource.Endpoint.Cloud\",\"uniqueId\":\"9674e7e1-bc1a-41fe-b503-fbe996801475\",\"resourceType\":\"VFC\"}"; + when(property.value()).thenReturn(vertexJsonIsDeletedFalse); + List componentList = toscaOperation.getElementCatalogData(true, null).left().value(); + assertEquals(1, componentList.size()); + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperationTest.java new file mode 100644 index 0000000000..205899d52f --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperationTest.java @@ -0,0 +1,363 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TestName; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.GraphTestUtils; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Created by chaya on 6/12/2017. + */ + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class ToscaElementOperationTest extends ModelTestBase{ + + private List allVertices = new ArrayList<>(); + private boolean isInitialized = false; + + @javax.annotation.Resource + private ToscaElementOperationTestImpl toscaElementOperation; + + @javax.annotation.Resource + private JanusGraphDao janusGraphDao; + + @BeforeClass + public static void initTest(){ + ModelTestBase.init(); + + } + + @Rule + public TestName testName = new TestName(); + + @Before + public void beforeTest() { + if (!isInitialized) { + GraphTestUtils.clearGraph(janusGraphDao); + //exportGraphMl(janusGraphDao.getGraph().left().value(),""); + initGraphForTest(); + isInitialized = true; + } + } + + + @Test + public void testGetAllHighestResourcesNoFilter() { + + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, null, true); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + } + }, null); + assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); + } + + + + + @Test + public void testGetAllResourcesCertifiedNoFilter() { + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, null, false); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + } + }, null); + highestResourcesExpectedCount += calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + } + }, new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + } + }); + assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); + } + + @Test + public void testGetHighestResourcesExclude() { + + // exclude VFCMT + List excludeList = Arrays.asList(ResourceTypeEnum.VFCMT); + assertTrue(genericTestGetResourcesWithExcludeList(excludeList)); + + // exclude CP & VL + excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP); + assertTrue(genericTestGetResourcesWithExcludeList(excludeList)); + + // exclude CP & VL & VF & VFC + excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP, ResourceTypeEnum.VF, ResourceTypeEnum.VFC); + assertTrue(genericTestGetResourcesWithExcludeList(excludeList)); + } + + @Test + public void testGetAllResourcesCertifiedExclude() { + // exclude VFCMT + List excludeList = Arrays.asList(ResourceTypeEnum.VFCMT); + assertTrue(genericTestGetCertifiedResourcesWithExcludeList(excludeList)); + + // exclude CP & VL + excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP); + assertTrue(genericTestGetCertifiedResourcesWithExcludeList(excludeList)); + + // exclude CP & VL & VF & VFC + excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP, ResourceTypeEnum.VF, ResourceTypeEnum.VFC); + assertTrue(genericTestGetCertifiedResourcesWithExcludeList(excludeList)); + } + + @Test + public void testGetAllHighestServicesNoFilter() { + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, true); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + } + }, null); + assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); + } + + @Test + public void testGetAllCertifiedServicesNoFilter() { + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, false); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + } + }, null); + highestResourcesExpectedCount += calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + } + }, new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + } + }); + assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); + } + + @Test + public void testGetServicesExcludeList() { + List excludeList = Arrays.asList(ResourceTypeEnum.VF, ResourceTypeEnum.VFCMT); + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, excludeList, true); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + } + }, null); + assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); + } + + @Test + public void testGetCertifiedServicesExcludeList() { + List excludeList = Arrays.asList(ResourceTypeEnum.VL); + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, excludeList, false); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + } + }, null); + highestResourcesExpectedCount += calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + } + }, new HashMap() { + { + put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + } + }); + assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); + } + + @Test + public void testUpdateToscaElement_NotFound() { + Either result; + TopologyTemplate topologyTemplate = new TopologyTemplate(); + String userID = "userID"; + topologyTemplate.setLastUpdaterUserId(userID); + GraphVertex graphVertex = new GraphVertex(); + ComponentParametersView componentParametersView = new ComponentParametersView(); + result = toscaElementOperation.updateToscaElement(topologyTemplate, graphVertex, componentParametersView); + assertEquals(null, result); + } + + private boolean genericTestGetResourcesWithExcludeList(List excludeList) { + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE,excludeList, true); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + } + }, new HashMap() { + { + put(GraphPropertyEnum.RESOURCE_TYPE, excludeList); + } + }); + return highestResources.stream().count() == (highestResourcesExpectedCount); + } + + private boolean genericTestGetCertifiedResourcesWithExcludeList(List excludeList) { + Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludeList, false); + assertTrue(highestResourcesRes.isLeft()); + List highestResources = highestResourcesRes.left().value(); + // calculate expected count value + long highestResourcesExpectedCount = calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + } + }, new HashMap() { + { + put(GraphPropertyEnum.RESOURCE_TYPE, excludeList); + } + }); + highestResourcesExpectedCount += calculateCount(new HashMap() { + { + put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + } + }, new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + put(GraphPropertyEnum.RESOURCE_TYPE, excludeList); + } + }); + return highestResources.stream().count() == highestResourcesExpectedCount; + } + + private void initGraphForTest() { + GraphTestUtils.createRootCatalogVertex(janusGraphDao); + + Map highstVerticesProps = new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + } + }; + + Map certifiedVerticesProps = new HashMap() { + { + put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + } + }; + + // add vertices with higestVersion = true + allVertices.add(GraphTestUtils.createResourceVertex(janusGraphDao, highstVerticesProps, ResourceTypeEnum.VF)); + allVertices.add(GraphTestUtils.createResourceVertex(janusGraphDao, highstVerticesProps, ResourceTypeEnum.VFC)); + allVertices.add(GraphTestUtils.createResourceVertex(janusGraphDao, highstVerticesProps, ResourceTypeEnum.VFCMT)); + allVertices.add(GraphTestUtils.createResourceVertex(janusGraphDao, highstVerticesProps, ResourceTypeEnum.VL)); + allVertices.add(GraphTestUtils.createResourceVertex(janusGraphDao, highstVerticesProps, ResourceTypeEnum.CP)); + allVertices.add(GraphTestUtils.createServiceVertex(janusGraphDao, highstVerticesProps)); + + // add vertices with non-additional properties + for (int i=0 ; i<2 ; i++) { + allVertices.add(GraphTestUtils.createResourceVertex(janusGraphDao, new HashMap<>(), ResourceTypeEnum.VF)); + allVertices.add(GraphTestUtils.createResourceVertex(janusGraphDao, new HashMap<>(), ResourceTypeEnum.VFC)); + allVertices.add(GraphTestUtils.createResourceVertex(janusGraphDao, new HashMap<>(), ResourceTypeEnum.VFCMT)); + allVertices.add(GraphTestUtils.createResourceVertex(janusGraphDao, new HashMap<>(), ResourceTypeEnum.VL)); + allVertices.add(GraphTestUtils.createResourceVertex(janusGraphDao, new HashMap<>(), ResourceTypeEnum.CP)); + allVertices.add(GraphTestUtils.createServiceVertex(janusGraphDao, new HashMap<>())); + } + + // add certified vertices + for (int i=0; i<3; i++) { + allVertices.add(GraphTestUtils.createResourceVertex(janusGraphDao, certifiedVerticesProps, ResourceTypeEnum.VF)); + allVertices.add(GraphTestUtils.createResourceVertex(janusGraphDao, certifiedVerticesProps, ResourceTypeEnum.VFC)); + allVertices.add(GraphTestUtils.createResourceVertex(janusGraphDao, certifiedVerticesProps, ResourceTypeEnum.VFCMT)); + allVertices.add(GraphTestUtils.createResourceVertex(janusGraphDao, certifiedVerticesProps, ResourceTypeEnum.VL)); + allVertices.add(GraphTestUtils.createResourceVertex(janusGraphDao, certifiedVerticesProps, ResourceTypeEnum.CP)); + allVertices.add(GraphTestUtils.createServiceVertex(janusGraphDao, certifiedVerticesProps)); + } + //allVertices.stream().forEach( v -> System.out.println("type: "+v.getMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE))); + //String result = GraphTestUtils.exportGraphMl(janusGraphDao.getGraph().left().value(), ""); + //System.out.println("graph is: " + result); + } + + private long calculateCount(HashMap hasProps, Map doesntHaveProps){ + return allVertices.stream(). + filter(v -> { + Map vertexProps = v.getMetadataProperties(); + if (hasProps != null) { + for (Map.Entry prop: hasProps.entrySet()){ + Object value = vertexProps.get(prop.getKey()); + if ( value == null || !value.equals(prop.getValue())) { + return false; + } + } + } + + if (doesntHaveProps != null) { + for (Map.Entry prop : doesntHaveProps.entrySet()) { + Object value = vertexProps.get(prop.getKey()); + Object propValue = prop.getValue(); + if ( value != null && propValue != null && propValue instanceof List ) { + for (ResourceTypeEnum propVal : (List)propValue) { + if (propVal.name().equals(value)) { + return false; + } + } + } + else if (value != null && value.equals(propValue)){ + return false; + } + } + } + return true; + }).count(); + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperationTestImpl.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperationTestImpl.java new file mode 100644 index 0000000000..01e14cd588 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperationTestImpl.java @@ -0,0 +1,74 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +/** + * Created by cb478c on 6/13/2017. + */ +@org.springframework.stereotype.Component("test-tosca-element-operation") +public class ToscaElementOperationTestImpl extends ToscaElementOperation { + + @Override + protected Either getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) { + janusGraphDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata); + T toscaElement = convertToComponent(vertexComponent); + return Either.left(toscaElement); + } + + @Override + public Either getToscaElement(String uniqueId, ComponentParametersView componentParametersView) { + return null; + } + + @Override + public Either getToscaElement(GraphVertex toscaElementVertex, ComponentParametersView componentParametersView) { + return null; + } + + @Override + public Either deleteToscaElement(GraphVertex toscaElementVertex) { + return null; + } + + @Override + public Either createToscaElement(ToscaElement toscaElement) { + return null; + } + + @Override + protected JanusGraphOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) { + return null; + } + + @Override + protected JanusGraphOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) { + return null; + } + + @Override + protected JanusGraphOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) { + return null; + } + + @Override + protected StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) { + return null; + } + + @Override + protected StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV) { + return null; + } + + @Override + public void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) { + + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacadePoliciesTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacadePoliciesTest.java new file mode 100644 index 0000000000..88d3db68c6 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacadePoliciesTest.java @@ -0,0 +1,134 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +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.config.JanusGraphSpringConfig; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao; +import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {JanusGraphSpringConfig.class, ModelOperationsSpringConfig.class}) +public class ToscaOperationFacadePoliciesTest extends ModelTestBase { + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + @Autowired + private HealingJanusGraphDao janusGraphDao; + + private PolicyDefinition policy1, policy2; + + @BeforeClass + public static void setupBeforeClass() { + ModelTestBase.init(); + } + + @Before + public void setUp() throws Exception { + policy1 = createPolicyDefinition("type1"); + policy2 = createPolicyDefinition("type2"); + createContainerVertexInDB(); + createPoliciesOnGraph(policy1, policy2); + } + + private void createPoliciesOnGraph(PolicyDefinition ... policies) { + for (int i = 0; i < policies.length; i++) { + PolicyDefinition policy = policies[i]; + Either createdPolicy = toscaOperationFacade.associatePolicyToComponent(CONTAINER_ID, policy, i); + assertTrue(createdPolicy.isLeft()); + } + } + + @After + public void tearDown() { + janusGraphDao.rollback(); + } + + @Test + public void updatePoliciesTargetsOfComponent_updateSinglePolicy() { + List updatedTargetIds = asList("instance1new", "instance2"); + PolicyDefinition originalPolicy2 = clonePolicyWithTargets(policy2); + updatePolicyTypeTargetsIds(policy1, PolicyTargetType.COMPONENT_INSTANCES, updatedTargetIds); + updatePolicyTypeTargetsIds(policy2, PolicyTargetType.COMPONENT_INSTANCES, updatedTargetIds); + + StorageOperationStatus storageOperationStatus = toscaOperationFacade.updatePoliciesOfComponent(CONTAINER_ID, singletonList(policy1)); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); + Component updatedComponent = fetchComponentFromDB(); + verifyPolicyTargets(updatedComponent.getPolicyById(policy1.getUniqueId()), policy1); + verifyPolicyTargets(updatedComponent.getPolicyById(policy2.getUniqueId()), originalPolicy2); + } + + @Test + public void updatePoliciesTargetsOfComponent_updateMultiplePolicies() { + List updatedTargetIds = asList("instance1new", "instance2"); + updatePolicyTypeTargetsIds(policy1, PolicyTargetType.COMPONENT_INSTANCES, updatedTargetIds); + updatePolicyTypeTargetsIds(policy2, PolicyTargetType.COMPONENT_INSTANCES, updatedTargetIds); + StorageOperationStatus storageOperationStatus = toscaOperationFacade.updatePoliciesOfComponent(CONTAINER_ID, asList(policy1, policy2)); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); + Component updatedComponent = fetchComponentFromDB(); + verifyPolicyTargets(updatedComponent.getPolicyById(policy1.getUniqueId()), policy1); + verifyPolicyTargets(updatedComponent.getPolicyById(policy2.getUniqueId()), policy2); + } + + private PolicyDefinition clonePolicyWithTargets(PolicyDefinition policy) { + PolicyDefinition originalPolicy = new PolicyDefinition(policy); + Map> clonedTargetMap = policy.getTargets().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> new ArrayList<>(entry.getValue()))); + originalPolicy.setTargets(clonedTargetMap); + return originalPolicy; + } + + private void verifyPolicyTargets(PolicyDefinition updatedPolicy, PolicyDefinition expectedPolicy) { + assertThat(updatedPolicy.getTargets()) + .isEqualTo(expectedPolicy.getTargets()); + } + + private void updatePolicyTypeTargetsIds(PolicyDefinition policy, PolicyTargetType targetType, List updatedTargetIds) { + policy.getTargets().put(targetType, updatedTargetIds); + } + + private Component fetchComponentFromDB() { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnorePolicies(false); + return toscaOperationFacade.getToscaElement(CONTAINER_ID, componentParametersView).left().value(); + } + + private void createContainerVertexInDB() { + GraphVertex resource = createBasicContainerGraphVertex(); + Either container = janusGraphDao.createVertex(resource); + assertTrue(container.isLeft()); + } + + private PolicyDefinition createPolicyDefinition(String type) { + PolicyDefinition policy = new PolicyDefinition(); + policy.setPolicyTypeName(type); + policy.setTargets(new HashMap<>()); + policy.getTargets().put(PolicyTargetType.COMPONENT_INSTANCES, asList("instance1", "instance2")); + return policy; + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacadeTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacadeTest.java new file mode 100644 index 0000000000..1bbbd1c087 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacadeTest.java @@ -0,0 +1,692 @@ +/* + + * Copyright (c) 2018 AT&T Intellectual Property. + + * + + * 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. + + */ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.ArgumentMatchers; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.NodeType; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.Set; +import java.util.HashSet; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.Collections; +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; + +@RunWith(MockitoJUnitRunner.class) +public class ToscaOperationFacadeTest { + private static final String COMPONENT_ID = "componentId"; + private static final String PROPERTY1_NAME = "prop1"; + private static final String PROPERTY1_TYPE = "string"; + private static final String PROPERTY2_NAME = "prop2"; + private static final String PROPERTY2_TYPE = "integer"; + + @InjectMocks + private ToscaOperationFacade testInstance; + + @Mock + private HealingJanusGraphDao janusGraphDaoMock; + + @Mock + private TopologyTemplateOperation topologyTemplateOperationMock; + + @Mock + private NodeTypeOperation nodeTypeOperation; + + @Mock + private NodeTemplateOperation nodeTemplateOperationMock; + + @Before + public void setUp() throws Exception { + testInstance = new ToscaOperationFacade(); + MockitoAnnotations.initMocks(this); + } + + @SuppressWarnings("unchecked") + @Test + public void fetchMetaDataByResourceType() throws Exception { + ArgumentCaptor criteriaCapture = ArgumentCaptor.forClass(Map.class); + ArgumentCaptor criteriaNotCapture = ArgumentCaptor.forClass(Map.class); + ComponentParametersView dataFilter = new ComponentParametersView(); + List mockVertices = getMockVertices(2); + Either, JanusGraphOperationStatus> returnedVertices = Either.left(mockVertices); + + when(janusGraphDaoMock.getByCriteria(eq(null), criteriaCapture.capture(), criteriaNotCapture.capture(), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(returnedVertices); + when(topologyTemplateOperationMock.getToscaElement(mockVertices.get(0), dataFilter)).thenReturn(Either.left(getResourceToscaElement("0"))); + when(topologyTemplateOperationMock.getToscaElement(mockVertices.get(1), dataFilter)).thenReturn(Either.left(getResourceToscaElement("1"))); + Either, StorageOperationStatus> fetchedComponents = testInstance.fetchMetaDataByResourceType(ResourceTypeEnum.VF.getValue(), dataFilter); + + verifyCriteriaForHighestVersionAndVfResourceType(criteriaCapture); + verifyCriteriaNotIsDeleted(criteriaNotCapture); + + assertTrue(fetchedComponents.isLeft()); + List cmpts = fetchedComponents.left().value(); + assertEquals(2, cmpts.size()); + assertEquals("0", cmpts.get(0).getUniqueId()); + assertEquals("1", cmpts.get(1).getUniqueId()); + } + + private void verifyCriteriaForHighestVersionAndVfResourceType(ArgumentCaptor criteriaCapture) { + Map criteria = (Map)criteriaCapture.getValue(); + assertEquals(2, criteria.size()); + assertEquals(criteria.get(GraphPropertyEnum.RESOURCE_TYPE), "VF"); + assertEquals(criteria.get(GraphPropertyEnum.IS_HIGHEST_VERSION), true); + } + + private void verifyCriteriaNotIsDeleted(ArgumentCaptor criteriaNotCapture) { + Map notCriteria = (Map)criteriaNotCapture.getValue(); + assertEquals(1, notCriteria.size()); + assertEquals(notCriteria.get(GraphPropertyEnum.IS_DELETED), true); + } + + @SuppressWarnings("unchecked") + @Test + public void fetchMetaDataByResourceType_failedToGetData() throws Exception { + when(janusGraphDaoMock.getByCriteria(eq(null), anyMap(), anyMap(), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(Either.right( + JanusGraphOperationStatus.GENERAL_ERROR)); + Either, StorageOperationStatus> fetchedComponents = testInstance.fetchMetaDataByResourceType(ResourceTypeEnum.VF.getValue(), new ComponentParametersView()); + assertTrue(fetchedComponents.isRight()); + assertEquals(StorageOperationStatus.GENERAL_ERROR, fetchedComponents.right().value()); + } + + @Test + public void associatePolicyToComponentSuccessTest(){ + Either result = associatePolicyToComponentWithStatus(StorageOperationStatus.OK); + assertTrue(result.isLeft()); + } + + @Test + public void associatePolicyToComponentFailureTest(){ + Either result = associatePolicyToComponentWithStatus(StorageOperationStatus.BAD_REQUEST); + assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.BAD_REQUEST); + } + + @Test + public void updatePolicyOfComponentSuccessTest(){ + Either result = updatePolicyOfComponentWithStatus(StorageOperationStatus.OK); + assertTrue(result.isLeft()); + } + + @Test + public void updatePolicyOfComponentFailureTest(){ + Either result = updatePolicyOfComponentWithStatus(StorageOperationStatus.NOT_FOUND); + assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND); + } + + @Test + public void removePolicyFromComponentSuccessTest(){ + removePolicyFromComponentWithStatus(StorageOperationStatus.OK); + } + + @Test + public void removePolicyFromComponentFailureTest(){ + removePolicyFromComponentWithStatus(StorageOperationStatus.NOT_FOUND); + } + + @Test + public void testFindLastCertifiedToscaElementByUUID(){ + Either result; + Component component = new Resource(); + List list = new ArrayList<>(); + GraphVertex graphVertex = getTopologyTemplateVertex(); + list.add(graphVertex); + Map props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.UUID, component.getUUID()); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + ToscaElement toscaElement = getToscaElementForTest(); + when(topologyTemplateOperationMock.getToscaElement(ArgumentMatchers.eq(graphVertex),any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement)); + when(janusGraphDaoMock.getByCriteria(ModelConverter.getVertexType(component), props)).thenReturn(Either.left(list)); + result = testInstance.findLastCertifiedToscaElementByUUID(component); + Component resultComp = result.left().value(); + assertEquals(resultComp.getToscaType(),ToscaElementTypeEnum.TOPOLOGY_TEMPLATE.getValue()); + } + + @Test + public void testLatestComponentByToscaResourceName(){ + Either result; + TopologyTemplate toscaElement = new TopologyTemplate(); + toscaElement.setComponentType(ComponentTypeEnum.SERVICE); + List list = new ArrayList<>(); + GraphVertex graphVertex = getTopologyTemplateVertex(); + Map props = new HashMap<>(); + props.put(GraphPropertyEnum.VERSION, "1.0"); + graphVertex.setMetadataProperties(props); + list.add(graphVertex); + + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, "toscaResourceName"); + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + when(janusGraphDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(list)); + when(topologyTemplateOperationMock.getToscaElement(ArgumentMatchers.eq(graphVertex),any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement)); + + result = testInstance.getFullLatestComponentByToscaResourceName("toscaResourceName"); + assertThat(result.isLeft()); + } + + @Test + public void testValidateCsarUuidUniqueness() { + StorageOperationStatus result; + String csarUUID = "csarUUID"; + Map properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID); + List vertexList = new ArrayList<>(); + when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(vertexList)); + result = testInstance.validateCsarUuidUniqueness(csarUUID); + assertEquals(StorageOperationStatus.ENTITY_ALREADY_EXISTS, result); + } + + @Test + public void testValidateCsarUuidUnique_true() { + StorageOperationStatus result; + String csarUUID = "csarUUID"; + Map properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID); + when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.right( + JanusGraphOperationStatus.NOT_FOUND)); + result = testInstance.validateCsarUuidUniqueness(csarUUID); + assertEquals(StorageOperationStatus.OK, result); + } + + @Test + public void testGetLatestCertiNodeTypeByToscaResourceName() { + Either result; + String toscaResourceName = "resourceName"; + String uniqueId = "uniqueId"; + GraphVertex graphVertex = getTopologyTemplateVertex(); + graphVertex.setJsonMetadataField(JsonPresentationFields.VERSION, "1.0"); + graphVertex.setUniqueId(uniqueId); + List vertexList = new ArrayList<>(); + vertexList.add(graphVertex); + Map props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + ToscaElement topologyTemplate = new TopologyTemplate(); + topologyTemplate.setComponentType(ComponentTypeEnum.SERVICE); + when(janusGraphDaoMock.getByCriteria(VertexTypeEnum.NODE_TYPE, props, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(vertexList)); + when(janusGraphDaoMock.getVertexById(uniqueId, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex)); + when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(topologyTemplate)); + result = testInstance.getLatestCertifiedNodeTypeByToscaResourceName(toscaResourceName); + assertThat(result.isLeft()); + } + + @Test + public void testValidateCompExists() { + Either result; + String componentId = "componentId"; + GraphVertex graphVertex = getTopologyTemplateVertex(); + when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex)); + result = testInstance.validateComponentExists(componentId); + assertEquals(true, result.left().value()); + } + + @Test + public void testValidateCompExists_NotFound() { + Either result; + String componentId = "componentId"; + when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.right( + JanusGraphOperationStatus.NOT_FOUND)); + result = testInstance.validateComponentExists(componentId); + assertEquals(false, result.left().value()); + } + + @Test + public void testValidateToscaResourceNameExists() { + Either result; + String templateName = "templateName"; + Map properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, templateName); + List graphVertexList = new ArrayList<>(); + GraphVertex graphVertex = getTopologyTemplateVertex(); + graphVertexList.add(graphVertex); + when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(graphVertexList)); + result = testInstance.validateToscaResourceNameExists(templateName); + assertEquals(true, result.left().value()); + } + + @Test + public void testValidateToscaResourceNameExists_false() { + Either result; + String templateName = "templateName"; + Map properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, templateName); + List graphVertexList = new ArrayList<>(); + GraphVertex graphVertex = getTopologyTemplateVertex(); + graphVertexList.add(graphVertex); + when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.right( + JanusGraphOperationStatus.NOT_FOUND)); + result = testInstance.validateToscaResourceNameExists(templateName); + assertEquals(false, result.left().value()); + } + + @Test + public void testOverrideComponent() { + Either result; + Resource resource = new Resource(); + String id = "id"; + resource.setUniqueId(id); + GraphVertex graphVertex = getTopologyTemplateVertex(); + graphVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); + NodeType nodeType = new NodeType(); + nodeType.setComponentType(ComponentTypeEnum.RESOURCE); + ToscaElement toscaElement = new TopologyTemplate(); + toscaElement.setComponentType(ComponentTypeEnum.SERVICE); + when(janusGraphDaoMock.getVertexById(id, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex)); + when(janusGraphDaoMock.getParentVertex(graphVertex, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex)); + when(topologyTemplateOperationMock.deleteToscaElement(graphVertex)).thenReturn(Either.left(toscaElement)); + when(nodeTypeOperation.createToscaElement(any(ToscaElement.class))).thenReturn(Either.left(nodeType)); + when(janusGraphDaoMock.getVertexById(null, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex)); + when(janusGraphDaoMock.createEdge(graphVertex, graphVertex, EdgeLabelEnum.VERSION, null)).thenReturn( + JanusGraphOperationStatus.OK); + result = testInstance.overrideComponent(resource, resource); + assertTrue(result.isLeft()); + } + + @Test + public void testGetToscaElement() { + Either result; + String id = "id"; + GraphVertex graphVertex = getTopologyTemplateVertex(); + ToscaElement toscaElement = getToscaElementForTest(); + when(janusGraphDaoMock.getVertexById(id, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex)); + when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement)); + result = testInstance.getToscaElement(id, JsonParseFlagEnum.ParseAll); + assertTrue(result.isLeft()); + } + + @Test + public void testMarkComponentToDelete() { + StorageOperationStatus result; + Component component = new Resource(); + String id = "id"; + component.setUniqueId(id); + GraphVertex graphVertex = getTopologyTemplateVertex(); + when(janusGraphDaoMock.getVertexById(id, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex)); + when(nodeTypeOperation.markComponentToDelete(graphVertex)).thenReturn(Either.left(graphVertex)); + result = testInstance.markComponentToDelete(component); + assertEquals(result, StorageOperationStatus.OK); + } + + @Test + public void testDelToscaComponent() { + Either result; + String componentId = "compId"; + GraphVertex graphVertex = getTopologyTemplateVertex(); + ToscaElement toscaElement = getToscaElementForTest(); + when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex)); + when(topologyTemplateOperationMock.deleteToscaElement(graphVertex)).thenReturn(Either.left(toscaElement)); + result = testInstance.deleteToscaComponent(componentId); + assertTrue(result.isLeft()); + } + + @Test + public void testGetLatestByToscaResourceName() { + Either result; + String toscaResourceName = "name"; + ToscaElement toscaElement = getToscaElementForTest(); + + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + List graphVertexList = new ArrayList<>(); + GraphVertex graphVertex = getTopologyTemplateVertex(); + graphVertex.setUniqueId(toscaResourceName); + Map props = new HashMap<>(); + props.put(GraphPropertyEnum.VERSION, "1.0"); + graphVertex.setMetadataProperties(props); + graphVertexList.add(graphVertex); + + when(janusGraphDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(graphVertexList)); + when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement)); + result = testInstance.getLatestByToscaResourceName(toscaResourceName); + assertTrue(result.isLeft()); + } + + @Test + public void testGetFollowed() { + Either, StorageOperationStatus> result; + String userId = "id"; + Set lifecycleStates = new HashSet<>(); + Set lastStateStates = new HashSet<>(); + lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); + lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + lifecycleStates.add(LifecycleStateEnum.CERTIFIED); + lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); + ComponentTypeEnum componentType = ComponentTypeEnum.RESOURCE; + List toscaEleList = new ArrayList<>(); + ToscaElement toscaElement = getToscaElementForTest(); + toscaEleList.add(toscaElement); + when(nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType)).thenReturn(Either.left(toscaEleList)); + result = testInstance.getFollowed(userId, lifecycleStates, lastStateStates, componentType); + assertTrue(result.isLeft()); + assertEquals(1, result.left().value().size()); + } + + @Test + public void testGetBySystemName() { + Either, StorageOperationStatus> result; + String sysName = "sysName"; + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE; + ToscaElement toscaElement = getToscaElementForTest(); + List componentVertices = new ArrayList<>(); + GraphVertex graphVertex = getTopologyTemplateVertex(); + componentVertices.add(graphVertex); + Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, sysName); + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentTypeEnum.name()); + + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + when(janusGraphDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(componentVertices)); + when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement)); + result = testInstance.getBySystemName(componentTypeEnum, sysName); + assertTrue(result.isLeft()); + assertEquals(1, result.left().value().size()); + } + + @Test + public void testGetCompByNameAndVersion() { + Either result; + ComponentTypeEnum componentType = ComponentTypeEnum.RESOURCE; + String name = "name"; + String version = "1.0"; + JsonParseFlagEnum parseFlag = JsonParseFlagEnum.ParseAll; + List graphVertexList = new ArrayList<>(); + GraphVertex graphVertex = getTopologyTemplateVertex(); + graphVertexList.add(graphVertex); + ToscaElement toscaElement = getToscaElementForTest(); + Map hasProperties = new EnumMap<>(GraphPropertyEnum.class); + Map hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); + + hasProperties.put(GraphPropertyEnum.NAME, name); + hasProperties.put(GraphPropertyEnum.VERSION, version); + hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); + hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + when(janusGraphDaoMock.getByCriteria(null, hasProperties, hasNotProperties, parseFlag)).thenReturn(Either.left(graphVertexList)); + when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement)); + result = testInstance.getComponentByNameAndVersion(componentType, name, version, parseFlag); + assertTrue(result.isLeft()); + } + + private ToscaElement getToscaElementForTest() { + ToscaElement toscaElement = new TopologyTemplate(); + toscaElement.setComponentType(ComponentTypeEnum.RESOURCE); + return toscaElement; + } + + @Test + public void addDataTypesToComponentSuccessTest(){ + Either, StorageOperationStatus> result = addDataTypesToComponentWithStatus(StorageOperationStatus.OK); + assertTrue(result.isLeft()); + } + + @Test + public void addDataTypesToComponentFailureTest_BadRequest(){ + Either, StorageOperationStatus> result = addDataTypesToComponentWithStatus(StorageOperationStatus.BAD_REQUEST); + assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.BAD_REQUEST); + } + + private Either, StorageOperationStatus> addDataTypesToComponentWithStatus(StorageOperationStatus status) { + Map dataTypes = new HashMap<>(); + String componentId = "componentid"; + String Id = "id"; + + PropertyDefinition noDefaultProp = new PropertyDefinition(); + noDefaultProp.setName("noDefaultProp"); + PropertyDefinition prop1 = new PropertyDefinition(); + prop1.setDefaultValue("def1"); + prop1.setName("prop1"); + PropertyDefinition prop2 = new PropertyDefinition(); + prop2.setType("dataType1"); + prop2.setName("prop2"); + PropertyDefinition prop3 = new PropertyDefinition(); + prop3.setDefaultValue("def3"); + prop3.setName("prop3"); + + DataTypeDefinition noDefaultValue = new DataTypeDefinition(); + noDefaultValue.setProperties(Collections.singletonList(noDefaultProp)); + noDefaultValue.setDerivedFromName("name0"); + + DataTypeDefinition dataType1 = new DataTypeDefinition(); + dataType1.setProperties(Arrays.asList(prop1, prop3)); + dataType1.setName("name1"); + dataType1.setDerivedFromName("derivedfromname1"); + + DataTypeDefinition dataType2 = new DataTypeDefinition(); + dataType2.setDerivedFrom(dataType1); + dataType2.setName("name2"); + dataType2.setDerivedFromName("derivedfromname2"); + + DataTypeDefinition dataType3 = new DataTypeDefinition(); + dataType3.setProperties(Collections.singletonList(prop2)); + dataType3.setDerivedFrom(noDefaultValue); + dataType3.setName("name3"); + dataType3.setDerivedFromName("derivedfromname3"); + + dataTypes.put("noDefault", noDefaultValue); + dataTypes.put("dataType1", dataType1); + dataTypes.put("dataType2", dataType2); + dataTypes.put("dataType3", dataType3); + + GraphVertex vertex; + if(status == StorageOperationStatus.OK){ + vertex = getTopologyTemplateVertex(); + } else { + vertex = getNodeTypeVertex(); + } + Either getVertexEither = Either.left(vertex); + when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(getVertexEither); + when(topologyTemplateOperationMock.addToscaDataToToscaElement(eq(vertex), + eq(EdgeLabelEnum.DATA_TYPES), eq(VertexTypeEnum.DATA_TYPES), anyMap(), eq(JsonPresentationFields.NAME))).thenReturn(status); + return testInstance.addDataTypesToComponent(dataTypes, componentId); + } + + @Test + public void testDataTypesToComponentFailureTest_NotFound() { + Either, StorageOperationStatus> result; + String componentId = "componentId"; + GraphVertex vertex = getNodeTypeVertex(); + Map dataTypes = new HashMap<>(); + when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.right( + JanusGraphOperationStatus.NOT_FOUND)); + result = testInstance.addDataTypesToComponent(dataTypes, componentId); + assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND); + } + + @Test + public void testDeleteDataTypeOfComponent() { + StorageOperationStatus result; + Component component = new Resource(); + String id = "id"; + component.setUniqueId(id); + String datatype = null; + + DataTypeDefinition dataType1 = new DataTypeDefinition(); + dataType1.setName("name1"); + Map dataTypeDataMap = new HashMap<>(); + dataTypeDataMap.put("datatype1", dataType1); + List dataTypeMap = dataTypeDataMap.values().stream().map(e -> { DataTypeDefinition dataType = new DataTypeDefinition(e);return dataType; }).collect(Collectors.toList()); + component.setDataTypes(dataTypeMap); + GraphVertex graphVertex = getTopologyTemplateVertex(); + result = testInstance.deleteDataTypeOfComponent(component, "datatype1"); + assertEquals(datatype, result); + } + + @Test + public void testAddComponentInstancePropertiesToComponent() { + // set up component object + Component component = new Resource(); + component.setUniqueId(COMPONENT_ID); + List instanceProps = new ArrayList<>(); + ComponentInstanceProperty instanceProp = new ComponentInstanceProperty(); + instanceProp.setName(PROPERTY1_NAME); + instanceProp.setType(PROPERTY1_TYPE); + instanceProps.add(instanceProp); + instanceProp = new ComponentInstanceProperty(); + instanceProp.setName(PROPERTY2_NAME); + instanceProp.setType(PROPERTY2_TYPE); + instanceProps.add(instanceProp); + Map> instancePropsMap = + Collections.singletonMap(COMPONENT_ID, instanceProps); + component.setComponentInstancesProperties(Collections.singletonMap(COMPONENT_ID, new ArrayList<>())); + + when(nodeTemplateOperationMock.addComponentInstanceProperty(any(), any(), any())) + .thenReturn(StorageOperationStatus.OK); + + Either>, StorageOperationStatus> result = + testInstance.addComponentInstancePropertiesToComponent(component, instancePropsMap); + assertTrue(result.isLeft()); + verify(nodeTemplateOperationMock, times(2)).addComponentInstanceProperty(any(), any(), any()); + List resultProps = result.left().value().get(COMPONENT_ID); + assertTrue(resultProps.stream().anyMatch(e -> e.getName().equals(PROPERTY1_NAME))); + assertTrue(resultProps.stream().anyMatch(e -> e.getName().equals(PROPERTY2_NAME))); + } + + private Either associatePolicyToComponentWithStatus(StorageOperationStatus status) { + PolicyDefinition policy = new PolicyDefinition(); + String componentId = "componentId"; + int counter = 0; + GraphVertex vertex; + if(status == StorageOperationStatus.OK){ + vertex = getTopologyTemplateVertex(); + } else { + vertex = getNodeTypeVertex(); + } + Either getVertexEither = Either.left(vertex); + when(janusGraphDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(getVertexEither); + when(topologyTemplateOperationMock.addPolicyToToscaElement(eq(vertex), any(PolicyDefinition.class), anyInt())).thenReturn(status); + return testInstance.associatePolicyToComponent(componentId, policy, counter); + } + + private Either updatePolicyOfComponentWithStatus(StorageOperationStatus status) { + PolicyDefinition policy = new PolicyDefinition(); + String componentId = "componentId"; + GraphVertex vertex = getTopologyTemplateVertex(); + when(janusGraphDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.NoParse))).thenReturn(Either.left(vertex)); + when(topologyTemplateOperationMock.updatePolicyOfToscaElement(eq(vertex), any(PolicyDefinition.class))).thenReturn(status); + return testInstance.updatePolicyOfComponent(componentId, policy); + } + + private void removePolicyFromComponentWithStatus(StorageOperationStatus status) { + String componentId = "componentId"; + String policyId = "policyId"; + GraphVertex vertex = getTopologyTemplateVertex(); + Either getVertexEither = Either.left(vertex); + when(janusGraphDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.NoParse))).thenReturn(getVertexEither); + when(topologyTemplateOperationMock.removePolicyFromToscaElement(eq(vertex), eq(policyId))).thenReturn(status); + StorageOperationStatus result = testInstance.removePolicyFromComponent(componentId, policyId); + assertSame(result, status); + } + + private List getMockVertices(int numOfVertices) { + return IntStream.range(0, numOfVertices).mapToObj(i -> getTopologyTemplateVertex()).collect(Collectors.toList()); + } + + private ToscaElement getResourceToscaElement(String id) { + ToscaElement toscaElement = new TopologyTemplate(); + toscaElement.setMetadata(new HashMap<>()); + toscaElement.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), "RESOURCE"); + toscaElement.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), id); + return toscaElement; + } + + private GraphVertex getTopologyTemplateVertex() { + GraphVertex graphVertex = new GraphVertex(); + graphVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); + return graphVertex; + } + + private GraphVertex getNodeTypeVertex() { + GraphVertex graphVertex = new GraphVertex(); + graphVertex.setLabel(VertexTypeEnum.NODE_TYPE); + return graphVertex; + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperationTest.java new file mode 100644 index 0000000000..68c87bb7e8 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperationTest.java @@ -0,0 +1,183 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.operations; + +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +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.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.GraphTestUtils; +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.UserAdminOperation; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class UpgradeOperationTest extends ModelTestBase { + + private boolean isInitialized; + @Resource + private JanusGraphDao janusGraphDao; + @Resource + private UpgradeOperation upgradeOperation; + @Resource + private TopologyTemplateOperation topologyTemplateOperation; + @Resource + private NodeTemplateOperation nodeTemplateOperation; + @Resource + private UserAdminOperation userAdminOperation; + @javax.annotation.Resource + private IElementOperation elementOperation; + + private User user; + + private CategoryDefinition resourceCategory; + private CategoryDefinition serviceCategory; + + + @BeforeClass + public static void initTest() { + ModelTestBase.init(); + } + + @Before + public void beforeTest() { + if (!isInitialized) { + GraphTestUtils.clearGraph(janusGraphDao); + initGraphForTest(); + isInitialized = true; + } + } + + @Test + public void testGetSimpleDependency() { + + TopologyTemplate vf = createVf("vf1"); + + TopologyTemplate service = createServiceWitnInstance("service1", vf); + + + Either, StorageOperationStatus> result = upgradeOperation.getComponentDependencies(vf.getUniqueId()); + assertThat(result.isLeft()).isTrue(); + List dependencies = result.left().value(); + assertThat(dependencies).hasSize(1); + + ComponentDependency dependency = dependencies.get(0); + assertThat(dependency.getName()).isEqualTo(vf.getName()); + assertThat(dependency.getVersion()).isEqualTo(vf.getVersion()); + assertThat(dependency.getDependencies()).hasSize(1); + + ComponentDependency container = dependency.getDependencies().get(0); + assertThat(container.getName()).isEqualTo(service.getName()); + assertThat(container.getVersion()).isEqualTo(service.getVersion()); + assertThat(container.getDependencies()).isNull(); + + } + + /******************************* + * Preperation Methods + *******************************/ + private void initGraphForTest() { + + user = new User("Jim", "Tom", "jt123a", "1@mail.com", "DESIGNER", System.currentTimeMillis()); + Either saveUserData = userAdminOperation.saveUserData(user); + assertThat(saveUserData.isLeft()).isTrue(); + + GraphTestUtils.createRootCatalogVertex(janusGraphDao); + resourceCategory = createResourceCategories(); + serviceCategory = createServiceCategory(); + + } + + private TopologyTemplate createServiceWitnInstance(String name, TopologyTemplate createdVf) { + + TopologyTemplate serviceNew = createTopologyTemplate(ComponentTypeEnum.SERVICE, name); + List categoriesService = new ArrayList<>(); + categoriesService.add(serviceCategory); + serviceNew.setCategories(categoriesService); + + Either createService = topologyTemplateOperation.createTopologyTemplate(serviceNew); + assertThat(createService.isLeft()).isTrue(); + + ComponentInstance vfInstance = new ComponentInstance(); + vfInstance.setUniqueId(createdVf.getUniqueId() + createdVf.getName()); + vfInstance.setComponentUid(createdVf.getUniqueId()); + vfInstance.setName(createdVf.getName()); + Either, StorageOperationStatus> addInstance = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(serviceNew, createdVf, "0", vfInstance, false, user); + assertThat(addInstance.isLeft()).isTrue(); + return serviceNew; + } + + private CategoryDefinition createServiceCategory() { + CategoryDefinition categoryService = new CategoryDefinition(); + categoryService.setName("servicecategory"); + categoryService.setNormalizedName("servicecategory"); + categoryService.setUniqueId("servicecategory"); + Either createCategory = elementOperation.createCategory(categoryService , NodeTypeEnum.ServiceNewCategory); + + assertThat(createCategory.isLeft()).isTrue(); + return categoryService; + } + + private TopologyTemplate createVf(String name) { + + TopologyTemplate resource = createTopologyTemplate(ComponentTypeEnum.RESOURCE, name); + + resource.setResourceType(ResourceTypeEnum.VF); + List categories = new ArrayList<>(); + categories.add(resourceCategory); + resource.setCategories(categories); + Either createVf = topologyTemplateOperation.createTopologyTemplate(resource); + assertThat( createVf.isLeft()).isTrue(); + return resource; + } + + private CategoryDefinition createResourceCategories() { + CategoryDefinition category = new CategoryDefinition(); + category.setName("category1"); + category.setNormalizedName("category1"); + category.setUniqueId("category1"); + Either createCategory = elementOperation.createCategory(category , NodeTypeEnum.ResourceNewCategory); + assertThat(createCategory.isLeft()).isTrue(); + + SubCategoryDefinition subCategory = new SubCategoryDefinition(); + + subCategory.setName("subcategory1"); + subCategory.setNormalizedName("subcategory1"); + subCategory.setUniqueId("subcategory1"); + elementOperation.createSubCategory(createCategory.left().value().getUniqueId(), subCategory, NodeTypeEnum.ResourceSubcategory); + category.addSubCategory(subCategory); + return category; + } + + private TopologyTemplate createTopologyTemplate(ComponentTypeEnum type, String name) { + TopologyTemplate template = new TopologyTemplate(); + template.setUniqueId(IdBuilderUtils.generateUniqueId()); + template.setComponentType(type); + template.setHighestVersion(true); + template.setLifecycleState(LifecycleStateEnum.CERTIFIED); + template.setMetadataValue(JsonPresentationFields.NAME, name); + template.setMetadataValue(JsonPresentationFields.VERSION, "1.0"); + template.setCreatorUserId(user.getUserId()); + return template; + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityTestUtils.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityTestUtils.java new file mode 100644 index 0000000000..8a17de4054 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityTestUtils.java @@ -0,0 +1,85 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * 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. + */ + +package org.openecomp.sdc.be.model.jsonjanusgraph.utils; + +import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CapabilityTestUtils { + + public static Map createCapPropsForTopologyTemplate(TopologyTemplate topologyTemplate) { + Map capabilitiesMap = new HashMap<>(); + + List capabilityDefinitions = new ArrayList<>(); + CapabilityDefinition capabilityDefinition = createCapabilityDefinition(); + + capabilityDefinitions.add(capabilityDefinition); + ListCapabilityDataDefinition listCapabilityDataDefinition = new ListCapabilityDataDefinition(capabilityDefinitions); + capabilitiesMap.put(capabilityDefinition.getType(), listCapabilityDataDefinition); + topologyTemplate.setCapabilities(capabilitiesMap); + + List capPropList = new ArrayList<>(); + ComponentInstanceProperty instanceProperty = createProperties(); + capPropList.add(instanceProperty); + + MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); + for (ComponentInstanceProperty cip : capPropList) { + PropertyDataDefinition propertyDataDefinition = new PropertyDataDefinition(cip); + dataToCreate.put(cip.getName(), propertyDataDefinition); + } + + Map capabilitiesProperties = new HashMap<>(); + capabilitiesProperties.put(capabilityDefinition.getType() + ModelConverter.CAP_PROP_DELIM + + capabilityDefinition.getName(), dataToCreate); + return capabilitiesProperties; + } + + private static CapabilityDefinition createCapabilityDefinition() { + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setName("cap" + Math.random()); + capabilityDefinition.setType("tosca.capabilities.network.Bindable"); + capabilityDefinition.setOwnerId("resourceId"); + capabilityDefinition.setUniqueId("capUniqueId"); + List path = new ArrayList<>(); + path.add("path1"); + capabilityDefinition.setPath(path); + return capabilityDefinition; + } + + private static ComponentInstanceProperty createProperties() { + ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); + instanceProperty.setUniqueId("ComponentInput1_uniqueId"); + instanceProperty.setType("Integer"); + instanceProperty.setName("prop_name"); + instanceProperty.setDescription("prop_description_prop_desc"); + instanceProperty.setOwnerId("capUniqueId"); + instanceProperty.setValue("{\"get_input\":\"extcp20_order\"}"); + instanceProperty.setSchema(new SchemaDefinition()); + return instanceProperty; + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/GraphTestUtils.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/GraphTestUtils.java new file mode 100644 index 0000000000..06e0b428b9 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/GraphTestUtils.java @@ -0,0 +1,129 @@ +/*- + * ============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.jsonjanusgraph.utils; + +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.io.IoCore; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; + +public final class GraphTestUtils { + + public static GraphVertex createRootCatalogVertex(JanusGraphDao janusGraphDao) { + GraphVertex catalogRootVertex = new GraphVertex(VertexTypeEnum.CATALOG_ROOT); + catalogRootVertex.setUniqueId(IdBuilderUtils.generateUniqueId()); + return janusGraphDao.createVertex(catalogRootVertex) + .either(v -> v, s -> null); + } + + public static GraphVertex createRootArchiveVertex(JanusGraphDao janusGraphDao) { + GraphVertex archiveRootVertex = new GraphVertex(VertexTypeEnum.ARCHIVE_ROOT); + archiveRootVertex.setUniqueId(IdBuilderUtils.generateUniqueId()); + return janusGraphDao.createVertex(archiveRootVertex) + .either(v -> v, s -> null); + } + + public static GraphVertex createResourceVertex(JanusGraphDao janusGraphDao, Map metadataProps, ResourceTypeEnum type) { + GraphVertex vertex = new GraphVertex(); + if (type == ResourceTypeEnum.VF) { + vertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); + vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE); + } else { + vertex.setLabel(VertexTypeEnum.NODE_TYPE); + vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.NODE_TYPE); + } + String uuid = UUID.randomUUID().toString(); + vertex.setUniqueId(uuid); + + vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid); + vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + vertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, type.name()); + vertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, false); + for (Map.Entry prop : metadataProps.entrySet()) { + vertex.addMetadataProperty(prop.getKey(), prop.getValue()); + } + janusGraphDao.createVertex(vertex); + janusGraphDao.commit(); + return vertex; + } + + public static GraphVertex createServiceVertex(JanusGraphDao janusGraphDao, Map metadataProps){ + GraphVertex vertex = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); + String uuid = UUID.randomUUID().toString(); + vertex.setUniqueId(uuid); + vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE); + vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid); + vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + for (Map.Entry prop : metadataProps.entrySet()) { + vertex.addMetadataProperty(prop.getKey(), prop.getValue()); + } + janusGraphDao.createVertex(vertex); + janusGraphDao.commit(); + return vertex; + } + + public static void clearGraph(JanusGraphDao janusGraphDao) { + Either graphResult = janusGraphDao.getGraph(); + JanusGraph graph = graphResult.left().value(); + + Iterable vertices = graph.query().vertices(); + if (vertices != null) { + Iterator iterator = vertices.iterator(); + while (iterator.hasNext()) { + JanusGraphVertex vertex = iterator.next(); + vertex.remove(); + } + } + janusGraphDao.commit(); + } + + public static String exportGraphMl(JanusGraph graph, String outputDirectory) { + String result = null; + String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml"; + 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; + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/IdMapperTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/IdMapperTest.java new file mode 100644 index 0000000000..dca79c6041 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/IdMapperTest.java @@ -0,0 +1,37 @@ +package org.openecomp.sdc.be.model.jsonjanusgraph.utils; + +import org.junit.Test; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; + +public class IdMapperTest { + + private IdMapper createTestSubject() { + return new IdMapper(); + } + + + @Test + public void testMapComponentNameToUniqueId() throws Exception { + IdMapper testSubject; + String componentInstanceName = ""; + GraphVertex serviceVertex = null; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.mapComponentNameToUniqueId(componentInstanceName, serviceVertex); + } + + + @Test + public void testMapUniqueIdToComponentNameTo() throws Exception { + IdMapper testSubject; + String compUniqueId = ""; + GraphVertex serviceVertex = null; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.mapUniqueIdToComponentNameTo(compUniqueId, serviceVertex); + } +} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverterTest.java new file mode 100644 index 0000000000..740d148a79 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverterTest.java @@ -0,0 +1,137 @@ +/* + + * Copyright (c) 2018 Huawei Intellectual Property. + + * + + * 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. + + */ +package org.openecomp.sdc.be.model.jsonjanusgraph.utils; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.NodeType; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +@RunWith(MockitoJUnitRunner.class) +public class ModelConverterTest { + @InjectMocks + private ModelConverter test; + + @Test + public void testConvertToToscaElementService() + { + Service service = new Service(); + service.setComponentType(ComponentTypeEnum.SERVICE); + TopologyTemplate template = test.convertToToscaElement(service); + assertThat(template.getToscaType()).isEqualTo(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE); + } + + @Test + public void testConvertToToscaElementResource() + { + Resource resource = new Resource(); + resource.setComponentType(ComponentTypeEnum.RESOURCE); + NodeType nodeType = test.convertToToscaElement(resource); + assertThat(nodeType.getToscaType()).isEqualTo(ToscaElementTypeEnum.NODE_TYPE); + } + + @Test + public void testConvertFromToscaElementService() + { + TopologyTemplate topologyTemplate = new TopologyTemplate(); + topologyTemplate.setComponentType(ComponentTypeEnum.SERVICE); + Component component = test.convertFromToscaElement(topologyTemplate); + assertThat(component.getToscaType()).isEqualTo(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE.getValue()); + } + + @Test + public void testConvertFromToscaElementServiceWithSelfCapabilities() + { + TopologyTemplate topologyTemplate = new TopologyTemplate(); + + Map capabilitiesProperties = CapabilityTestUtils + .createCapPropsForTopologyTemplate(topologyTemplate); + + topologyTemplate.setCapabilitiesProperties(capabilitiesProperties); + + topologyTemplate.setComponentType(ComponentTypeEnum.SERVICE); + Component component = test.convertFromToscaElement(topologyTemplate); + assertThat(component.getToscaType()).isEqualTo(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE.getValue()); + } + + @Test + public void testConvertFromToscaElementResource() + { + TopologyTemplate topologyTemplate = new TopologyTemplate(); + topologyTemplate.setComponentType(ComponentTypeEnum.RESOURCE); + Component component = test.convertFromToscaElement(topologyTemplate); + assertThat(component.getToscaType()).isEqualTo(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE.getValue()); + } + + @Test + public void testConvertFromToscaElementResourceType() + { + TopologyTemplate topologyTemplate = new TopologyTemplate(); + topologyTemplate.setComponentType(ComponentTypeEnum.RESOURCE); + topologyTemplate.setResourceType(ResourceTypeEnum.PNF); + Resource resource = test.convertFromToscaElement(topologyTemplate); + assertSame(ResourceTypeEnum.PNF, resource.getResourceType()); + } + + @Test + public void testIsAtomicComponent() + { + Resource component = new Resource(); + component.setComponentType(ComponentTypeEnum.RESOURCE); + boolean result = test.isAtomicComponent(component); + assertTrue(result); + } + + @Test + public void testGetVertexType() + { + VertexTypeEnum result; + Resource component = new Resource(); + component.setComponentType(ComponentTypeEnum.RESOURCE); + result = test.getVertexType(component); + assertThat(result.getName()).isEqualTo("node_type"); + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeTypeTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeTypeTest.java deleted file mode 100644 index 493cb74a25..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeTypeTest.java +++ /dev/null @@ -1,173 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.datamodel; - -import java.util.List; -import java.util.Map; - -import org.junit.Test; -import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; - - -public class NodeTypeTest { - - private NodeType createTestSubject() { - return new NodeType(); - } - - - @Test - public void testGetDerivedList() throws Exception { - NodeType testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDerivedList(); - } - - - @Test - public void testSetDerivedList() throws Exception { - NodeType testSubject; - List derivedList = null; - - // default test - testSubject = createTestSubject(); - testSubject.setDerivedList(derivedList); - } - - - @Test - public void testGetDerivedFrom() throws Exception { - NodeType testSubject; - List result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDerivedFrom(); - } - - - @Test - public void testSetDerivedFrom() throws Exception { - NodeType testSubject; - List derivedFrom = null; - - // default test - testSubject = createTestSubject(); - testSubject.setDerivedFrom(derivedFrom); - } - - - @Test - public void testGetAttributes() throws Exception { - NodeType testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getAttributes(); - } - - - @Test - public void testSetAttributes() throws Exception { - NodeType testSubject; - Map attributes = null; - - // default test - testSubject = createTestSubject(); - testSubject.setAttributes(attributes); - } - - - @Test - public void testGetCapabilties() throws Exception { - NodeType testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCapabilities(); - } - - - @Test - public void testSetCapabilties() throws Exception { - NodeType testSubject; - Map capabilties = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCapabilities(capabilties); - } - - - @Test - public void testGetRequirements() throws Exception { - NodeType testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getRequirements(); - } - - - @Test - public void testSetRequirements() throws Exception { - NodeType testSubject; - Map requirements = null; - - // default test - testSubject = createTestSubject(); - testSubject.setRequirements(requirements); - } - - - @Test - public void testGetCapabiltiesProperties() throws Exception { - NodeType testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCapabilitiesProperties(); - } - - - @Test - public void testSetCapabiltiesProperties() throws Exception { - NodeType testSubject; - Map capabiltiesProperties = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCapabilitiesProperties(capabiltiesProperties); - } - - - @Test - public void testGetInterfaceArtifacts() throws Exception { - NodeType testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInterfaceArtifacts(); - } - - - @Test - public void testSetInterfaceArtifacts() throws Exception { - NodeType testSubject; - Map interfaceArtifacts = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInterfaceArtifacts(interfaceArtifacts); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplateTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplateTest.java deleted file mode 100644 index c13ddd3970..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplateTest.java +++ /dev/null @@ -1,423 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.datamodel; - -import java.util.Map; - -import org.junit.Test; -import org.openecomp.sdc.be.datatypes.elements.*; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.DataTypeDefinition; - - -public class TopologyTemplateTest { - - private TopologyTemplate createTestSubject() { - return new TopologyTemplate(); - } - - - @Test - public void testGetInputs() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInputs(); - } - - - @Test - public void testSetInputs() throws Exception { - TopologyTemplate testSubject; - Map inputs = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInputs(inputs); - } - - - @Test - public void testGetInstInputs() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInstInputs(); - } - - - @Test - public void testSetInstInputs() throws Exception { - TopologyTemplate testSubject; - Map instInputs = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInstInputs(instInputs); - } - - - @Test - public void testGetHeatParameters() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getHeatParameters(); - } - - - @Test - public void testSetHeatParameters() throws Exception { - TopologyTemplate testSubject; - Map heatParameters = null; - - // default test - testSubject = createTestSubject(); - testSubject.setHeatParameters(heatParameters); - } - - - @Test - public void testGetInstAttributes() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInstAttributes(); - } - - - @Test - public void testSetInstAttributes() throws Exception { - TopologyTemplate testSubject; - Map instAttributes = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInstAttributes(instAttributes); - } - - - @Test - public void testGetInstProperties() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInstProperties(); - } - - - @Test - public void testSetInstProperties() throws Exception { - TopologyTemplate testSubject; - Map instProperties = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInstProperties(instProperties); - } - - - @Test - public void testGetGroups() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getGroups(); - } - - - @Test - public void testSetGroups() throws Exception { - TopologyTemplate testSubject; - Map groups = null; - - // default test - testSubject = createTestSubject(); - testSubject.setGroups(groups); - } - - - @Test - public void testGetInstGroups() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInstGroups(); - } - - - @Test - public void testSetInstGroups() throws Exception { - TopologyTemplate testSubject; - Map instGroups = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInstGroups(instGroups); - } - - - @Test - public void testGetServiceApiArtifacts() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getServiceApiArtifacts(); - } - - - @Test - public void testSetServiceApiArtifacts() throws Exception { - TopologyTemplate testSubject; - Map serviceApiArtifacts = null; - - // default test - testSubject = createTestSubject(); - testSubject.setServiceApiArtifacts(serviceApiArtifacts); - } - - - @Test - public void testGetCompositions() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCompositions(); - } - - - @Test - public void testSetCompositions() throws Exception { - TopologyTemplate testSubject; - Map compositions = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCompositions(compositions); - } - - - @Test - public void testGetCalculatedCapabilities() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCalculatedCapabilities(); - } - - - @Test - public void testSetCalculatedCapabilities() throws Exception { - TopologyTemplate testSubject; - Map calculatedCapabilities = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCalculatedCapabilities(calculatedCapabilities); - } - - - @Test - public void testGetCalculatedRequirements() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCalculatedRequirements(); - } - - - @Test - public void testSetCalculatedRequirements() throws Exception { - TopologyTemplate testSubject; - Map calculatedRequirements = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCalculatedRequirements(calculatedRequirements); - } - - - @Test - public void testGetFullfilledCapabilities() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getFullfilledCapabilities(); - } - - - @Test - public void testSetFullfilledCapabilities() throws Exception { - TopologyTemplate testSubject; - Map fullfilledCapabilities = null; - - // default test - testSubject = createTestSubject(); - testSubject.setFullfilledCapabilities(fullfilledCapabilities); - } - - - @Test - public void testGetFullfilledRequirements() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getFullfilledRequirements(); - } - - - @Test - public void testSetFullfilledRequirements() throws Exception { - TopologyTemplate testSubject; - Map fullfilledRequirements = null; - - // default test - testSubject = createTestSubject(); - testSubject.setFullfilledRequirements(fullfilledRequirements); - } - - - @Test - public void testGetInstDeploymentArtifacts() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInstDeploymentArtifacts(); - } - - - @Test - public void testSetInstDeploymentArtifacts() throws Exception { - TopologyTemplate testSubject; - Map instDeploymentArtifacts = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInstDeploymentArtifacts(instDeploymentArtifacts); - } - - - @Test - public void testGetCalculatedCapabilitiesProperties() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCalculatedCapabilitiesProperties(); - } - - - @Test - public void testSetCalculatedCapabilitiesProperties() throws Exception { - TopologyTemplate testSubject; - Map calculatedCapabilitiesProperties = null; - - // default test - testSubject = createTestSubject(); - testSubject.setCalculatedCapabilitiesProperties(calculatedCapabilitiesProperties); - } - - - @Test - public void testGetInstanceArtifacts() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInstanceArtifacts(); - } - - - @Test - public void testSetInstanceArtifacts() throws Exception { - TopologyTemplate testSubject; - Map instanceArtifacts = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInstanceArtifacts(instanceArtifacts); - } - - - @Test - public void testGetDataTypes() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDataTypes(); - } - - - @Test - public void testSetDataTypes() throws Exception { - TopologyTemplate testSubject; - Map dataTypes = null; - - // default test - testSubject = createTestSubject(); - testSubject.setDataTypes(dataTypes); - } - - - @Test - public void testGetComponentInstances() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getComponentInstances(); - } - - - @Test - public void testSetComponentInstances() throws Exception { - TopologyTemplate testSubject; - Map instances = null; - - // default test - testSubject = createTestSubject(); - testSubject.setComponentInstances(instances); - } - - - @Test - public void testGetRelations() throws Exception { - TopologyTemplate testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getRelations(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnumTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnumTest.java deleted file mode 100644 index 918b0328a9..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnumTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.datamodel; - -import org.junit.Test; - - -public class ToscaElementTypeEnumTest { - - private ToscaElementTypeEnum createTestSubject() { - return ToscaElementTypeEnum.TOPOLOGY_TEMPLATE; - } - - - - - - @Test - public void testGetValue() throws Exception { - ToscaElementTypeEnum testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getValue(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnumTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnumTest.java deleted file mode 100644 index b00b13e162..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnumTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.enums; - -import org.junit.Test; - - -public class JsonConstantKeysEnumTest { - - private JsonConstantKeysEnum createTestSubject() { - return JsonConstantKeysEnum.COMPOSITION; - } - - - @Test - public void testGetValue() throws Exception { - JsonConstantKeysEnum testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getValue(); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArchiveOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArchiveOperationTest.java deleted file mode 100644 index b906604037..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArchiveOperationTest.java +++ /dev/null @@ -1,486 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; -import org.openecomp.sdc.be.model.jsontitan.utils.GraphTestUtils; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import javax.annotation.Resource; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Created by yavivi on 21/03/2018. - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(value = {"classpath:application-context-test.xml", "classpath:healing-context-test.xml"}) -public class ArchiveOperationTest extends ModelTestBase { - - private static final String CI_UID_RES1_CP = "cp_uid"; - private static final String CI_UID_RES2_VL = "vl_uid"; - private static final String CI_UID_SVC_PROXY = "svc_proxy_uid"; - - @Resource - private ArchiveOperation archiveOperation; - - @Resource - private TitanDao titanDao; - - private boolean isInitialized; - - private GraphVertex serviceVertex1; - private GraphVertex archivedVertex1; - - GraphVertex archiveVertex; - GraphVertex catalogVertex; - - private GraphVertex serviceVertex1_0; - private GraphVertex serviceVertex1_1; - private GraphVertex serviceVertex2_0; - private GraphVertex serviceVertex3_0; - private GraphVertex serviceVertex3_1; - - private GraphVertex serviceVertex0_1; - private GraphVertex serviceVertex0_2; - private GraphVertex serviceVertex0_3; - private GraphVertex serviceVertex0_4; - private GraphVertex serviceVertex0_5; - - //Composition Elements - private GraphVertex compositionService; - private GraphVertex compositionResource1; - private GraphVertex compositionResource2; - private GraphVertex compositionServiceProxy; - private GraphVertex compositionAnotherService; - - //For VSP Archive Notification - private GraphVertex vfResource0_1; - private GraphVertex vfResource0_2; - private GraphVertex vfResource1_0; - private String csarUuid = "123456789";; - - @BeforeClass - public static void initTest(){ - ModelTestBase.init(); - } - - @Before - public void beforeTest() { - if (!isInitialized) { - GraphTestUtils.clearGraph(titanDao); - initGraphForTest(); - isInitialized = true; - } - } - - @Test - public void testArchiveComponentSingleVersion(){ - String componentId = serviceVertex1.getUniqueId(); - Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(componentId); - assertThat(actionStatus.isLeft()).isTrue(); - assertArchived(serviceVertex1.getUniqueId()); - } - - @Test - public void testArchiveComponentFailsWhenInCheckoutSingleVersion(){ - checkoutComponent(serviceVertex1); - String componentId = serviceVertex1.getUniqueId(); - Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(componentId); - assertThat(actionStatus.isLeft()).isFalse(); - assertThat(actionStatus.right().value()).isEqualTo(ActionStatus.INVALID_SERVICE_STATE); - } - - @Test - public void testArchiveWithWrongId() { - Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent("fakeComponentId"); - assertThat(actionStatus.isLeft()).isFalse(); - assertThat(actionStatus.right().value()).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND); - } - - @Test - public void testAlreadyArchived() { - Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(archivedVertex1.getUniqueId()); - assertThat(actionStatus.isLeft()).isTrue(); - assertThat(actionStatus.left().value()).containsExactly(archivedVertex1.getUniqueId()); - } - - @Test - public void testScenario2_archive_1_0(){ - Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex1_0.getUniqueId()); - assertThat(actionStatus.isLeft()).isTrue(); - assertThat(actionStatus.left().value()).containsExactlyInAnyOrder(serviceVertex1_0.getUniqueId(), serviceVertex1_1.getUniqueId()); - assertArchived(serviceVertex1_0.getUniqueId()); - assertArchived(serviceVertex1_1.getUniqueId()); - } - - @Test - public void testScenario2_archive_1_1(){ - Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex1_1.getUniqueId()); - assertThat(actionStatus.left().value()).containsExactlyInAnyOrder(serviceVertex1_0.getUniqueId(), serviceVertex1_1.getUniqueId()); - assertArchived(serviceVertex1_0.getUniqueId()); - assertArchived(serviceVertex1_1.getUniqueId()); - } - - @Test - public void testScenario4_oneLowOneHighestVersion(){ - Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex0_2.getUniqueId()); - assertThat(actionStatus.left().value()).containsExactlyInAnyOrder(serviceVertex0_2.getUniqueId(), serviceVertex0_1.getUniqueId(), serviceVertex0_3.getUniqueId(), serviceVertex0_4.getUniqueId(), serviceVertex0_5.getUniqueId()); - assertArchived(serviceVertex0_1.getUniqueId()); - assertArchived(serviceVertex0_2.getUniqueId()); - assertArchived(serviceVertex0_3.getUniqueId()); - assertArchived(serviceVertex0_4.getUniqueId()); - assertArchived(serviceVertex0_5.getUniqueId()); - - actionStatus = this.archiveOperation.restoreComponent(serviceVertex0_2.getUniqueId()); - assertThat(actionStatus.isLeft()).isTrue(); - assertThat(actionStatus.left().value()).containsExactlyInAnyOrder(serviceVertex0_2.getUniqueId(), serviceVertex0_1.getUniqueId(), serviceVertex0_3.getUniqueId(), serviceVertex0_4.getUniqueId(), serviceVertex0_5.getUniqueId()); - } - - - /////////////// Continue Here ////////////////// - @Test - public void testScenario4_archiveFromNonHighest(){ - Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex0_2.getUniqueId()); - assertArchived(serviceVertex0_1.getUniqueId()); - assertArchived(serviceVertex0_2.getUniqueId()); - assertArchived(serviceVertex0_3.getUniqueId()); - assertArchived(serviceVertex0_4.getUniqueId()); - assertArchived(serviceVertex0_5.getUniqueId()); - - actionStatus = this.archiveOperation.restoreComponent(serviceVertex0_3.getUniqueId()); - assertRestored(serviceVertex0_1.getUniqueId()); - assertRestored(serviceVertex0_2.getUniqueId()); - assertRestored(serviceVertex0_3.getUniqueId()); - assertRestored(serviceVertex0_4.getUniqueId()); - assertRestored(serviceVertex0_5.getUniqueId()); - } - - @Test - public void testArchiveFailsWhenHighestVersionIsInCheckoutState(){ - checkoutComponent(serviceVertex0_5); - Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex0_2.getUniqueId()); - assertThat(actionStatus.right().value()).isEqualTo(ActionStatus.INVALID_SERVICE_STATE); - } - - @Test - public void testScenario3_archive_3_0(){ - Either, ActionStatus> actionStatus = this.archiveOperation.archiveComponent(serviceVertex3_0.getUniqueId()); - assertArchived(serviceVertex3_0.getUniqueId()); - assertArchived(serviceVertex3_1.getUniqueId()); - assertArchivedProps(serviceVertex2_0.getUniqueId()); - } - - @Test - public void testArchivedOriginsCalculation(){ - - //Archive the CP resource - this.archiveOperation.archiveComponent(this.compositionResource1.getUniqueId()); - this.archiveOperation.archiveComponent(this.compositionServiceProxy.getUniqueId()); - - List ciWithArchivedOrigins = this.archiveOperation.setArchivedOriginsFlagInComponentInstances(this.compositionService); - - //Validate that method returns the CI of CP - assertThat(ciWithArchivedOrigins).containsExactlyInAnyOrder(CI_UID_RES1_CP, CI_UID_SVC_PROXY); - - Map compositionsJson = (Map) this.compositionService.getJson(); - - assertThat(compositionsJson).isNotNull(); - assertThat(compositionsJson.get(JsonConstantKeysEnum.COMPOSITION.getValue())).isNotNull(); - - CompositionDataDefinition composition = compositionsJson.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - - //Get all component instances from composition - Map componentInstances = composition.getComponentInstances(); - for (ComponentInstanceDataDefinition ci : componentInstances.values()) { - //Verify that exactly 2 CIs are marked as archived - if (ci.getUniqueId().equals(CI_UID_RES1_CP) || ci.getUniqueId().equals(CI_UID_SVC_PROXY)) { - assertThat(ci.isOriginArchived()).isTrue(); - } - } - - } - - @Test - public void testNoArchivedOriginsCalculation(){ - List ciWithArchivedOrigins = this.archiveOperation.setArchivedOriginsFlagInComponentInstances(this.compositionService); - - //Validate that method returns the CI of CP - assertThat(ciWithArchivedOrigins).isEmpty(); - } - - @Test - public void testOnVspArchivedAndRestored(){ - this.archiveOperation.onVspArchived(csarUuid); - //assertOnCommit(); - - assertOnVspArchived(true); - - this.archiveOperation.onVspRestored(csarUuid); - //assertOnCommit(); - assertOnVspArchived(false); - - //Not Found CSAR UUID - ActionStatus result = this.archiveOperation.onVspRestored("fakeUuid"); - //assertOnCommit(); - assertThat(result).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND); - } - - private void assertOnVspArchived(boolean expectedValue) { - GraphVertex v = titanDao.getVertexById(vfResource0_1.getUniqueId()).left().value(); - assertThat(v.getMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED)).isEqualTo(expectedValue); - - v = titanDao.getVertexById(vfResource0_2.getUniqueId()).left().value(); - assertThat(v.getMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED)).isEqualTo(expectedValue); - - v = titanDao.getVertexById(vfResource1_0.getUniqueId()).left().value(); - assertThat(v.getMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED)).isEqualTo(expectedValue); - } - - /************************** - * Utility Methods - *************************/ - - private void checkoutComponent(GraphVertex serviceVertex0_5) { - Either vE = titanDao.getVertexById(serviceVertex0_5.getUniqueId()); - GraphVertex v = vE.left().value(); - v.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - v.setJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - titanDao.updateVertex(v); - assertOnCommit(); - } - - private void assertOnCommit(){ - final TitanOperationStatus commit = this.titanDao.commit(); - assertThat(commit).isEqualTo(TitanOperationStatus.OK); - } - - private void assertArchived(String componentUniqueId) { - assertArchivedOrRestored(ArchiveOperation.Action.ARCHIVE, componentUniqueId); - } - - private void assertRestored(String componentUniqueId) { - assertArchivedOrRestored(ArchiveOperation.Action.RESTORE, componentUniqueId); - } - - private void assertArchivedOrRestored(ArchiveOperation.Action action, String componentUniqueId) { - GraphVertex v = titanDao.getVertexById(componentUniqueId).left().value(); - - EdgeLabelEnum requiredEdge = action == ArchiveOperation.Action.ARCHIVE ? EdgeLabelEnum.ARCHIVE_ELEMENT : EdgeLabelEnum.CATALOG_ELEMENT; - EdgeLabelEnum otherEdge = action == ArchiveOperation.Action.ARCHIVE ? EdgeLabelEnum.CATALOG_ELEMENT : EdgeLabelEnum.ARCHIVE_ELEMENT; - - GraphVertex parent = null; - Either otherLookup = null; - Boolean isHighest = (Boolean) v.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); - if (isHighest != null && isHighest) { - //Highest version are linked to Archive/Catalog Root - parent = titanDao.getParentVertex(v, requiredEdge, JsonParseFlagEnum.NoParse).left().value(); - otherLookup = titanDao.getParentVertex(v, otherEdge, JsonParseFlagEnum.NoParse); - assertThat(otherLookup.isRight()).isTrue(); //Verify that component is not linked to Catalog/Archive Root - assertThat(parent.getUniqueId()).isEqualTo(action == ArchiveOperation.Action.ARCHIVE ? this.archiveVertex.getUniqueId() : this.catalogVertex.getUniqueId()); //Verify that parent is indeed Archive Root - } - - assertArchivedOrRestoredProps(action, v); - } - - private void assertArchivedProps(String uniqueId) { - GraphVertex v = - titanDao.getVertexById(uniqueId).left().value(); - assertArchivedOrRestoredProps(ArchiveOperation.Action.ARCHIVE, v); - } - - private void assertRestoredProps(String uniqueId) { - GraphVertex v = - titanDao.getVertexById(uniqueId).left().value(); - assertArchivedOrRestoredProps(ArchiveOperation.Action.RESTORE, v); - } - - private void assertArchivedOrRestoredProps(ArchiveOperation.Action action, GraphVertex v) { - Object isArchived = v.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED); - Object archiveTime = v.getMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME); - assertThat(isArchived).isNotNull().isEqualTo(action == ArchiveOperation.Action.ARCHIVE ? true : false); - assertThat(archiveTime).isNotNull(); - } - - /******************************* - * Preperation Methods - *******************************/ - private void initGraphForTest() { - //Create Catalog Root - this.catalogVertex = GraphTestUtils.createRootCatalogVertex(titanDao); - //Create Archive Root - this.archiveVertex = GraphTestUtils.createRootArchiveVertex(titanDao); - - createScenario1_SingleVersionNode(); - createScenario2_TwoHighestVersions(); - createScenario3_TwoHighestVersionsOneLowest(); - createMiscServices(); - createServiceCompositionForCalculatingArchivedOrigins(); - createScenario4_1Highest4LowestVersions(); - createResourcesForArchivedVsp(); - - assertOnCommit(); - } - - private void createScenario1_SingleVersionNode() { - //Create Service for Scenario 1 Tests (1 Service) - this.serviceVertex1 = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); - - //Connect Service to Catalog Root - titanDao.createEdge(catalogVertex, serviceVertex1, EdgeLabelEnum.CATALOG_ELEMENT, null); - } - - private void createScenario2_TwoHighestVersions() { - //Create Service for Scenario 2 Tests (1 Service) - this.serviceVertex1_0 = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); - this.serviceVertex1_1 = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); - - titanDao.createEdge(serviceVertex1_0, serviceVertex1_1, EdgeLabelEnum.VERSION, null); - - //Connect 1.0 and 1.1 to Catalog Root - titanDao.createEdge(catalogVertex, serviceVertex1_0, EdgeLabelEnum.CATALOG_ELEMENT, null); - titanDao.createEdge(catalogVertex, serviceVertex1_1, EdgeLabelEnum.CATALOG_ELEMENT, null); - } - - private void createScenario3_TwoHighestVersionsOneLowest() { - //Create Service for Scenario 1 Tests (1 Service) - this.serviceVertex2_0 = GraphTestUtils.createServiceVertex(titanDao, propsForNonHighestVersion()); //NonHighestVersion - this.serviceVertex3_0 = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); - this.serviceVertex3_1 = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); - - //Connect version edges - titanDao.createEdge(serviceVertex2_0, serviceVertex3_0, EdgeLabelEnum.VERSION, null); - titanDao.createEdge(serviceVertex3_0, serviceVertex3_1, EdgeLabelEnum.VERSION, null); - - //Connect 3.0 and 3.1 to Catalog Root - titanDao.createEdge(catalogVertex, serviceVertex3_0, EdgeLabelEnum.CATALOG_ELEMENT, null); - titanDao.createEdge(catalogVertex, serviceVertex3_1, EdgeLabelEnum.CATALOG_ELEMENT, null); - } - - private void createScenario4_1Highest4LowestVersions() { - //2 Lowest version only - this.serviceVertex0_1 = GraphTestUtils.createServiceVertex(titanDao, propsForNonHighestVersion()); - this.serviceVertex0_2 = GraphTestUtils.createServiceVertex(titanDao, propsForNonHighestVersion()); - this.serviceVertex0_3 = GraphTestUtils.createServiceVertex(titanDao, propsForNonHighestVersion()); - this.serviceVertex0_4 = GraphTestUtils.createServiceVertex(titanDao, propsForNonHighestVersion()); - this.serviceVertex0_5 = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); - - titanDao.createEdge(serviceVertex0_1, serviceVertex0_2, EdgeLabelEnum.VERSION, null); - titanDao.createEdge(serviceVertex0_2, serviceVertex0_3, EdgeLabelEnum.VERSION, null); - titanDao.createEdge(serviceVertex0_3, serviceVertex0_4, EdgeLabelEnum.VERSION, null); - titanDao.createEdge(serviceVertex0_4, serviceVertex0_5, EdgeLabelEnum.VERSION, null); - - titanDao.createEdge(catalogVertex, serviceVertex0_5, EdgeLabelEnum.CATALOG_ELEMENT, null); - } - - private void createResourcesForArchivedVsp(){ - Map vfPropsNonHighest = propsForNonHighestVersion(); - Map vfPropsHighest = propsForNonHighestVersion(); - - vfPropsNonHighest.put(GraphPropertyEnum.CSAR_UUID, csarUuid); - vfPropsNonHighest.put(GraphPropertyEnum.IS_VSP_ARCHIVED, false); - vfPropsHighest.put(GraphPropertyEnum.CSAR_UUID, csarUuid); - vfPropsHighest.put(GraphPropertyEnum.IS_VSP_ARCHIVED, false); - - this.vfResource0_1 = GraphTestUtils.createResourceVertex(titanDao, vfPropsNonHighest, ResourceTypeEnum.VF); - this.vfResource0_2 = GraphTestUtils.createResourceVertex(titanDao, vfPropsNonHighest, ResourceTypeEnum.VF); - this.vfResource1_0 = GraphTestUtils.createResourceVertex(titanDao, vfPropsHighest, ResourceTypeEnum.VF); - - titanDao.createEdge(vfResource0_1, vfResource0_2, EdgeLabelEnum.VERSION, null); - titanDao.createEdge(vfResource0_2, vfResource1_0, EdgeLabelEnum.VERSION, null); - } - - private void createMiscServices() { - //Create Service for Scenario 1 Tests (1 Service) - this.archivedVertex1 = GraphTestUtils.createServiceVertex(titanDao, new HashMap<>()); - - //Connect Service to Catalog Root - titanDao.createEdge(archiveVertex, archivedVertex1, EdgeLabelEnum.ARCHIVE_ELEMENT, null); - } - - private void createServiceCompositionForCalculatingArchivedOrigins(){ - //Service that point to another service in composition - this.compositionService = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); - this.compositionAnotherService = GraphTestUtils.createServiceVertex(titanDao, propsForHighestVersion()); - - this.compositionResource1 = GraphTestUtils.createResourceVertex(titanDao, propsForHighestVersion(), ResourceTypeEnum.CP); - this.compositionResource2 = GraphTestUtils.createResourceVertex(titanDao, propsForHighestVersion(), ResourceTypeEnum.VL); - this.compositionServiceProxy = GraphTestUtils.createResourceVertex(titanDao, propsForHighestVersion(), ResourceTypeEnum.ServiceProxy); - - titanDao.createEdge(compositionService, compositionResource1, EdgeLabelEnum.INSTANCE_OF, null); - titanDao.createEdge(compositionService, compositionResource2, EdgeLabelEnum.INSTANCE_OF, null); - titanDao.createEdge(compositionService, compositionServiceProxy, EdgeLabelEnum.INSTANCE_OF, null); - titanDao.createEdge(compositionService, compositionAnotherService, EdgeLabelEnum.PROXY_OF, null); - - createAndAttachCompositionJson(compositionService); - } - - private void createAndAttachCompositionJson(GraphVertex compositionService) { - //Full composition json - Map compositions = new HashMap<>(); - //Single composition data - CompositionDataDefinition composition = new CompositionDataDefinition(); - //Instances Map - Map instances = new HashMap<>(); - - //Prepare Instances Map - ComponentInstanceDataDefinition instance = new ComponentInstanceDataDefinition(); - instance.setUniqueId(CI_UID_RES1_CP); - instance.setComponentUid(compositionResource1.getUniqueId()); - instances.put(CI_UID_RES1_CP, instance); - - instance = new ComponentInstanceDataDefinition(); - instance.setUniqueId(CI_UID_RES2_VL); - instance.setComponentUid(compositionResource2.getUniqueId()); - instances.put(CI_UID_RES2_VL, instance); - - instance = new ComponentInstanceDataDefinition(); - instance.setUniqueId(CI_UID_SVC_PROXY); - instance.setComponentUid(compositionServiceProxy.getUniqueId()); - instances.put(CI_UID_SVC_PROXY, instance); - - //Add Instances to Composition - composition.setComponentInstances(instances); - //Add to full composition - compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), composition); - //Add Full Json to vertex - compositionService.setJson(compositions); - //System.out.println(JsonParserUtils.toJson(compositions)); - titanDao.updateVertex(compositionService); - } - - private Map propsForHighestVersion(){ - Map props = new HashMap(); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - return props; - } - - private Map propsForNonHighestVersion(){ - Map props = new HashMap(); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, false); - props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - return props; - } - -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java deleted file mode 100644 index 410cef9ae8..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -import org.junit.Test; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -public class ArtifactsOperationsTest { - - private static final String SERVICE_ID = "serviceId"; - private static final String INSTANCE_ID = "instanceId"; - private ArtifactsOperations testInstance = mock(ArtifactsOperations.class, CALLS_REAL_METHODS); - - @Test - public void getInstanceArtifacts_collectAllInstanceArtifacts() throws Exception { - Map instanceArtifacts = Collections.singletonMap(INSTANCE_ID, getArtifactsByInstance("name1")); - - Map instanceDeploymentArtifacts = new HashMap<>(); - instanceDeploymentArtifacts.put(INSTANCE_ID, getArtifactsByInstance("name2", "name3")); - instanceDeploymentArtifacts.put("instanceId2", getArtifactsByInstance("name4")); - - doReturn(Either.left(instanceArtifacts)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS); - doReturn(Either.left(instanceDeploymentArtifacts)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); - Either, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, INSTANCE_ID); - - assertTrue(allInstArtifacts.isLeft()); - assertEquals(allInstArtifacts.left().value().size(), 3); - assertTrue(allInstArtifacts.left().value().containsKey("name1")); - assertTrue(allInstArtifacts.left().value().containsKey("name2")); - assertTrue(allInstArtifacts.left().value().containsKey("name3")); - assertFalse(allInstArtifacts.left().value().containsKey("name4"));//this key is of different instance - } - - @Test - public void getInstanceArtifacts_noArtifactsForInstance() throws Exception { - Map instanceArtifacts = Collections.singletonMap(INSTANCE_ID, getArtifactsByInstance("name1")); - - doReturn(Either.left(instanceArtifacts)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS); - doReturn(Either.left(new HashMap<>())).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); - Either, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, "someOtherInstance"); - - assertTrue(allInstArtifacts.isLeft()); - assertTrue(allInstArtifacts.left().value().isEmpty()); - } - - @Test - public void getInstanceArtifacts_errorGettingInstanceArtifacts() throws Exception { - doReturn(Either.right(TitanOperationStatus.GENERAL_ERROR)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS); - Either, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, INSTANCE_ID); - verify(testInstance, times(0)).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); - assertTrue(allInstArtifacts.isRight()); - } - - @Test - public void getAllInstanceArtifacts_errorGettingDeploymentArtifacts() throws Exception { - doReturn(Either.left(new HashMap<>())).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS); - doReturn(Either.right(TitanOperationStatus.GENERAL_ERROR)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); - Either, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, INSTANCE_ID); - assertTrue(allInstArtifacts.isRight()); - } - - private ToscaDataDefinition getArtifactsByInstance(String ... artifactsNames) { - MapArtifactDataDefinition artifactsByInstance = new MapArtifactDataDefinition(); - Map artifactsByName = new HashMap<>(); - for (String artifactName : artifactsNames) { - artifactsByName.put(artifactName, new ArtifactDataDefinition()); - } - artifactsByInstance.setMapToscaDataDefinition(artifactsByName); - return artifactsByInstance; - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/CapabilitiesOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/CapabilitiesOperationTest.java deleted file mode 100644 index 0c9c35b62a..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/CapabilitiesOperationTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright © 2016-2018 European Support Limited - * - * 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. - */ - -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.utils.CapabilityTestUtils; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; - -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - -public class CapabilitiesOperationTest { - - @InjectMocks - CapabilitiesOperation operation = new CapabilitiesOperation(); - @Mock - private TitanDao mockTitanDao; - @Mock - private TopologyTemplateOperation topologyTemplateOperation; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - when(mockTitanDao.commit()).thenReturn(TitanOperationStatus.OK); - when(mockTitanDao.getVertexById(anyString(), any())).thenReturn(Either.left(new GraphVertex())); - - when(topologyTemplateOperation.updateFullToscaData(any(), any(), any(), anyMap())).thenReturn(StorageOperationStatus.OK); - TopologyTemplate topologyTemplate = new TopologyTemplate(); - - Map capPropsForTopologyTemplate = CapabilityTestUtils - .createCapPropsForTopologyTemplate(topologyTemplate); - topologyTemplate.setCapabilitiesProperties(capPropsForTopologyTemplate); - - when(topologyTemplateOperation.getToscaElement(anyString(), any())).thenReturn(Either.left(topologyTemplate)); - } - - @Test - public void testCreateOrUpdateCapabilitiesProperties() { - - Map mapToscaDataDefinition = new HashMap<>(); - PropertyDataDefinition propertyDataDefinition = new PropertyDataDefinition(); - propertyDataDefinition.setUniqueId("ComponentInput1_uniqueId"); - propertyDataDefinition.setName("propName"); - mapToscaDataDefinition.put(propertyDataDefinition.getUniqueId(), propertyDataDefinition); - MapPropertiesDataDefinition mapPropertiesDataDefinition = new MapPropertiesDataDefinition(mapToscaDataDefinition); - - Map propertiesMap = new HashMap<>(); - propertiesMap.put(propertyDataDefinition.getUniqueId(), mapPropertiesDataDefinition); - - StorageOperationStatus operationStatus = operation.createOrUpdateCapabilityProperties("componentId", - propertiesMap); - - Assert.assertEquals(StorageOperationStatus.OK, operationStatus); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperationTest.java deleted file mode 100644 index e580fd51bb..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperationTest.java +++ /dev/null @@ -1,226 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.MapComponentInstanceExternalRefs; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.jsontitan.utils.GraphTestUtils; -import org.openecomp.sdc.be.model.jsontitan.utils.IdMapper; -import org.openecomp.sdc.be.model.operations.StorageException; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import javax.annotation.Resource; -import java.util.*; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -/** - * Created by yavivi on 26/01/2018. - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:application-context-test.xml") -public class ExternalReferencesOperationTest extends ModelTestBase { - - private static final String COMPONENT_ID = "ci-MyComponentName"; - private static final String COMPONENT2_ID = "ci-MyComponentName2"; - private static final String MONITORING_OBJECT_TYPE = "monitoring"; - private static final String WORKFLOW_OBJECT_TYPE = "workflow"; - private static final String REF_1 = "ref1"; - private static final String REF_2 = "ref2"; - private static final String REF_3 = "ref3"; - private static final String REF_4 = "ref4"; - private static final String REF_5 = "ref5"; - //workflow - private static final String REF_6 = "ref6"; - - @Resource - private ExternalReferencesOperation externalReferenceOperation; - - @Resource - private TitanDao titanDao; - - private boolean isInitialized; - - private GraphVertex serviceVertex; - private GraphVertex serviceVertex2; - private GraphVertex serviceVertex3; - - private String serviceVertexUuid; - private String serviceVertex2Uuid; - private String serviceVertex3Uuid; - - private IdMapper idMapper; - - @BeforeClass - public static void initTest(){ - ModelTestBase.init(); - } - - @Before - public void beforeTest() { - idMapper = Mockito.mock(IdMapper.class); - this.externalReferenceOperation.setIdMapper(idMapper); - when(idMapper.mapComponentNameToUniqueId(Mockito.anyString(), Mockito.any(GraphVertex.class))).thenReturn(COMPONENT_ID); - if (!isInitialized) { - GraphTestUtils.clearGraph(titanDao); - initGraphForTest(); - isInitialized = true; - } - } - - @Test - public void testAddComponentInstanceExternalRef(){ - Either addResult = externalReferenceOperation.addExternalReference(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_4); - assertThat(addResult.isLeft()).isEqualTo(true); - - //commit changes to titan - final TitanOperationStatus commit = this.titanDao.commit(); - assertThat(commit).isEqualTo(TitanOperationStatus.OK); - - assertThat(getServiceExternalRefs()).contains(REF_1, REF_2, REF_3, REF_4); - } - - @Test - public void testAddExternalReferences_success() { - Map> refsMap = Collections.singletonMap(MONITORING_OBJECT_TYPE, Arrays.asList(REF_1, REF_2)); - externalReferenceOperation.addAllExternalReferences(serviceVertex3Uuid, COMPONENT_ID, refsMap); - Map> allExternalReferences = externalReferenceOperation.getAllExternalReferences(serviceVertex3Uuid, COMPONENT_ID); - assertThat(allExternalReferences.size()).isEqualTo(1); - assertThat(allExternalReferences).flatExtracting(MONITORING_OBJECT_TYPE).containsExactly(REF_1, REF_2); - externalReferenceOperation.addAllExternalReferences(serviceVertex3Uuid, COMPONENT2_ID, refsMap); - Map> allExternalReferences2 = externalReferenceOperation.getAllExternalReferences(serviceVertex3Uuid, COMPONENT2_ID); - assertThat(allExternalReferences2.size()).isEqualTo(1); - assertThat(allExternalReferences2).flatExtracting(MONITORING_OBJECT_TYPE).containsExactly(REF_1, REF_2); - } - - @Test - public void testGetAllCIExternalRefs_success() { - Map> allExternalReferences = externalReferenceOperation.getAllExternalReferences(serviceVertexUuid, COMPONENT_ID); - assertThat(allExternalReferences.size()).isEqualTo(2); - assertThat(allExternalReferences).flatExtracting(WORKFLOW_OBJECT_TYPE).containsExactly(REF_6); - assertThat(allExternalReferences).flatExtracting(MONITORING_OBJECT_TYPE).containsExactly(REF_1, REF_2, REF_3, REF_5); - } - - @Test - public void testGetAllCIExternalRefs_noRefsExist() { - Map> allExternalReferences = externalReferenceOperation.getAllExternalReferences(serviceVertex2Uuid, COMPONENT_ID); - assertThat(allExternalReferences.size()).isZero(); - } - - @Test - public void testGetAllCIExternalRefs_noSuchComponentInstance() { - Map> allExternalReferences = externalReferenceOperation.getAllExternalReferences(serviceVertex2Uuid, "FAKE"); - assertThat(allExternalReferences.size()).isZero(); - } - - @Test(expected=StorageException.class) - public void testGetAllCIExternalRefs_nonExitingService_throwsException() { - externalReferenceOperation.getAllExternalReferences("FAKE", COMPONENT_ID); - } - - @Test - public void testGetComponentInstanceExternalRef(){ - assertThat(externalReferenceOperation.getExternalReferences(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE).left().value()).contains(REF_1, REF_2, REF_3, REF_5); - assertThat(externalReferenceOperation.getExternalReferences(this.serviceVertexUuid, COMPONENT_ID, WORKFLOW_OBJECT_TYPE).left().value()).containsExactly(REF_6); - } - - @Test - public void testGetComponentInstanceExternalRefForNonExistingObjectId(){ - assertThat(externalReferenceOperation.getExternalReferences(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE).left().value()).contains(REF_1, REF_2, REF_3, REF_5); - Either, ActionStatus> getResult = externalReferenceOperation.getExternalReferences(this.serviceVertexUuid, COMPONENT_ID, "FAKE_OBJECT_TYPE"); - assertThat(getResult.left().value()).isEmpty(); - } - - @Test - public void testDeleteComponentInstanceExternalRef(){ - //Test the precondition - assertThat(getServiceExternalRefs()).contains(REF_5); - - //Remove REF 5 - Either deleteStatus = externalReferenceOperation.deleteExternalReference(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5); - assertThat(deleteStatus.isLeft()).isEqualTo(true); - - //commit changes to titan - final TitanOperationStatus commit = this.titanDao.commit(); - assertThat(commit).isEqualTo(TitanOperationStatus.OK); - - //Check that ref does not exist anymore - assertThat(getServiceExternalRefs()).doesNotContain(REF_5).contains(REF_1, REF_2, REF_3); - } - - @Test - public void testUpdateComponentInstanceExternalRef(){ - //Test the precondition - assertThat(getServiceExternalRefs()).contains(REF_5).doesNotContain(REF_4); - - //Update REF 5 with REF_4 - Either updateResult = externalReferenceOperation.updateExternalReference(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5, REF_4); - - assertThat(updateResult.isLeft()).isEqualTo(true); - - //commit changes to titan - final TitanOperationStatus commit = this.titanDao.commit(); - assertThat(commit).isEqualTo(TitanOperationStatus.OK); - - //Check that ref does not exist anymore - assertThat(getServiceExternalRefs()).doesNotContain(REF_5).contains(REF_1, REF_2, REF_3, REF_4); - } - - private List getServiceExternalRefs(){ - //Get service vertex - final Either externalRefsVertexResult = this.titanDao.getChildVertex(this.serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, JsonParseFlagEnum.ParseJson); - assertThat(externalRefsVertexResult.isLeft()).isEqualTo(true); - - GraphVertex externalRefVertex = externalRefsVertexResult.left().value(); - - //Get the full map - Map componentInstancesMap = (Map) externalRefVertex.getJson(); - assertThat(componentInstancesMap).isNotNull(); - - //Get Map of external refs by object type - final MapComponentInstanceExternalRefs mapComponentInstanceExternalRefs = componentInstancesMap.get(COMPONENT_ID); - - //Get List of references - //final List externalRefsByObjectType = mapComponentInstanceExternalRefs.externalRefsByObjectType(objectType); - - return mapComponentInstanceExternalRefs.getExternalRefsByObjectType(MONITORING_OBJECT_TYPE); - } - - private void initGraphForTest() { - //create a service - this.serviceVertex = GraphTestUtils.createServiceVertex(titanDao, new HashMap<>()); - this.serviceVertexUuid = this.serviceVertex.getUniqueId(); - - //monitoring references - externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_1); - externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_2); - externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_3); - externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5); - - //workflow references - externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, WORKFLOW_OBJECT_TYPE, REF_6); - - //create a service without refs - serviceVertex2 = GraphTestUtils.createServiceVertex(titanDao, new HashMap<>()); - serviceVertex2Uuid = serviceVertex2.getUniqueId(); - - //create a service for adding all references - serviceVertex3 = GraphTestUtils.createServiceVertex(titanDao, new HashMap<>()); - serviceVertex3Uuid = serviceVertex3.getUniqueId(); - - final TitanOperationStatus commit = this.titanDao.commit(); - assertThat(commit).isEqualTo(TitanOperationStatus.OK); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperationTest.java deleted file mode 100644 index 575fbbca59..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperationTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; - -import fj.data.Either; -import java.util.List; -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.config.TitanSpringConfig; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.HealingTitanDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {TitanSpringConfig.class, ModelOperationsSpringConfig.class}) -public class GroupsOperationTest extends ModelTestBase { - - @Autowired - private GroupsOperation groupsOperation; - - @Autowired - HealingTitanDao titanDao; - - @Autowired - private ToscaOperationFacade toscaOperationFacade; - private Component container; - - @BeforeClass - public static void initClass() { - ModelTestBase.init(); - } - - @Before - public void setUp() throws Exception { - container = new Resource(); - container.setUniqueId(CONTAINER_ID); - Either createdCmpt = titanDao.createVertex(createBasicContainerGraphVertex()); - assertThat(createdCmpt.isLeft()).isTrue(); - - } - - @After - public void tearDown() throws Exception { - titanDao.rollback(); - } - - @Test - public void addGroups_whenContainerHasNoGroups_associateContainerWithGroup() { - GroupDefinition g1 = createGroupDefinition("g1"); - GroupDefinition g2 = createGroupDefinition("g2"); - Either, StorageOperationStatus> createGroups = groupsOperation.addGroups(container, asList(g1, g2)); - assertThat(createGroups.isLeft()).isTrue(); - - ComponentParametersView getGroupsFilter = new ComponentParametersView(true); - getGroupsFilter.setIgnoreGroups(false); - Component cmptWithGroups = toscaOperationFacade.getToscaElement(CONTAINER_ID, getGroupsFilter).left().value(); - assertThat(cmptWithGroups.getGroups()) - .usingElementComparatorOnFields("name", "uniqueId") - .containsExactlyInAnyOrder(g1, g2); - } - - @Test - public void addGroups_whenContainerHasGroups_addTheGivenGroupsToTheGroupsList() { - GroupDefinition g1 = createGroupDefinition("g1"); - GroupDefinition g2 = createGroupDefinition("g2"); - groupsOperation.addGroups(container, asList(g1, g2)).left().value(); - - GroupDefinition g3 = createGroupDefinition("g3"); - GroupDefinition g4 = createGroupDefinition("g4"); - - groupsOperation.addGroups(container, asList(g3, g4)).left().value(); - - ComponentParametersView getGroupsFilter = new ComponentParametersView(true); - getGroupsFilter.setIgnoreGroups(false); - Component cmptWithGroups = toscaOperationFacade.getToscaElement(CONTAINER_ID, getGroupsFilter).left().value(); - assertThat(cmptWithGroups.getGroups()) - .usingElementComparatorOnFields("name", "uniqueId") - .containsExactlyInAnyOrder(g1, g2, g3, g4); - - } - - private GroupDefinition createGroupDefinition(String id) { - GroupDefinition groupDefinition = new GroupDefinition(); - groupDefinition.setUniqueId(id); - groupDefinition.setName("name" + id); - return groupDefinition; - } - - -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperationTest.java deleted file mode 100644 index fe2ea209f9..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperationTest.java +++ /dev/null @@ -1,497 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import fj.data.Either; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.annotation.Resource; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.Component; -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.Service; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.category.SubCategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.utils.GraphTestUtils; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.common.util.ValidationUtils; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:application-context-test.xml") -public class InterfaceOperationTest extends ModelTestBase { - - private static final String RESOURCE_NAME = "Resource Name"; - private static final String RESOURCE_ID = "resourceID"; - private static final String SERVICE_NAME = "Service Name"; - private static final String SERVICE_ID = "serviceID"; - private final String categoryName = "category"; - private final String subcategory = "mycategory"; - private final Service service = createService(); - private final org.openecomp.sdc.be.model.Resource resource = createResource(); - @Resource - protected TitanDao titanDao; - @Resource - protected NodeTypeOperation nodeTypeOperation; - @Resource - protected TopologyTemplateOperation topologyTemplateOperation; - @Resource - private InterfaceOperation interfaceOperation; - @Resource - private ToscaElementLifecycleOperation lifecycleOperation; - private GraphVertex ownerVertex; - - @BeforeClass - public static void initInterfacesOperation() { - init(); - } - - @Before - public void setupBefore() { - GraphTestUtils.clearGraph(titanDao); - createUsers(); - createResourceCategory(); - createServiceCategory(); - GraphTestUtils.createRootCatalogVertex(titanDao); - createRootNodeType(); - createNodeType("resource", RESOURCE_ID); - createNodeType("service", SERVICE_ID); - createTopologyTemplate("firstService"); - } - - private void createUsers() { - GraphVertex ownerV = new GraphVertex(VertexTypeEnum.USER); - ownerV.setUniqueId("user1"); - - Map metadataProperties = new HashMap<>(); - metadataProperties.put(GraphPropertyEnum.USERID, ownerV.getUniqueId()); - metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.USER.getName()); - metadataProperties.put(GraphPropertyEnum.NAME, "user1"); - ownerV.setMetadataProperties(metadataProperties); - ownerV.updateMetadataJsonWithCurrentMetadataProperties(); - ownerV.setJson(new HashMap<>()); - Either createUserRes = titanDao.createVertex(ownerV); - - ownerVertex = createUserRes.left().value(); - - GraphVertex modifierV = new GraphVertex(VertexTypeEnum.USER); - modifierV.setUniqueId("user2"); - - metadataProperties = new HashMap<>(); - metadataProperties.put(GraphPropertyEnum.USERID, modifierV.getUniqueId()); - metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.USER.getName()); - metadataProperties.put(GraphPropertyEnum.NAME, "user2"); - modifierV.setMetadataProperties(metadataProperties); - modifierV.updateMetadataJsonWithCurrentMetadataProperties(); - modifierV.setJson(new HashMap<>()); - createUserRes = titanDao.createVertex(modifierV); - createUserRes.left().value(); - - lifecycleOperation.findUser(ownerVertex.getUniqueId()); - } - - private void createResourceCategory() { - GraphVertex cat = new GraphVertex(VertexTypeEnum.RESOURCE_CATEGORY); - Map metadataProperties = new HashMap<>(); - String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.RESOURCE_CATEGORY); - cat.setUniqueId(catId); - metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId); - metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.RESOURCE_CATEGORY.getName()); - metadataProperties.put(GraphPropertyEnum.NAME, categoryName); - metadataProperties - .put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); - cat.setMetadataProperties(metadataProperties); - cat.updateMetadataJsonWithCurrentMetadataProperties(); - - GraphVertex subCat = new GraphVertex(VertexTypeEnum.RESOURCE_SUBCATEGORY); - metadataProperties = new HashMap<>(); - String subCatId = UniqueIdBuilder.buildSubCategoryUid(cat.getUniqueId(), subcategory); - subCat.setUniqueId(subCatId); - metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, subCatId); - metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.RESOURCE_SUBCATEGORY.getName()); - metadataProperties.put(GraphPropertyEnum.NAME, subcategory); - metadataProperties - .put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(subcategory)); - subCat.setMetadataProperties(metadataProperties); - subCat.updateMetadataJsonWithCurrentMetadataProperties(); - - Either catRes = titanDao.createVertex(cat); - Either subCatRes = titanDao.createVertex(subCat); - titanDao.createEdge(catRes.left().value().getVertex(), subCatRes.left().value().getVertex(), - EdgeLabelEnum.SUB_CATEGORY, new HashMap<>()); - } - - private void createServiceCategory() { - GraphVertex cat = new GraphVertex(VertexTypeEnum.SERVICE_CATEGORY); - Map metadataProperties = new HashMap<>(); - String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.SERVICE_CATEGORY); - cat.setUniqueId(catId); - metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId); - metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.SERVICE_CATEGORY.getName()); - metadataProperties.put(GraphPropertyEnum.NAME, categoryName); - metadataProperties - .put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); - cat.setMetadataProperties(metadataProperties); - cat.updateMetadataJsonWithCurrentMetadataProperties(); - titanDao.createVertex(cat); - } - - private void createRootNodeType() { - NodeType vf = new NodeType(); - String uniqueId = UniqueIdBuilder.buildResourceUniqueId(); - vf.setUniqueId(uniqueId); - vf.setComponentType(ComponentTypeEnum.RESOURCE); - vf.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); - vf.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), "root"); - vf.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); - vf.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "1.0"); - vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VFC.name()); - vf.getMetadata() - .put(JsonPresentationFields.LIFECYCLE_STATE.getPresentation(), LifecycleStateEnum.CERTIFIED.name()); - vf.getMetadata().put(JsonPresentationFields.TOSCA_RESOURCE_NAME.getPresentation(), "root"); - vf.getMetadata().put(JsonPresentationFields.HIGHEST_VERSION.getPresentation(), true); - - List categories = new ArrayList<>(); - CategoryDefinition cat = new CategoryDefinition(); - categories.add(cat); - cat.setName(categoryName); - List subCategories = new ArrayList<>(); - SubCategoryDefinition subCat = new SubCategoryDefinition(); - subCat.setName(subcategory); - subCategories.add(subCat); - cat.setSubcategories(subCategories); - vf.setCategories(categories); - - List derivedFrom = new ArrayList<>(); - vf.setDerivedFrom(derivedFrom); - - Map properties = new HashMap<>(); - PropertyDataDefinition prop1 = new PropertyDataDefinition(); - prop1.setName("derived1"); - prop1.setDefaultValue("deriveddef1"); - properties.put("derived1", prop1); - - PropertyDataDefinition prop2 = new PropertyDataDefinition(); - prop2.setUniqueId("derived2"); - prop2.setName("deriveddef2"); - properties.put("derived2", prop2); - - PropertyDataDefinition prop3 = new PropertyDataDefinition(); - prop3.setName("derived3"); - prop3.setDefaultValue("deriveddef3"); - properties.put("derived3", prop3); - - vf.setProperties(properties); - vf.setComponentType(ComponentTypeEnum.RESOURCE); - Either createVFRes = nodeTypeOperation.createNodeType(vf); - - Either getNodeTyeRes = - titanDao.getVertexById(createVFRes.left().value().getUniqueId()); - getNodeTyeRes.left().value(); - } - - private void createNodeType(String nodeTypeName, String uniqueId) { - NodeType vf = new NodeType(); - vf.setUniqueId(uniqueId); - vf.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); - vf.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), nodeTypeName); - vf.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); - vf.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "0.1"); - vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VF.name()); - vf.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), ComponentTypeEnum.RESOURCE); - List categories = new ArrayList<>(); - CategoryDefinition cat = new CategoryDefinition(); - categories.add(cat); - cat.setName(categoryName); - List subCategories = new ArrayList<>(); - SubCategoryDefinition subCat = new SubCategoryDefinition(); - subCat.setName(subcategory); - subCategories.add(subCat); - cat.setSubcategories(subCategories); - vf.setCategories(categories); - - List derivedFrom = new ArrayList<>(); - derivedFrom.add("root"); - vf.setDerivedFrom(derivedFrom); - - vf.setComponentType(ComponentTypeEnum.RESOURCE); - - List addProperties = new ArrayList<>(); - PropertyDataDefinition prop11 = new PropertyDataDefinition(); - prop11.setName("prop11"); - prop11.setDefaultValue("def11"); - - addProperties.add(prop11); - - PropertyDataDefinition prop22 = new PropertyDataDefinition(); - prop22.setName("prop22"); - prop22.setDefaultValue("def22"); - addProperties.add(prop22); - - Either createVFRes = nodeTypeOperation.createNodeType(vf); - Either getNodeTyeRes = - titanDao.getVertexById(createVFRes.left().value().getUniqueId()); - GraphVertex vfVertex = getNodeTyeRes.left().value(); - StorageOperationStatus status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, - VertexTypeEnum.PROPERTIES, addProperties, JsonPresentationFields.NAME); - assertSame(StorageOperationStatus.OK, status); - - PropertyDataDefinition prop33 = new PropertyDataDefinition(); - prop33.setName("prop33"); - prop33.setDefaultValue("def33"); - - status = nodeTypeOperation - .addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, - prop33, JsonPresentationFields.NAME); - assertSame(StorageOperationStatus.OK, status); - - PropertyDataDefinition prop44 = new PropertyDataDefinition(); - prop44.setName("prop44"); - prop44.setDefaultValue("def44"); - - status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex.getUniqueId(), EdgeLabelEnum.PROPERTIES, - VertexTypeEnum.PROPERTIES, prop44, JsonPresentationFields.NAME); - assertSame(StorageOperationStatus.OK, status); - - PropertyDataDefinition capProp = new PropertyDataDefinition(); - capProp.setName("capProp"); - capProp.setDefaultValue("capPropDef"); - - MapDataDefinition dataToCreate = new MapPropertiesDataDefinition(); - dataToCreate.put("capProp", capProp); - - Map capProps = new HashMap<>(); - capProps.put("capName", dataToCreate); - - nodeTypeOperation.associateElementToData(vfVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, - EdgeLabelEnum.CAPABILITIES_PROPERTIES, capProps); - - List pathKeys = new ArrayList<>(); - pathKeys.add("capName"); - capProp.setDefaultValue("BBBB"); - nodeTypeOperation.updateToscaDataDeepElementOfToscaElement(vfVertex, EdgeLabelEnum.CAPABILITIES_PROPERTIES, - VertexTypeEnum.CAPABILITIES_PROPERTIES, capProp, pathKeys, JsonPresentationFields.NAME); - } - - private void createTopologyTemplate(String name) { - TopologyTemplate service = new TopologyTemplate(); - String uniqueId = UniqueIdBuilder.buildResourceUniqueId(); - service.setUniqueId(uniqueId); - service.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); - service.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), name); - service.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); - service.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "0.1"); - service.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VF.name()); - service.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), ComponentTypeEnum.RESOURCE); - List categories = new ArrayList<>(); - CategoryDefinition cat = new CategoryDefinition(); - categories.add(cat); - cat.setName(categoryName); - service.setCategories(categories); - - service.setComponentType(ComponentTypeEnum.SERVICE); - Either createRes = - topologyTemplateOperation.createTopologyTemplate(service); - Either getNodeTyeRes = - titanDao.getVertexById(createRes.left().value().getUniqueId()); - - getNodeTyeRes.left().value(); - } - - @After - public void cleanAfter() { - GraphTestUtils.clearGraph(titanDao); - } - - @Test - public void testAddInterface_Service() { - testAddSingleInterface(service); - } - - private void testAddSingleInterface(Component component) { - InterfaceDefinition interfaceDefinition = buildInterfaceDefinition("1"); - Either, StorageOperationStatus> res = interfaceOperation - .addInterfaces(component.getUniqueId(), - Collections.singletonList( - interfaceDefinition)); - Assert.assertTrue(res.isLeft()); - Assert.assertEquals("1", res.left().value().get(0).getUniqueId()); - } - - private InterfaceDefinition buildInterfaceDefinition(String uniqueId) { - InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); - interfaceDefinition.setType("tosca.interfaces.standard"); - interfaceDefinition.setUniqueId(uniqueId); - interfaceDefinition.setOperationsMap(createMockOperationMap()); - return interfaceDefinition; - } - - private Map createMockOperationMap() { - Map operationMap = new HashMap<>(); - operationMap.put("op1", createMockOperation()); - return operationMap; - } - - private Operation createMockOperation() { - Operation operation = new Operation(); - operation.setDefinition(false); - operation.setName("create"); - operation.setUniqueId("op1"); - return operation; - } - - @Test - public void testAddInterface_Resource() { - testAddMultipleInterface(resource); - } - - private void testAddMultipleInterface(Component component) { - InterfaceDefinition interfaceDefinition1 = buildInterfaceDefinition("1"); - InterfaceDefinition interfaceDefinition2 = buildInterfaceDefinition("2"); - List interfaceDefinitions = new ArrayList<>(); - interfaceDefinitions.add(interfaceDefinition1); - interfaceDefinitions.add(interfaceDefinition2); - Either, StorageOperationStatus> res = - interfaceOperation.addInterfaces(component.getUniqueId(), interfaceDefinitions); - Assert.assertTrue(res.isLeft()); - Assert.assertEquals(2, res.left().value().size()); - } - - @Test - public void testUpdateInterface_Service() { - testUpdateInterface(service); - } - - private void testUpdateInterface(Component component) { - InterfaceDefinition interfaceDefinition = buildInterfaceDefinition("1"); - Either, StorageOperationStatus> res = interfaceOperation - .addInterfaces(component.getUniqueId(), - Collections.singletonList( - interfaceDefinition)); - Assert.assertTrue(res.isLeft()); - List value = res.left().value(); - InterfaceDefinition createdInterfaceDef = value.get(0); - String newDescription = "New Description"; - createdInterfaceDef.setDescription(newDescription); - res = interfaceOperation - .updateInterfaces(component.getUniqueId(), Collections.singletonList(createdInterfaceDef)); - assertTrue(res.isLeft()); - assertEquals(newDescription, res.left().value().get(0).getDescription()); - } - - @Test - public void testUpdateInterface_Resource() { - testUpdateInterface(resource); - } - - @Test - public void testDeleteInterface_Service() { - testDeleteInterface(service); - } - - private void testDeleteInterface(Component component) { - InterfaceDefinition interfaceDefinition = buildInterfaceDefinition("1"); - Either, StorageOperationStatus> res = interfaceOperation - .addInterfaces(component.getUniqueId(), - Collections.singletonList( - interfaceDefinition)); - Assert.assertTrue(res.isLeft()); - List value = res.left().value(); - Either deleteInterfaceOperationRes = - interfaceOperation.deleteInterface(component.getUniqueId(), value.get(0).getUniqueId()); - assertTrue(deleteInterfaceOperationRes.isLeft()); - } - - @Test - public void testDeleteInterface_Resource() { - testDeleteInterface(resource); - } - - @Test - public void testUpdateInterfaceShouldFailWhenNOtCreatedFirst() { - Component component = createResource(); - InterfaceDefinition interfaceDefinition = buildInterfaceDefinitionWithoutOperation(); - interfaceDefinition.setOperationsMap(createMockOperationMap()); - Either, StorageOperationStatus> res = interfaceOperation.updateInterfaces( - component.getUniqueId(), Collections.singletonList(interfaceDefinition)); - Assert.assertTrue(res.isRight()); - } - - private InterfaceDefinition buildInterfaceDefinitionWithoutOperation() { - InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); - interfaceDefinition.setType("tosca.interfaces.standard"); - return interfaceDefinition; - } - - private org.openecomp.sdc.be.model.Resource createResource() { - org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource(); - resource.setUniqueId(RESOURCE_ID); - resource.setName(RESOURCE_NAME); - resource.setDescription("My short description"); - resource.setInterfaces(createMockInterfaceDefinition()); - return resource; - } - - private Service createService() { - Service service = new Service(); - service.setUniqueId(SERVICE_ID); - service.setName(SERVICE_NAME); - service.setDescription("My short description"); - service.setInterfaces(createMockInterfaceDefinition()); - return service; - } - - private Map createMockInterfaceDefinition() { - Map operationMap = createMockOperationMap(); - Map interfaceDefinitionMap = new HashMap<>(); - interfaceDefinitionMap.put("int1", createInterface("int1", "Interface 1", "lifecycle", "tosca", operationMap)); - return interfaceDefinitionMap; - } - - private InterfaceDefinition createInterface(String uniqueId, String description, String type, - String toscaResourceName, Map op) { - InterfaceDefinition id = new InterfaceDefinition(); - id.setType(type); - id.setDescription(description); - id.setUniqueId(uniqueId); - id.setToscaResourceName(toscaResourceName); - id.setOperationsMap(op); - return id; - } - - @After - public void teardown() { - GraphTestUtils.clearGraph(titanDao); - } - -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationGraphTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationGraphTest.java deleted file mode 100644 index 1887891f2b..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationGraphTest.java +++ /dev/null @@ -1,244 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; -import fj.data.Either; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import javax.annotation.Resource; -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.io.IoCore; -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.config.TitanSpringConfig; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.HealingTitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {TitanSpringConfig.class, ModelOperationsSpringConfig.class}) -public class NodeTemplateOperationGraphTest extends ModelTestBase{ - @Resource - private HealingTitanDao titanDao; - @Resource - private NodeTemplateOperation nodeTemplateOperation; - - private TitanGraph graphT; - private GraphVertex containerVertex; - private String containeId; - - @BeforeClass - public static void setupBeforeClass() { - - ModelTestBase.init(); - } - @Before - public void before(){ - - Either graph = titanDao.getGraph(); - graphT = graph.left().value(); - - containerVertex = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); - containeId = "containerId"; - containerVertex.setUniqueId(containeId); - Either createVertex = titanDao.createVertex(containerVertex); - assertTrue(createVertex.isLeft()); - } - - @After - public void after(){ - titanDao.rollback(); - - } - - - String outputDirectory = "C:\\Output"; - - @Test - public void testCreateInstanceEdge(){ - - Map> mapOriginToInstId = new HashMap<>(); - createIntancesFromSameResource(mapOriginToInstId, 1, 3); - createIntancesFromSameResource(mapOriginToInstId, 2, 4); - createIntancesFromSameResource(mapOriginToInstId, 3, 1); - -// exportGraphMl(graphT); - - validateOnGraph(mapOriginToInstId, 3); - } - - @Test - public void testRemoveInstanceEdge(){ - //create 3 instances from same resource orig1 - Map> mapOriginToInstId = new HashMap<>(); - String originId = createIntancesFromSameResource(mapOriginToInstId, 1, 3); - validateOnGraph(mapOriginToInstId, 1); - - //remove instance 2 - String instanceId = removeInstanceEdge(containerVertex, originId, 1, 1); - mapOriginToInstId.get(originId).remove(instanceId); - validateOnGraph(mapOriginToInstId, 1); - - //create new instance from orig1 - instanceId = createInstanceEdge(containerVertex, originId, 1, 4, false, null); - mapOriginToInstId.get(originId).add(instanceId); - validateOnGraph(mapOriginToInstId, 1); - - //create 1 instance from same resource orig2 - originId = createIntancesFromSameResource(mapOriginToInstId, 2, 1); - validateOnGraph(mapOriginToInstId, 2); - - //remove instance of orig 2 - instanceId = removeInstanceEdge(containerVertex, originId, 2, 1); - mapOriginToInstId.get(originId).remove(instanceId); - validateOnGraph(mapOriginToInstId, 1); - - } - - @Test - public void testProxyInstanceEdge(){ - Map> mapOriginToInstId = new HashMap<>(); - String proxyId = createOrigin(2); - createIntancesFromSameResource(mapOriginToInstId, 1, 1, true, proxyId); - - validateOnGraph(mapOriginToInstId, 1); - } - private void validateOnGraph(Map> mapOriginToInstId, int expectedEdgeCount) { - validateOnGraph(mapOriginToInstId, expectedEdgeCount, false); - } - private void validateOnGraph(Map> mapOriginToInstId, int expectedEdgeCount, boolean validateProxy) { - Iterable vertices = graphT.query().has(GraphPropertyEnum.UNIQUE_ID.getProperty(), containeId).vertices(); - assertNotNull(vertices); - Iterator iterator = vertices.iterator(); - assertTrue(iterator.hasNext()); - Vertex containerV = iterator.next(); - validatePerEdgeType(mapOriginToInstId, expectedEdgeCount, containerV, EdgeLabelEnum.INSTANCE_OF); - if ( validateProxy ){ - validatePerEdgeType(mapOriginToInstId, expectedEdgeCount, containerV, EdgeLabelEnum.PROXY_OF); - } - } - private void validatePerEdgeType(Map> mapOriginToInstId, int expectedEdgeCount, Vertex containerV, EdgeLabelEnum edgeLabel) { - Iterator edges = containerV.edges(Direction.OUT, edgeLabel.name()); - assertNotNull(edges); - - int counter = 0; - while (edges.hasNext()){ - Edge edge = edges.next(); - counter++; - validateEdge(edge, mapOriginToInstId); - } - assertEquals("check edge size", expectedEdgeCount, counter); - } - - - private String createIntancesFromSameResource(Map> mapOriginToInstId, int originIndex, int countInstances) { - return createIntancesFromSameResource(mapOriginToInstId, originIndex, countInstances, false, null); - } - - private String createIntancesFromSameResource(Map> mapOriginToInstId, int originIndex, int countInstances, boolean isProxy, String proxyId) { - - List exp = new ArrayList(); - String originId = createOrigin(originIndex); - - for ( int i = 0; i < countInstances; i++){ - String instanceId = createInstanceEdge(containerVertex, originId, originIndex, i+1, isProxy, proxyId); - exp.add(instanceId); - } - mapOriginToInstId.put(originId, exp); - if ( isProxy ){ - mapOriginToInstId.put(proxyId, exp); - } - return originId; - } - - private String createInstanceEdge(GraphVertex containerVertex, String originId, int originIndex, int insIndex, boolean isProxy, String proxyId) { - ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(); - componentInstance.setComponentUid(originId); - String instanceId = buildInstanceId(originIndex, insIndex); - componentInstance.setUniqueId(instanceId); - componentInstance.setIsProxy(isProxy); - componentInstance.setSourceModelUid(proxyId); - StorageOperationStatus edgeStatus = nodeTemplateOperation.createInstanceEdge(containerVertex, componentInstance); - assertEquals("assertion createInstanceEdge", StorageOperationStatus.OK, edgeStatus); - return instanceId; - } - - private String buildInstanceId(int originIndex, int insIndex) { - StringBuffer sb = new StringBuffer("instanceId_"); - sb.append(originIndex).append("-").append(insIndex); - return sb.toString(); - } - private String removeInstanceEdge(GraphVertex containerVertex, String originId, int originIndex, int insIndex) { - ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(); - componentInstance.setComponentUid(originId); - String instanceId = buildInstanceId(originIndex, insIndex); - componentInstance.setUniqueId(instanceId); - StorageOperationStatus edgeStatus = nodeTemplateOperation.removeInstanceEdge(containerVertex, componentInstance); - assertEquals("assertion removeInstanceEdge", StorageOperationStatus.OK, edgeStatus); - return instanceId; - } - - - private String createOrigin(int index) { - Either createVertex; - GraphVertex originVertex = new GraphVertex(VertexTypeEnum.NODE_TYPE); - String originId = "originId_" + index; - originVertex.setUniqueId(originId); - createVertex = titanDao.createVertex(originVertex); - assertTrue(createVertex.isLeft()); - return originId; - } - private void validateEdge(Edge edge, Map> mapOriginToInstId) { - List expextedInList; - - Vertex originV = edge.inVertex(); - String id = (String) titanDao.getProperty((TitanVertex)originV, GraphPropertyEnum.UNIQUE_ID.getProperty()); - expextedInList = mapOriginToInstId.get(id); - - List list = (List) titanDao.getProperty(edge, EdgePropertyEnum.INSTANCES); - assertThat(list).hasSameSizeAs(expextedInList); - assertThat(list).containsOnlyElementsOf(expextedInList); - } - - private String exportGraphMl(TitanGraph graph) { - String result = null; - String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml"; - try { - try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) { - graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph); - } - result = outputFile; - } catch (Exception e) { - e.printStackTrace(); - } - return result; - - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationTest.java deleted file mode 100644 index bddebea630..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationTest.java +++ /dev/null @@ -1,364 +0,0 @@ -/* - - * Copyright (c) 2018 AT&T Intellectual Property. - - * - - * 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. - - */ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import com.google.common.collect.Lists; -import fj.data.Either; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.*; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class NodeTemplateOperationTest extends ModelTestBase { - - private final static String COMPONENT_ID = "componentId"; - private final static String TO_INSTANCE_ID = "toInstanceId"; - private final static String FROM_INSTANCE_ID = "fromInstanceId"; - private final static String RELATION_ID = "relationId"; - private final static String CAPABILITY_OWNER_ID = "capabilityOwnerId"; - private final static String CAPABILITY_UID = "capabilityUid"; - private final static String CAPABILITY_NAME = "capabilityName"; - private final static String REQUIREMENT_OWNER_ID = "requirementOwnerId"; - private final static String REQUIREMENT_UID = "requirementUid"; - private final static String REQUIREMENT_NAME = "requirementName"; - private final static String RELATIONSHIP_TYPE = "relationshipType"; - - private static Map fulfilledCapability; - private static Map fulfilledRequirement; - private static CapabilityDataDefinition capability; - private static RequirementDataDefinition requirement; - private static RequirementCapabilityRelDef relation; - - @InjectMocks - private static NodeTemplateOperation operation; - - @Mock - private static TitanDao titanDao; - - @Mock - private static TopologyTemplateOperation topologyTemplateOperation; - - @BeforeClass - public static void setup() { - init(); - titanDao = Mockito.mock(TitanDao.class); - operation = new NodeTemplateOperation(); - operation.setTitanDao(titanDao); - buildDataDefinition(); - } - - private static void buildDataDefinition() { - buildCapabiltyDataDefinition(); - buildRequirementDataDefinition(); - buildRelation(); - } - - @Test - public void testGetFulfilledCapabilityByRelationSuccess(){ - GraphVertex vertex = Mockito.mock(GraphVertex.class); - Either vertexRes = Either.left(vertex); - when(titanDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); - - GraphVertex dataVertex = new GraphVertex(); - dataVertex.setJson(fulfilledCapability); - Either childVertexRes = Either.left(dataVertex); - when(titanDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_CAPABILITIES), eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); - Either result = operation.getFulfilledCapabilityByRelation(COMPONENT_ID, TO_INSTANCE_ID, relation, this::isBelongingCapability); - assertTrue(result.isLeft()); - assertEquals(result.left().value(), capability); - } - - @Test - public void testGetFulfilledRequirementByRelationSuccess(){ - GraphVertex vertex = Mockito.mock(GraphVertex.class); - Either vertexRes = Either.left(vertex); - when(titanDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); - - GraphVertex dataVertex = new GraphVertex(); - dataVertex.setJson(fulfilledRequirement); - Either childVertexRes = Either.left(dataVertex); - when(titanDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_REQUIREMENTS), eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); - Either result = operation.getFulfilledRequirementByRelation(COMPONENT_ID, FROM_INSTANCE_ID, relation, this::isBelongingRequirement); - assertTrue(result.isLeft()); - assertEquals(result.left().value(), requirement); - } - - @Test - public void testGetFulfilledCapabilityByRelationNotFoundFailure(){ - GraphVertex vertex = Mockito.mock(GraphVertex.class); - Either vertexRes = Either.left(vertex); - when(titanDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); - - Either childVertexRes = Either.right(TitanOperationStatus.NOT_FOUND); - when(titanDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_CAPABILITIES), eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); - Either result = operation.getFulfilledCapabilityByRelation(COMPONENT_ID, TO_INSTANCE_ID, relation, this::isBelongingCapability); - assertTrue(result.isRight()); - assertSame(result.right().value(), StorageOperationStatus.NOT_FOUND); - } - - @Test - public void testGetFulfilledRequirementByRelationNotFoundFailure(){ - GraphVertex vertex = Mockito.mock(GraphVertex.class); - Either vertexRes = Either.left(vertex); - when(titanDao.getVertexById(eq(COMPONENT_ID), eq(JsonParseFlagEnum.ParseAll))).thenReturn(vertexRes); - - Either childVertexRes = Either.right(TitanOperationStatus.NOT_FOUND); - when(titanDao.getChildVertex(eq(vertex), eq(EdgeLabelEnum.FULLFILLED_REQUIREMENTS), eq(JsonParseFlagEnum.ParseJson))).thenReturn(childVertexRes); - Either result = operation.getFulfilledRequirementByRelation(COMPONENT_ID, FROM_INSTANCE_ID, relation, this::isBelongingRequirement); - assertTrue(result.isRight()); - assertSame(result.right().value(), StorageOperationStatus.NOT_FOUND); - } - - @Test - public void testUpdateCIMetadataOfTopologyTemplate() { - Either, StorageOperationStatus> result; - String id = "id"; - TopologyTemplate container = new TopologyTemplate(); - ToscaElement toscaElement = new TopologyTemplate(); - toscaElement.setResourceType(ResourceTypeEnum.VF); - ComponentInstance componentInstance = new ComponentInstance(); - componentInstance.setName(id); - componentInstance.setComponentUid(id); - container.setUniqueId(id); - GraphVertex graphVertex = new GraphVertex(); - when(titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(graphVertex)); - when(titanDao.updateVertex(graphVertex)).thenReturn(Either.left(graphVertex)); - when(topologyTemplateOperation.getToscaElement(anyString())).thenReturn(Either.left(toscaElement)); - - result = operation.updateComponentInstanceMetadataOfTopologyTemplate(container, toscaElement, componentInstance); - assertTrue(result.isLeft()); - } - - @Test - public void testGetDefaultHeatTimeout() { - Integer result; - - // default test - result = NodeTemplateOperation.getDefaultHeatTimeout(); - } - - @Test - public void testPrepareInstDeploymentArtifactPerInstance() { - Map deploymentResourceArtifacts = new HashMap<>(); - Map deploymentArtifacts = new HashMap<>(); - ArtifactDataDefinition artifactDataDefinition = new ArtifactDataDefinition(); - artifactDataDefinition.setArtifactType("HEAT"); - artifactDataDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - deploymentArtifacts.put("1", artifactDataDefinition); - deploymentResourceArtifacts.put("1", artifactDataDefinition); - String componentInstanceId = "componentInstanceId"; - User user = new User(); - user.setUserId("userId"); - user.setFirstName("first"); - user.setLastName("last"); - String envType = "VfHeatEnv"; - MapArtifactDataDefinition result; - - result = operation.prepareInstDeploymentArtifactPerInstance(deploymentArtifacts, componentInstanceId, user, - envType); - Assert.assertEquals(2, result.getMapToscaDataDefinition().size()); - } - - @Test - public void testCreateCapPropertyKey() throws Exception { - String key = ""; - String instanceId = ""; - String result; - - // default test - result = NodeTemplateOperation.createCapPropertyKey(key, instanceId); - } - - @Test - public void testPrepareCalculatedCapabiltyForNodeType() { - Map capabilities = new HashMap<>(); - ListCapabilityDataDefinition listCapDataDefinition = new ListCapabilityDataDefinition(); - List listToscaDataDefinition = new ArrayList<>(); - CapabilityDataDefinition capabilityDataDefinition = new CapabilityDefinition(); - capabilityDataDefinition.setMaxOccurrences("1"); - listToscaDataDefinition.add(capabilityDataDefinition); - listCapDataDefinition.setListToscaDataDefinition(listToscaDataDefinition); - capabilities.put("1", listCapDataDefinition); - ComponentInstance componentInstance = createCompInstance(); - MapListCapabilityDataDefinition result; - - result = operation.prepareCalculatedCapabiltyForNodeType(capabilities, componentInstance); - Assert.assertEquals(1, result.getMapToscaDataDefinition().size()); - } - - @Test - public void testPrepareCalculatedReqForNodeType() { - Map requirements = new HashMap<>(); - ListRequirementDataDefinition listReqDataDef = new ListRequirementDataDefinition(); - List listToscaDataDefinition = new ArrayList<>(); - RequirementDataDefinition reqDataDefinition = new RequirementDataDefinition(); - reqDataDefinition.setMaxOccurrences("1"); - listToscaDataDefinition.add(reqDataDefinition); - listReqDataDef.setListToscaDataDefinition(listToscaDataDefinition); - requirements.put("1", listReqDataDef); - ComponentInstance componentInstance = createCompInstance(); - MapListRequirementDataDefinition result; - - result = operation.prepareCalculatedRequirementForNodeType(requirements, componentInstance); - Assert.assertEquals(1, result.getMapToscaDataDefinition().size()); - } - - @Test - public void testAddGroupInstancesToComponentInstance() throws Exception { - Component containerComponent = null; - ComponentInstanceDataDefinition componentInstance = null; - List groups = null; - Map> groupInstancesArtifacts = null; - StorageOperationStatus result; - - result = operation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, - groupInstancesArtifacts); - Assert.assertEquals(StorageOperationStatus.OK, result); - } - - @Test - public void testGenerateCustomizationUUIDOnInstanceGroup() throws Exception { - String componentId = ""; - String instanceId = ""; - List groupInstances = null; - StorageOperationStatus result; - - result = operation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances); - Assert.assertEquals(StorageOperationStatus.OK, result); - } - - private ComponentInstance createCompInstance() { - ComponentInstance componentInstance = new ComponentInstance(); - String id = "id"; - componentInstance.setComponentUid(id); - componentInstance.setUniqueId(id); - componentInstance.setName(id); - return componentInstance; - } - private static void buildRequirementDataDefinition() { - buildRequirement(); - fulfilledRequirement = new HashMap<>(); - MapListRequirementDataDefinition mapListRequirementDataDefinition = new MapListRequirementDataDefinition(); - mapListRequirementDataDefinition.add(requirement.getCapability(), requirement); - fulfilledRequirement.put(FROM_INSTANCE_ID, mapListRequirementDataDefinition); - - } - - private static void buildRequirement() { - requirement = new RequirementDataDefinition(); - requirement.setOwnerId(REQUIREMENT_OWNER_ID); - requirement.setUniqueId(REQUIREMENT_UID); - requirement.setName(REQUIREMENT_NAME); - requirement.setRelationship(RELATIONSHIP_TYPE); - } - - private static void buildCapabiltyDataDefinition() { - buildCapability(); - fulfilledCapability = new HashMap<>(); - MapListCapabilityDataDefinition mapListCapabiltyDataDefinition = new MapListCapabilityDataDefinition(); - mapListCapabiltyDataDefinition.add(capability.getType(), capability); - fulfilledCapability.put(TO_INSTANCE_ID, mapListCapabiltyDataDefinition); - } - - private static void buildCapability() { - capability = new CapabilityDataDefinition(); - capability.setOwnerId(CAPABILITY_OWNER_ID); - capability.setUniqueId(CAPABILITY_UID); - capability.setName(CAPABILITY_NAME); - } - - private static void buildRelation() { - - relation = new RequirementCapabilityRelDef(); - CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship(); - RelationshipInfo relationInfo = new RelationshipInfo(); - relationInfo.setId(RELATION_ID); - relationship.setRelation(relationInfo); - - relation.setRelationships(Lists.newArrayList(relationship)); - relation.setToNode(TO_INSTANCE_ID); - relation.setFromNode(FROM_INSTANCE_ID); - - relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID); - relationInfo.setCapabilityUid(CAPABILITY_UID); - relationInfo.setCapability(CAPABILITY_NAME); - relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID); - relationInfo.setRequirementUid(REQUIREMENT_UID); - relationInfo.setRequirement(REQUIREMENT_NAME); - RelationshipImpl relationshipImpl = new RelationshipImpl(); - relationshipImpl.setType(RELATIONSHIP_TYPE); - relationInfo.setRelationships(relationshipImpl); - } - - private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) { - return req.getRelationship().equals(relationshipInfo.getRelationship().getType()) && - req.getName().equals(relationshipInfo.getRequirement()) && - req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && - req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId()); - } - - private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) { - return cap.getName().equals(relationshipInfo.getCapability()) && - cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && - cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId()); - } - -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationIntegrationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationIntegrationTest.java deleted file mode 100644 index ca8713fdf3..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationIntegrationTest.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -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.config.TitanSpringConfig; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.HealingTitanDao; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.PolicyDefinition; -import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import javax.annotation.Resource; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import static org.apache.commons.collections.ListUtils.union; -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {TitanSpringConfig.class, ModelOperationsSpringConfig.class}) -public class PolicyOperationIntegrationTest extends ModelTestBase { - - private static final String CONTAINER_ID = "container"; - public static final String POLICY_ID = "policy"; - @Resource - private TopologyTemplateOperation topologyTemplateOperation; - @Resource - private HealingTitanDao titanDao; - @Resource - private PolicyOperation policyOperation; - private PropertyDataDefinition prop1, prop2; - private PolicyDefinition policy; - - @BeforeClass - public static void setupBeforeClass() { - - ModelTestBase.init(); - } - - @Before - public void setUp() throws Exception { - prop1 = new PropertyDataDefinition(); - prop1.setUniqueId("prop1"); - prop1.setName("prop1"); - prop1.setValue("prop1"); - - prop2 = new PropertyDataDefinition(); - prop2.setUniqueId("prop2"); - prop2.setName("prop2"); - prop2.setValue("prop2"); - - policy = new PolicyDefinition(); - policy.setUniqueId(POLICY_ID); - - policy.setProperties(Arrays.asList(prop1, prop2)); - - GraphVertex resource = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); - resource.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, CONTAINER_ID); - titanDao.createVertex(resource); - GraphVertex loadedResource = titanDao.getVertexById(CONTAINER_ID).left().value(); - topologyTemplateOperation.addToscaDataToToscaElement(loadedResource, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policy, JsonPresentationFields.UNIQUE_ID); -// titanDao.commit(); - } - - @After - public void tearDown() { - titanDao.rollback(); - } - - @Test - public void testUpdatePolicyProperties_singleProperty() { - PropertyDataDefinition prop1Copy = new PropertyDataDefinition(prop1); - prop1Copy.setValue("prop1NewValue"); - testUpdatePolicyProperties(Collections.singletonList(prop1Copy), Collections.singletonList(prop2)); - } - - @Test - public void testUpdatePolicyProperties_multipleProperties() { - PropertyDataDefinition prop1Copy = new PropertyDataDefinition(prop1); - prop1Copy.setValue("prop1NewValue"); - - PropertyDataDefinition prop2Copy = new PropertyDataDefinition(prop2); - prop2Copy.setValue("prop2NewValue"); - - testUpdatePolicyProperties(Arrays.asList(prop1Copy, prop2Copy), Collections.emptyList()); - } - - private void testUpdatePolicyProperties(List updatedProperties, List nonUpdatedPropeties) { - Component cmpt = new org.openecomp.sdc.be.model.Resource(); - cmpt.setUniqueId(CONTAINER_ID); - cmpt.setPolicies(Collections.singletonMap(POLICY_ID, policy)); - StorageOperationStatus storageOperationStatus = policyOperation.updatePolicyProperties(cmpt, POLICY_ID, updatedProperties); - assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnorePolicies(false); - Either loadedCmptEither = topologyTemplateOperation.getToscaElement(CONTAINER_ID, componentParametersView); - - assertThat(loadedCmptEither.isLeft()).isTrue(); - ToscaElement loadedCmpt = loadedCmptEither.left().value(); - assertThat(loadedCmpt).isInstanceOf(TopologyTemplate.class); - @SuppressWarnings("unchecked") List allProperties = union(updatedProperties, nonUpdatedPropeties); - verifyPolicyPropertiesValuesUpdated((TopologyTemplate) loadedCmpt, allProperties); - } - - private void verifyPolicyPropertiesValuesUpdated(TopologyTemplate toscaElement, List expectedUpdatedProperties) { - Map policies = toscaElement.getPolicies(); - PolicyDataDefinition policy = policies.get(POLICY_ID); - List policyProperties = policy.getProperties(); - assertThat(policyProperties).usingElementComparatorOnFields("value") - .containsAll(expectedUpdatedProperties); - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationTest.java deleted file mode 100644 index 136f95b987..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.PolicyDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; - -import java.util.Arrays; -import java.util.Collections; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class PolicyOperationTest { - - private static final String CONTAINER_ID = "containerId"; - private static final String POLICY_ID = "policyId"; - @InjectMocks - private PolicyOperation testInstance; - @Mock - private TitanDao titanDao; - @Mock - private TopologyTemplateOperation topologyTemplateOperation; - @Captor - private ArgumentCaptor policyDefCaptor; - private Component component; - private PolicyDefinition policyDefinition; - private PropertyDataDefinition prop1, prop2; - - @Before - public void setUp() throws Exception { - component = new Resource(); - component.setUniqueId(CONTAINER_ID); - policyDefinition = new PolicyDefinition(); - policyDefinition.setUniqueId(POLICY_ID); - prop1 = new PropertyDataDefinition(); - prop1.setName("prop1"); - prop1.setValue("prop1"); - - prop2 = new PropertyDataDefinition(); - prop2.setName("prop2"); - prop2.setValue("prop2"); - policyDefinition.setProperties(Arrays.asList(prop1, prop2)); - component.setPolicies(Collections.singletonMap(POLICY_ID, policyDefinition)); - } - - @Test - public void updatePolicyProperties_failedToFetchContainer() { - when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); - StorageOperationStatus storageOperationStatus = testInstance.updatePolicyProperties(component, POLICY_ID, Collections.emptyList()); - assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.NOT_FOUND); - verifyZeroInteractions(topologyTemplateOperation); - } - - @Test - public void updatePolicyProperties_updateFailed() { - GraphVertex cmptVertex = new GraphVertex(); - when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(cmptVertex)); - when(topologyTemplateOperation.updatePolicyOfToscaElement(cmptVertex, policyDefinition)).thenReturn(StorageOperationStatus.GENERAL_ERROR); - StorageOperationStatus storageOperationStatus = testInstance.updatePolicyProperties(component, POLICY_ID, Collections.emptyList()); - assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.GENERAL_ERROR); - } - - @Test - public void updatePolicyProperties() { - GraphVertex cmptVertex = new GraphVertex(); - when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(cmptVertex)); - when(topologyTemplateOperation.updatePolicyOfToscaElement(eq(cmptVertex), policyDefCaptor.capture())).thenReturn(StorageOperationStatus.OK); - PropertyDataDefinition prop1Copy = new PropertyDataDefinition(prop1); - prop1Copy.setValue("prop1Copy"); - StorageOperationStatus storageOperationStatus = testInstance.updatePolicyProperties(component, POLICY_ID, Collections.singletonList(prop1Copy)); - assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); - assertThat(policyDefCaptor.getValue().getProperties()).usingElementComparatorOnFields("value") - .containsExactlyInAnyOrder(prop1Copy, prop2); - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationCapabilityIntegrationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationCapabilityIntegrationTest.java deleted file mode 100644 index 9936d45f62..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationCapabilityIntegrationTest.java +++ /dev/null @@ -1,198 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -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.config.TitanSpringConfig; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.HealingTitanDao; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import javax.annotation.Resource; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {TitanSpringConfig.class, ModelOperationsSpringConfig.class}) -public class TopologyTemplateOperationCapabilityIntegrationTest extends ModelTestBase { - - private static final String CONTAINER_ID = "id"; - private Map capabilitiesPropsMap; - private List capabilitiesProperties; - - @Resource - private TopologyTemplateOperation topologyTemplateOperation; - - @Resource - private HealingTitanDao titanDao; - private CapabilityPropertyDataObject capabilityProperty1; - private CapabilityPropertyDataObject capabilityProperty2; - private CapabilityPropertyDataObject capabilityProperty3; - - @BeforeClass - public static void setupBeforeClass() { - - ModelTestBase.init(); - } - - @Before - public void setUp() throws Exception { - - capabilitiesPropsMap = new HashMap<>(); - capabilityProperty1 = new CapabilityPropertyDataObject("instance1", "capability1", "prop1", "val1"); - capabilityProperty2 = new CapabilityPropertyDataObject("instance1", "capability2", "prop2", "val2"); - capabilityProperty3 = new CapabilityPropertyDataObject("instance2", "capability3", "prop3", "val3"); - capabilitiesProperties = Arrays.asList(capabilityProperty1, capabilityProperty2, capabilityProperty3); - - - //capablities props == Map>> - capabilitiesProperties.forEach(capabilitiesProperty -> { - capabilitiesPropsMap.computeIfAbsent(capabilitiesProperty.getInstanceId(), k -> new MapCapabilityProperty(new HashMap<>())) - .getMapToscaDataDefinition().computeIfAbsent(capabilitiesProperty.getCapabilityId(), k -> new MapPropertiesDataDefinition(new HashMap<>())) - .getMapToscaDataDefinition().computeIfAbsent(capabilitiesProperty.getPropName(), k -> new PropertyDefinition(createPropWithValue(capabilitiesProperty.getPropValue()))); - }); - - GraphVertex resource = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); - resource.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, CONTAINER_ID); - titanDao.createVertex(resource); - GraphVertex loadedResource = titanDao.getVertexById(CONTAINER_ID).left().value(); - topologyTemplateOperation.associateElementToData(loadedResource, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilitiesPropsMap).left().value(); - } - - @After - public void tearDown() { - titanDao.rollback(); - } - - @Test - public void overrideCalculatedCapabilityProperties() { - Map loadedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID); - compareCapabilitiesProperties(capabilitiesProperties, loadedCapPropsMap); - capabilityProperty1.setPropValue("newVal1"); - capabilityProperty3.setPropValue("newVal3"); - setPropertyValue(capabilitiesPropsMap, capabilityProperty1); - setPropertyValue(capabilitiesPropsMap, capabilityProperty3); - StorageOperationStatus storageOperationStatus = topologyTemplateOperation.overrideToscaDataOfToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilitiesPropsMap); - assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); - Map updatedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID); - compareCapabilitiesProperties(capabilitiesProperties, updatedCapPropsMap); - } - - @Test - public void updateToscaDataDeepElementsBlockToToscaElement() { - assertCapabilityPropValue(capabilityProperty1, "val1"); - assertCapabilityPropValue(capabilityProperty2, "val2"); - assertCapabilityPropValue(capabilityProperty3, "val3"); - - MapCapabilityProperty instance1Props = capabilitiesPropsMap.get("instance1"); - capabilityProperty1.setPropValue("newVal1"); - setPropertyValue(capabilitiesPropsMap, capabilityProperty1); - - capabilityProperty3.setPropValue("newVal3"); - setPropertyValue(capabilitiesPropsMap, capabilityProperty3); - - Component component = new org.openecomp.sdc.be.model.Resource(); - component.setUniqueId(CONTAINER_ID); - StorageOperationStatus updateStatus = topologyTemplateOperation.updateToscaDataDeepElementsBlockToToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, instance1Props, "instance1"); - - assertThat(updateStatus).isEqualTo(StorageOperationStatus.OK); - assertCapabilityPropValue(capabilityProperty1, "newVal1"); - assertCapabilityPropValue(capabilityProperty2, "val2"); - assertCapabilityPropValue(capabilityProperty3, "val3");//only instance1 props should be updated - } - - private Map fetchCapabilitiesProps(String containerId) { - ComponentParametersView capabilityPropsFilter = new ComponentParametersView(true); - capabilityPropsFilter.setIgnoreCapabiltyProperties(false); - return ((TopologyTemplate) topologyTemplateOperation.getToscaElement(containerId, capabilityPropsFilter).left().value()).getCalculatedCapabilitiesProperties(); - } - - private void compareCapabilitiesProperties(List expected, Map actual) { - expected.forEach(expectedCapabilityProp -> { - assertThat(getPropertyValue(actual, expectedCapabilityProp.instanceId, expectedCapabilityProp.capabilityId, expectedCapabilityProp.propName)) - .isEqualTo(expectedCapabilityProp.propValue); - }); - } - - private String getPropertyValue(Map capabilityPropertyMap, String instance, String capability, String prop) { - return capabilityPropertyMap.get(instance).getMapToscaDataDefinition().get(capability).getMapToscaDataDefinition().get(prop).getValue(); - } - - private void setPropertyValue(Map capabilityPropertyMap, CapabilityPropertyDataObject capabilityProperty) { - setPropertyValue(capabilityPropertyMap.get(capabilityProperty.getInstanceId()), capabilityProperty); - - } - - private void setPropertyValue(MapCapabilityProperty capabilitiesInstanceProperties, CapabilityPropertyDataObject capabilityProperty) { - capabilitiesInstanceProperties.getMapToscaDataDefinition().get(capabilityProperty.getCapabilityId()) - .getMapToscaDataDefinition().get(capabilityProperty.getPropName()) - .setValue(capabilityProperty.getPropValue()); - } - - private void assertCapabilityPropValue(CapabilityPropertyDataObject prop, String expectedValue) { - Map loadedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID); - String propertyValue = getPropertyValue(loadedCapPropsMap, prop.getInstanceId(), prop.getCapabilityId(), prop.getPropName()); - assertThat(propertyValue).isEqualTo(expectedValue); - } - - - private PropertyDefinition createPropWithValue(String val) { - PropertyDefinition propertyDefinition = new PropertyDefinition(); - propertyDefinition.setValue(val); - return propertyDefinition; - } - - private static class CapabilityPropertyDataObject { - private String instanceId; - private String capabilityId; - private String propName; - private String propValue; - - CapabilityPropertyDataObject(String instanceId, String capabilityId, String propName, String propValue) { - this.instanceId = instanceId; - this.capabilityId = capabilityId; - this.propName = propName; - this.propValue = propValue; - } - - String getInstanceId() { - return instanceId; - } - - String getCapabilityId() { - return capabilityId; - } - - String getPropName() { - return propName; - } - - String getPropValue() { - return propValue; - } - - void setPropValue(String propValue) { - this.propValue = propValue; - } - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationTest.java deleted file mode 100644 index 4ace70b34f..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationTest.java +++ /dev/null @@ -1,177 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import com.thinkaurelius.titan.core.TitanVertex; -import fj.data.Either; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; -import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.model.DistributionStatusEnum; -import org.openecomp.sdc.be.model.PolicyDefinition; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; - -import java.util.*; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -//error scenarios -public class TopologyTemplateOperationTest { - - private static final String CONTAINER_ID = "containerId"; - @InjectMocks - private TopologyTemplateOperation topologyTemplateOperation; - @Mock - private TitanDao titanDao; - - @Test - public void overrideToscaDataOfToscaElement_failedToFetchContainerVertex() { - when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(TitanOperationStatus.INVALID_ID)); - StorageOperationStatus storageOperationStatus = topologyTemplateOperation.overrideToscaDataOfToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, Collections.emptyMap()); - assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.INVALID_ID); - } - - @Test - public void overrideToscaDataOfToscaElement_failedToFetchDataVertex() { - GraphVertex containerVertex = new GraphVertex(); - when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(containerVertex)); - when(titanDao.getChildVertex(containerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, JsonParseFlagEnum.ParseJson)).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); - StorageOperationStatus storageOperationStatus = topologyTemplateOperation.overrideToscaDataOfToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, Collections.emptyMap()); - assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.NOT_FOUND); - } - - @Test - public void updateToscaDataDeepElements_failedToFetchContainerVertex() { - when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(TitanOperationStatus.INVALID_ID)); - StorageOperationStatus storageOperationStatus = topologyTemplateOperation.updateToscaDataDeepElementsBlockToToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, new MapCapabilityProperty(), ""); - assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.INVALID_ID); - } - - @Test - public void updateToscaDataDeepElements_failedToFetchDataVertex() { - GraphVertex containerVertex = new GraphVertex(); - when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(containerVertex)); - when(titanDao.getChildVertex(containerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, JsonParseFlagEnum.ParseJson)).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); - StorageOperationStatus storageOperationStatus = topologyTemplateOperation.updateToscaDataDeepElementsBlockToToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, new MapCapabilityProperty(), ""); - assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.NOT_FOUND); - } - - @Test - public void addPolicyToToscaElementSuccessTest(){ - TitanOperationStatus status = TitanOperationStatus.OK; - StorageOperationStatus result = addPolicyToToscaElementWithStatus(status); - assertThat(result).isEqualTo(StorageOperationStatus.OK); - } - - @Test - public void addPolicyToToscaElementFailureTest(){ - TitanOperationStatus status = TitanOperationStatus.ALREADY_EXIST; - StorageOperationStatus result = addPolicyToToscaElementWithStatus(status); - assertThat(result).isEqualTo(StorageOperationStatus.ENTITY_ALREADY_EXISTS); - } - - @Test - public void testAssociateOrAddCalcCapReqToComponent() { - StorageOperationStatus result; - GraphVertex graphVertex = new GraphVertex(); - Map calcRequirements = new HashMap<>(); - Map calcCapabilty = new HashMap<>(); - Map calCapabilitiesProps = new HashMap<>(); - addPolicyToToscaElementWithStatus(TitanOperationStatus.OK); - result = topologyTemplateOperation.associateOrAddCalcCapReqToComponent(graphVertex, calcRequirements, calcCapabilty, calCapabilitiesProps); - assertEquals(StorageOperationStatus.OK, result); - } - - @Test - public void testSetDataTypesFromGraph() { - GraphVertex containerVertex = new GraphVertex(); - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreComponentInstancesInterfaces(true); - filter.setIgnoreDataType(false); - String componentName = "componentName"; - String componentId = UniqueIdBuilder.buildResourceUniqueId(); - containerVertex.setVertex(Mockito.mock(TitanVertex.class)); - containerVertex.setJsonMetadataField(JsonPresentationFields.NAME, componentName); - containerVertex.setUniqueId(componentId); - containerVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); - when(titanDao.getChildVertex(any(GraphVertex.class), any(EdgeLabelEnum.class), any(JsonParseFlagEnum.class))).thenReturn(Either.right(TitanOperationStatus.GENERAL_ERROR)); - Either storageOperationStatus = topologyTemplateOperation.getToscaElement(containerVertex, filter); - assertThat(storageOperationStatus).isEqualTo(Either.right(StorageOperationStatus.GENERAL_ERROR)); - } - - @Test - public void testUpdateDistributionStatus() { - Either result; - String uniqueId = "uniqueId"; - User user = new User(); - String userId = "userId"; - user.setUserId(userId); - Iterator edgeIterator = new Iterator() { - @Override - public boolean hasNext() { - return false; - } - - @Override - public Edge next() { - return null; - } - }; - GraphVertex graphVertex = Mockito.mock(GraphVertex.class); - TitanVertex titanVertex = Mockito.mock(TitanVertex.class); - when(graphVertex.getVertex()).thenReturn(titanVertex); - when(titanVertex.edges(Direction.IN, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER.name())).thenReturn(edgeIterator); - when(titanDao.getVertexByPropertyAndLabel(GraphPropertyEnum.USERID, userId, VertexTypeEnum.USER, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex)); - when(titanDao.getVertexById(uniqueId, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(graphVertex)); - when(titanDao.createEdge(graphVertex, graphVertex, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER, null)).thenReturn(TitanOperationStatus.OK); - when(titanDao.updateVertex(graphVertex)).thenReturn(Either.left(graphVertex)); - result = topologyTemplateOperation.updateDistributionStatus(uniqueId, user, DistributionStatusEnum.DISTRIBUTED); - assertThat(result.isLeft()); - } - - @SuppressWarnings("unchecked") - private StorageOperationStatus addPolicyToToscaElementWithStatus(TitanOperationStatus status) { - GraphVertex componentV = new GraphVertex(); - componentV.setVertex(Mockito.mock(TitanVertex.class)); - GraphVertex dataV = new GraphVertex(); - dataV.setVertex(Mockito.mock(TitanVertex.class)); - String componentName = "componentName"; - String componentId = UniqueIdBuilder.buildResourceUniqueId(); - String policyTypeName = "org.openecomp.policies.placement.valet.Affinity"; - componentV.setJsonMetadataField(JsonPresentationFields.NAME, componentName); - componentV.setUniqueId(componentId); - PolicyDefinition policy = new PolicyDefinition(); - policy.setPolicyTypeName(policyTypeName); - int counter = 0; - Either toscaDataVertexRes = Either.right(TitanOperationStatus.NOT_FOUND); - when(titanDao.getChildVertex(eq(componentV), eq(EdgeLabelEnum.POLICIES), eq(JsonParseFlagEnum.ParseJson))).thenReturn(toscaDataVertexRes); - Either createVertex = Either.left(dataV); - when(titanDao.createVertex(any(GraphVertex.class))).thenReturn(createVertex); - when(titanDao.createEdge(any(TitanVertex.class), any(TitanVertex.class), any(EdgeLabelEnum.class), any(HashMap.class))).thenReturn(status); - return topologyTemplateOperation.addPolicyToToscaElement(componentV, policy, counter); - } - -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationCatalogTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationCatalogTest.java deleted file mode 100644 index bffefd86cd..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationCatalogTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.model.catalog.CatalogComponent; - -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; - -@RunWith(MockitoJUnitRunner.class) -public class ToscaElementOperationCatalogTest { - - private ArrayList vertexList = new ArrayList<>(); - - @Mock - Vertex vertex; - @Mock - TitanDao titanDao; - @Mock - VertexProperty property; - - @InjectMocks - private ToscaElementOperation toscaOperation = new TopologyTemplateOperation(); - - @Before - public void setUp() { - vertexList.add(vertex); - when(titanDao.getCatalogOrArchiveVerticies(true)).thenReturn(Either.left(vertexList.iterator())); - when(titanDao.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse)) - .thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); - when(vertex.property(GraphPropertiesDictionary.METADATA.getProperty())).thenReturn(property); - } - - @Test - public void getComponentFromCatalogWhenDeleteIsTrue() { - final String vertexJsonIsDeletedTrue = "{\"lifecycleState\":\"CERTIFIED\",\"componentType\":\"RESOURCE\",\"vendorRelease\":\"1\",\"contactId\":\"ah7840\",\"lastUpdateDate\":1496119811038,\"icon\":\"att\",\"description\":\"Cloud\",\"creationDate\":1459432094781,\"vendorName\":\"AT&T\",\"mandatory\":false,\"version\":\"1.0\",\"tags\":[\"Cloud\"],\"highestVersion\":true,\"systemName\":\"Cloud\",\"name\":\"Cloud\",\"isDeleted\":true,\"invariantUuid\":\"ab5263fd-115c-41f2-8d0c-8b9279bce2b2\",\"UUID\":\"208cf7df-68a1-4ae7-afc9-409ea8012332\",\"normalizedName\":\"cloud\",\"toscaResourceName\":\"org.openecomp.resource.Endpoint.Cloud\",\"uniqueId\":\"9674e7e1-bc1a-41fe-b503-fbe996801475\",\"resourceType\":\"VFC\"}"; - when(property.value()).thenReturn(vertexJsonIsDeletedTrue); - List componentList = toscaOperation.getElementCatalogData(true, null).left().value(); - assertTrue(componentList.isEmpty()); - } - - @Test - public void getComponentFromCatalogWhenDeleteNotFound() { - final String vertexJsonIsDeletedNotFound = "{\"lifecycleState\":\"CERTIFIED\",\"componentType\":\"RESOURCE\",\"vendorRelease\":\"1\",\"contactId\":\"ah7840\",\"lastUpdateDate\":1496119811038,\"icon\":\"att\",\"description\":\"Cloud\",\"creationDate\":1459432094781,\"vendorName\":\"AT&T\",\"mandatory\":false,\"version\":\"1.0\",\"tags\":[\"Cloud\"],\"highestVersion\":true,\"systemName\":\"Cloud\",\"name\":\"Cloud\",\"invariantUuid\":\"ab5263fd-115c-41f2-8d0c-8b9279bce2b2\",\"UUID\":\"208cf7df-68a1-4ae7-afc9-409ea8012332\",\"normalizedName\":\"cloud\",\"toscaResourceName\":\"org.openecomp.resource.Endpoint.Cloud\",\"uniqueId\":\"9674e7e1-bc1a-41fe-b503-fbe996801475\",\"resourceType\":\"VFC\"}"; - when(property.value()).thenReturn(vertexJsonIsDeletedNotFound); - List componentList = toscaOperation.getElementCatalogData(true, null).left().value(); - assertEquals(1, componentList.size()); - } - - @Test - public void getComponentFromCatalogWhenDeleteIsFalse() { - final String vertexJsonIsDeletedFalse = "{\"lifecycleState\":\"CERTIFIED\",\"componentType\":\"RESOURCE\",\"vendorRelease\":\"1\",\"contactId\":\"ah7840\",\"lastUpdateDate\":1496119811038,\"icon\":\"att\",\"description\":\"Cloud\",\"creationDate\":1459432094781,\"vendorName\":\"AT&T\",\"mandatory\":false,\"version\":\"1.0\",\"tags\":[\"Cloud\"],\"highestVersion\":true,\"systemName\":\"Cloud\",\"name\":\"Cloud\",\"isDeleted\":false,\"invariantUuid\":\"ab5263fd-115c-41f2-8d0c-8b9279bce2b2\",\"UUID\":\"208cf7df-68a1-4ae7-afc9-409ea8012332\",\"normalizedName\":\"cloud\",\"toscaResourceName\":\"org.openecomp.resource.Endpoint.Cloud\",\"uniqueId\":\"9674e7e1-bc1a-41fe-b503-fbe996801475\",\"resourceType\":\"VFC\"}"; - when(property.value()).thenReturn(vertexJsonIsDeletedFalse); - List componentList = toscaOperation.getElementCatalogData(true, null).left().value(); - assertEquals(1, componentList.size()); - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java deleted file mode 100644 index e77f8e108c..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java +++ /dev/null @@ -1,363 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; -import org.junit.runner.RunWith; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.utils.GraphTestUtils; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import java.util.*; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * Created by chaya on 6/12/2017. - */ - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:application-context-test.xml") -public class ToscaElementOperationTest extends ModelTestBase{ - - private List allVertices = new ArrayList<>(); - private boolean isInitialized = false; - - @javax.annotation.Resource - private ToscaElementOperationTestImpl toscaElementOperation; - - @javax.annotation.Resource - private TitanDao titanDao; - - @BeforeClass - public static void initTest(){ - ModelTestBase.init(); - - } - - @Rule - public TestName testName = new TestName(); - - @Before - public void beforeTest() { - if (!isInitialized) { - GraphTestUtils.clearGraph(titanDao); - //exportGraphMl(titanDao.getGraph().left().value(),""); - initGraphForTest(); - isInitialized = true; - } - } - - - @Test - public void testGetAllHighestResourcesNoFilter() { - - Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, null, true); - assertTrue(highestResourcesRes.isLeft()); - List highestResources = highestResourcesRes.left().value(); - // calculate expected count value - long highestResourcesExpectedCount = calculateCount(new HashMap() { - { - put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - } - }, null); - assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); - } - - - - - @Test - public void testGetAllResourcesCertifiedNoFilter() { - Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, null, false); - assertTrue(highestResourcesRes.isLeft()); - List highestResources = highestResourcesRes.left().value(); - // calculate expected count value - long highestResourcesExpectedCount = calculateCount(new HashMap() { - { - put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - } - }, null); - highestResourcesExpectedCount += calculateCount(new HashMap() { - { - put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - } - }, new HashMap() { - { - put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - } - }); - assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); - } - - @Test - public void testGetHighestResourcesExclude() { - - // exclude VFCMT - List excludeList = Arrays.asList(ResourceTypeEnum.VFCMT); - assertTrue(genericTestGetResourcesWithExcludeList(excludeList)); - - // exclude CP & VL - excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP); - assertTrue(genericTestGetResourcesWithExcludeList(excludeList)); - - // exclude CP & VL & VF & VFC - excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP, ResourceTypeEnum.VF, ResourceTypeEnum.VFC); - assertTrue(genericTestGetResourcesWithExcludeList(excludeList)); - } - - @Test - public void testGetAllResourcesCertifiedExclude() { - // exclude VFCMT - List excludeList = Arrays.asList(ResourceTypeEnum.VFCMT); - assertTrue(genericTestGetCertifiedResourcesWithExcludeList(excludeList)); - - // exclude CP & VL - excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP); - assertTrue(genericTestGetCertifiedResourcesWithExcludeList(excludeList)); - - // exclude CP & VL & VF & VFC - excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP, ResourceTypeEnum.VF, ResourceTypeEnum.VFC); - assertTrue(genericTestGetCertifiedResourcesWithExcludeList(excludeList)); - } - - @Test - public void testGetAllHighestServicesNoFilter() { - Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, true); - assertTrue(highestResourcesRes.isLeft()); - List highestResources = highestResourcesRes.left().value(); - // calculate expected count value - long highestResourcesExpectedCount = calculateCount(new HashMap() { - { - put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - } - }, null); - assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); - } - - @Test - public void testGetAllCertifiedServicesNoFilter() { - Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, false); - assertTrue(highestResourcesRes.isLeft()); - List highestResources = highestResourcesRes.left().value(); - // calculate expected count value - long highestResourcesExpectedCount = calculateCount(new HashMap() { - { - put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - } - }, null); - highestResourcesExpectedCount += calculateCount(new HashMap() { - { - put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - } - }, new HashMap() { - { - put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - } - }); - assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); - } - - @Test - public void testGetServicesExcludeList() { - List excludeList = Arrays.asList(ResourceTypeEnum.VF, ResourceTypeEnum.VFCMT); - Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, excludeList, true); - assertTrue(highestResourcesRes.isLeft()); - List highestResources = highestResourcesRes.left().value(); - // calculate expected count value - long highestResourcesExpectedCount = calculateCount(new HashMap() { - { - put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - } - }, null); - assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); - } - - @Test - public void testGetCertifiedServicesExcludeList() { - List excludeList = Arrays.asList(ResourceTypeEnum.VL); - Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, excludeList, false); - assertTrue(highestResourcesRes.isLeft()); - List highestResources = highestResourcesRes.left().value(); - // calculate expected count value - long highestResourcesExpectedCount = calculateCount(new HashMap() { - { - put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - } - }, null); - highestResourcesExpectedCount += calculateCount(new HashMap() { - { - put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - } - }, new HashMap() { - { - put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - } - }); - assertEquals(highestResources.stream().count(), highestResourcesExpectedCount); - } - - @Test - public void testUpdateToscaElement_NotFound() { - Either result; - TopologyTemplate topologyTemplate = new TopologyTemplate(); - String userID = "userID"; - topologyTemplate.setLastUpdaterUserId(userID); - GraphVertex graphVertex = new GraphVertex(); - ComponentParametersView componentParametersView = new ComponentParametersView(); - result = toscaElementOperation.updateToscaElement(topologyTemplate, graphVertex, componentParametersView); - assertEquals(null, result); - } - - private boolean genericTestGetResourcesWithExcludeList(List excludeList) { - Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE,excludeList, true); - assertTrue(highestResourcesRes.isLeft()); - List highestResources = highestResourcesRes.left().value(); - // calculate expected count value - long highestResourcesExpectedCount = calculateCount(new HashMap() { - { - put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - } - }, new HashMap() { - { - put(GraphPropertyEnum.RESOURCE_TYPE, excludeList); - } - }); - return highestResources.stream().count() == (highestResourcesExpectedCount); - } - - private boolean genericTestGetCertifiedResourcesWithExcludeList(List excludeList) { - Either, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludeList, false); - assertTrue(highestResourcesRes.isLeft()); - List highestResources = highestResourcesRes.left().value(); - // calculate expected count value - long highestResourcesExpectedCount = calculateCount(new HashMap() { - { - put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - } - }, new HashMap() { - { - put(GraphPropertyEnum.RESOURCE_TYPE, excludeList); - } - }); - highestResourcesExpectedCount += calculateCount(new HashMap() { - { - put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - } - }, new HashMap() { - { - put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - put(GraphPropertyEnum.RESOURCE_TYPE, excludeList); - } - }); - return highestResources.stream().count() == highestResourcesExpectedCount; - } - - private void initGraphForTest() { - GraphTestUtils.createRootCatalogVertex(titanDao); - - Map highstVerticesProps = new HashMap() { - { - put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - } - }; - - Map certifiedVerticesProps = new HashMap() { - { - put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - } - }; - - // add vertices with higestVersion = true - allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VF)); - allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VFC)); - allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VFCMT)); - allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VL)); - allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.CP)); - allVertices.add(GraphTestUtils.createServiceVertex(titanDao, highstVerticesProps)); - - // add vertices with non-additional properties - for (int i=0 ; i<2 ; i++) { - allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VF)); - allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VFC)); - allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VFCMT)); - allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VL)); - allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.CP)); - allVertices.add(GraphTestUtils.createServiceVertex(titanDao, new HashMap<>())); - } - - // add certified vertices - for (int i=0; i<3; i++) { - allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VF)); - allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VFC)); - allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VFCMT)); - allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VL)); - allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.CP)); - allVertices.add(GraphTestUtils.createServiceVertex(titanDao, certifiedVerticesProps)); - } - //allVertices.stream().forEach( v -> System.out.println("type: "+v.getMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE))); - //String result = GraphTestUtils.exportGraphMl(titanDao.getGraph().left().value(), ""); - //System.out.println("graph is: " + result); - } - - private long calculateCount(HashMap hasProps, Map doesntHaveProps){ - return allVertices.stream(). - filter(v -> { - Map vertexProps = v.getMetadataProperties(); - if (hasProps != null) { - for (Map.Entry prop: hasProps.entrySet()){ - Object value = vertexProps.get(prop.getKey()); - if ( value == null || !value.equals(prop.getValue())) { - return false; - } - } - } - - if (doesntHaveProps != null) { - for (Map.Entry prop : doesntHaveProps.entrySet()) { - Object value = vertexProps.get(prop.getKey()); - Object propValue = prop.getValue(); - if ( value != null && propValue != null && propValue instanceof List ) { - for (ResourceTypeEnum propVal : (List)propValue) { - if (propVal.name().equals(value)) { - return false; - } - } - } - else if (value != null && value.equals(propValue)){ - return false; - } - } - } - return true; - }).count(); - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java deleted file mode 100644 index 27fbce4776..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; - -/** - * Created by cb478c on 6/13/2017. - */ -@org.springframework.stereotype.Component("test-tosca-element-operation") -public class ToscaElementOperationTestImpl extends ToscaElementOperation { - - @Override - protected Either getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) { - titanDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata); - T toscaElement = convertToComponent(vertexComponent); - return Either.left(toscaElement); - } - - @Override - public Either getToscaElement(String uniqueId, ComponentParametersView componentParametersView) { - return null; - } - - @Override - public Either getToscaElement(GraphVertex toscaElementVertex, ComponentParametersView componentParametersView) { - return null; - } - - @Override - public Either deleteToscaElement(GraphVertex toscaElementVertex) { - return null; - } - - @Override - public Either createToscaElement(ToscaElement toscaElement) { - return null; - } - - @Override - protected TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) { - return null; - } - - @Override - protected TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) { - return null; - } - - @Override - protected TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) { - return null; - } - - @Override - protected StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) { - return null; - } - - @Override - protected StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV) { - return null; - } - - @Override - public void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) { - - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadePoliciesTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadePoliciesTest.java deleted file mode 100644 index 95dca7f920..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadePoliciesTest.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -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.config.TitanSpringConfig; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.HealingTitanDao; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.ModelTestBase; -import org.openecomp.sdc.be.model.PolicyDefinition; -import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static java.util.Arrays.asList; -import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {TitanSpringConfig.class, ModelOperationsSpringConfig.class}) -public class ToscaOperationFacadePoliciesTest extends ModelTestBase { - - @Autowired - private ToscaOperationFacade toscaOperationFacade; - @Autowired - private HealingTitanDao titanDao; - - private PolicyDefinition policy1, policy2; - - @BeforeClass - public static void setupBeforeClass() { - ModelTestBase.init(); - } - - @Before - public void setUp() throws Exception { - policy1 = createPolicyDefinition("type1"); - policy2 = createPolicyDefinition("type2"); - createContainerVertexInDB(); - createPoliciesOnGraph(policy1, policy2); - } - - private void createPoliciesOnGraph(PolicyDefinition ... policies) { - for (int i = 0; i < policies.length; i++) { - PolicyDefinition policy = policies[i]; - Either createdPolicy = toscaOperationFacade.associatePolicyToComponent(CONTAINER_ID, policy, i); - assertTrue(createdPolicy.isLeft()); - } - } - - @After - public void tearDown() { - titanDao.rollback(); - } - - @Test - public void updatePoliciesTargetsOfComponent_updateSinglePolicy() { - List updatedTargetIds = asList("instance1new", "instance2"); - PolicyDefinition originalPolicy2 = clonePolicyWithTargets(policy2); - updatePolicyTypeTargetsIds(policy1, PolicyTargetType.COMPONENT_INSTANCES, updatedTargetIds); - updatePolicyTypeTargetsIds(policy2, PolicyTargetType.COMPONENT_INSTANCES, updatedTargetIds); - - StorageOperationStatus storageOperationStatus = toscaOperationFacade.updatePoliciesOfComponent(CONTAINER_ID, singletonList(policy1)); - assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); - Component updatedComponent = fetchComponentFromDB(); - verifyPolicyTargets(updatedComponent.getPolicyById(policy1.getUniqueId()), policy1); - verifyPolicyTargets(updatedComponent.getPolicyById(policy2.getUniqueId()), originalPolicy2); - } - - @Test - public void updatePoliciesTargetsOfComponent_updateMultiplePolicies() { - List updatedTargetIds = asList("instance1new", "instance2"); - updatePolicyTypeTargetsIds(policy1, PolicyTargetType.COMPONENT_INSTANCES, updatedTargetIds); - updatePolicyTypeTargetsIds(policy2, PolicyTargetType.COMPONENT_INSTANCES, updatedTargetIds); - StorageOperationStatus storageOperationStatus = toscaOperationFacade.updatePoliciesOfComponent(CONTAINER_ID, asList(policy1, policy2)); - assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); - Component updatedComponent = fetchComponentFromDB(); - verifyPolicyTargets(updatedComponent.getPolicyById(policy1.getUniqueId()), policy1); - verifyPolicyTargets(updatedComponent.getPolicyById(policy2.getUniqueId()), policy2); - } - - private PolicyDefinition clonePolicyWithTargets(PolicyDefinition policy) { - PolicyDefinition originalPolicy = new PolicyDefinition(policy); - Map> clonedTargetMap = policy.getTargets().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> new ArrayList<>(entry.getValue()))); - originalPolicy.setTargets(clonedTargetMap); - return originalPolicy; - } - - private void verifyPolicyTargets(PolicyDefinition updatedPolicy, PolicyDefinition expectedPolicy) { - assertThat(updatedPolicy.getTargets()) - .isEqualTo(expectedPolicy.getTargets()); - } - - private void updatePolicyTypeTargetsIds(PolicyDefinition policy, PolicyTargetType targetType, List updatedTargetIds) { - policy.getTargets().put(targetType, updatedTargetIds); - } - - private Component fetchComponentFromDB() { - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnorePolicies(false); - return toscaOperationFacade.getToscaElement(CONTAINER_ID, componentParametersView).left().value(); - } - - private void createContainerVertexInDB() { - GraphVertex resource = createBasicContainerGraphVertex(); - Either container = titanDao.createVertex(resource); - assertTrue(container.isLeft()); - } - - private PolicyDefinition createPolicyDefinition(String type) { - PolicyDefinition policy = new PolicyDefinition(); - policy.setPolicyTypeName(type); - policy.setTargets(new HashMap<>()); - policy.getTargets().put(PolicyTargetType.COMPONENT_INSTANCES, asList("instance1", "instance2")); - return policy; - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadeTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadeTest.java deleted file mode 100644 index b43b632ad1..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadeTest.java +++ /dev/null @@ -1,688 +0,0 @@ -/* - - * Copyright (c) 2018 AT&T Intellectual Property. - - * - - * 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. - - */ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.ArgumentMatchers; -import org.mockito.MockitoAnnotations; -import org.mockito.junit.MockitoJUnitRunner; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.HealingTitanDao; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.PolicyDefinition; -import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; -import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.Set; -import java.util.HashSet; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.Collections; -import java.util.Arrays; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; - -@RunWith(MockitoJUnitRunner.class) -public class ToscaOperationFacadeTest { - private static final String COMPONENT_ID = "componentId"; - private static final String PROPERTY1_NAME = "prop1"; - private static final String PROPERTY1_TYPE = "string"; - private static final String PROPERTY2_NAME = "prop2"; - private static final String PROPERTY2_TYPE = "integer"; - - @InjectMocks - private ToscaOperationFacade testInstance; - - @Mock - private HealingTitanDao titanDaoMock; - - @Mock - private TopologyTemplateOperation topologyTemplateOperationMock; - - @Mock - private NodeTypeOperation nodeTypeOperation; - - @Mock - private NodeTemplateOperation nodeTemplateOperationMock; - - @Before - public void setUp() throws Exception { - testInstance = new ToscaOperationFacade(); - MockitoAnnotations.initMocks(this); - } - - @SuppressWarnings("unchecked") - @Test - public void fetchMetaDataByResourceType() throws Exception { - ArgumentCaptor criteriaCapture = ArgumentCaptor.forClass(Map.class); - ArgumentCaptor criteriaNotCapture = ArgumentCaptor.forClass(Map.class); - ComponentParametersView dataFilter = new ComponentParametersView(); - List mockVertices = getMockVertices(2); - Either, TitanOperationStatus> returnedVertices = Either.left(mockVertices); - - when(titanDaoMock.getByCriteria(eq(null), criteriaCapture.capture(), criteriaNotCapture.capture(), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(returnedVertices); - when(topologyTemplateOperationMock.getToscaElement(mockVertices.get(0), dataFilter)).thenReturn(Either.left(getResourceToscaElement("0"))); - when(topologyTemplateOperationMock.getToscaElement(mockVertices.get(1), dataFilter)).thenReturn(Either.left(getResourceToscaElement("1"))); - Either, StorageOperationStatus> fetchedComponents = testInstance.fetchMetaDataByResourceType(ResourceTypeEnum.VF.getValue(), dataFilter); - - verifyCriteriaForHighestVersionAndVfResourceType(criteriaCapture); - verifyCriteriaNotIsDeleted(criteriaNotCapture); - - assertTrue(fetchedComponents.isLeft()); - List cmpts = fetchedComponents.left().value(); - assertEquals(2, cmpts.size()); - assertEquals("0", cmpts.get(0).getUniqueId()); - assertEquals("1", cmpts.get(1).getUniqueId()); - } - - private void verifyCriteriaForHighestVersionAndVfResourceType(ArgumentCaptor criteriaCapture) { - Map criteria = (Map)criteriaCapture.getValue(); - assertEquals(2, criteria.size()); - assertEquals(criteria.get(GraphPropertyEnum.RESOURCE_TYPE), "VF"); - assertEquals(criteria.get(GraphPropertyEnum.IS_HIGHEST_VERSION), true); - } - - private void verifyCriteriaNotIsDeleted(ArgumentCaptor criteriaNotCapture) { - Map notCriteria = (Map)criteriaNotCapture.getValue(); - assertEquals(1, notCriteria.size()); - assertEquals(notCriteria.get(GraphPropertyEnum.IS_DELETED), true); - } - - @SuppressWarnings("unchecked") - @Test - public void fetchMetaDataByResourceType_failedToGetData() throws Exception { - when(titanDaoMock.getByCriteria(eq(null), anyMap(), anyMap(), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(Either.right(TitanOperationStatus.GENERAL_ERROR)); - Either, StorageOperationStatus> fetchedComponents = testInstance.fetchMetaDataByResourceType(ResourceTypeEnum.VF.getValue(), new ComponentParametersView()); - assertTrue(fetchedComponents.isRight()); - assertEquals(StorageOperationStatus.GENERAL_ERROR, fetchedComponents.right().value()); - } - - @Test - public void associatePolicyToComponentSuccessTest(){ - Either result = associatePolicyToComponentWithStatus(StorageOperationStatus.OK); - assertTrue(result.isLeft()); - } - - @Test - public void associatePolicyToComponentFailureTest(){ - Either result = associatePolicyToComponentWithStatus(StorageOperationStatus.BAD_REQUEST); - assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.BAD_REQUEST); - } - - @Test - public void updatePolicyOfComponentSuccessTest(){ - Either result = updatePolicyOfComponentWithStatus(StorageOperationStatus.OK); - assertTrue(result.isLeft()); - } - - @Test - public void updatePolicyOfComponentFailureTest(){ - Either result = updatePolicyOfComponentWithStatus(StorageOperationStatus.NOT_FOUND); - assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND); - } - - @Test - public void removePolicyFromComponentSuccessTest(){ - removePolicyFromComponentWithStatus(StorageOperationStatus.OK); - } - - @Test - public void removePolicyFromComponentFailureTest(){ - removePolicyFromComponentWithStatus(StorageOperationStatus.NOT_FOUND); - } - - @Test - public void testFindLastCertifiedToscaElementByUUID(){ - Either result; - Component component = new Resource(); - List list = new ArrayList<>(); - GraphVertex graphVertex = getTopologyTemplateVertex(); - list.add(graphVertex); - Map props = new EnumMap<>(GraphPropertyEnum.class); - props.put(GraphPropertyEnum.UUID, component.getUUID()); - props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - ToscaElement toscaElement = getToscaElementForTest(); - when(topologyTemplateOperationMock.getToscaElement(ArgumentMatchers.eq(graphVertex),any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement)); - when(titanDaoMock.getByCriteria(ModelConverter.getVertexType(component), props)).thenReturn(Either.left(list)); - result = testInstance.findLastCertifiedToscaElementByUUID(component); - Component resultComp = result.left().value(); - assertEquals(resultComp.getToscaType(),ToscaElementTypeEnum.TOPOLOGY_TEMPLATE.getValue()); - } - - @Test - public void testLatestComponentByToscaResourceName(){ - Either result; - TopologyTemplate toscaElement = new TopologyTemplate(); - toscaElement.setComponentType(ComponentTypeEnum.SERVICE); - List list = new ArrayList<>(); - GraphVertex graphVertex = getTopologyTemplateVertex(); - Map props = new HashMap<>(); - props.put(GraphPropertyEnum.VERSION, "1.0"); - graphVertex.setMetadataProperties(props); - list.add(graphVertex); - - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, "toscaResourceName"); - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - when(titanDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(list)); - when(topologyTemplateOperationMock.getToscaElement(ArgumentMatchers.eq(graphVertex),any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement)); - - result = testInstance.getFullLatestComponentByToscaResourceName("toscaResourceName"); - assertThat(result.isLeft()); - } - - @Test - public void testValidateCsarUuidUniqueness() { - StorageOperationStatus result; - String csarUUID = "csarUUID"; - Map properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID); - List vertexList = new ArrayList<>(); - when(titanDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(vertexList)); - result = testInstance.validateCsarUuidUniqueness(csarUUID); - assertEquals(StorageOperationStatus.ENTITY_ALREADY_EXISTS, result); - } - - @Test - public void testValidateCsarUuidUnique_true() { - StorageOperationStatus result; - String csarUUID = "csarUUID"; - Map properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID); - when(titanDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); - result = testInstance.validateCsarUuidUniqueness(csarUUID); - assertEquals(StorageOperationStatus.OK, result); - } - - @Test - public void testGetLatestCertiNodeTypeByToscaResourceName() { - Either result; - String toscaResourceName = "resourceName"; - String uniqueId = "uniqueId"; - GraphVertex graphVertex = getTopologyTemplateVertex(); - graphVertex.setJsonMetadataField(JsonPresentationFields.VERSION, "1.0"); - graphVertex.setUniqueId(uniqueId); - List vertexList = new ArrayList<>(); - vertexList.add(graphVertex); - Map props = new EnumMap<>(GraphPropertyEnum.class); - props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - ToscaElement topologyTemplate = new TopologyTemplate(); - topologyTemplate.setComponentType(ComponentTypeEnum.SERVICE); - when(titanDaoMock.getByCriteria(VertexTypeEnum.NODE_TYPE, props, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(vertexList)); - when(titanDaoMock.getVertexById(uniqueId, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex)); - when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(topologyTemplate)); - result = testInstance.getLatestCertifiedNodeTypeByToscaResourceName(toscaResourceName); - assertThat(result.isLeft()); - } - - @Test - public void testValidateCompExists() { - Either result; - String componentId = "componentId"; - GraphVertex graphVertex = getTopologyTemplateVertex(); - when(titanDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex)); - result = testInstance.validateComponentExists(componentId); - assertEquals(true, result.left().value()); - } - - @Test - public void testValidateCompExists_NotFound() { - Either result; - String componentId = "componentId"; - when(titanDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); - result = testInstance.validateComponentExists(componentId); - assertEquals(false, result.left().value()); - } - - @Test - public void testValidateToscaResourceNameExists() { - Either result; - String templateName = "templateName"; - Map properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, templateName); - List graphVertexList = new ArrayList<>(); - GraphVertex graphVertex = getTopologyTemplateVertex(); - graphVertexList.add(graphVertex); - when(titanDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(graphVertexList)); - result = testInstance.validateToscaResourceNameExists(templateName); - assertEquals(true, result.left().value()); - } - - @Test - public void testValidateToscaResourceNameExists_false() { - Either result; - String templateName = "templateName"; - Map properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, templateName); - List graphVertexList = new ArrayList<>(); - GraphVertex graphVertex = getTopologyTemplateVertex(); - graphVertexList.add(graphVertex); - when(titanDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); - result = testInstance.validateToscaResourceNameExists(templateName); - assertEquals(false, result.left().value()); - } - - @Test - public void testOverrideComponent() { - Either result; - Resource resource = new Resource(); - String id = "id"; - resource.setUniqueId(id); - GraphVertex graphVertex = getTopologyTemplateVertex(); - graphVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); - NodeType nodeType = new NodeType(); - nodeType.setComponentType(ComponentTypeEnum.RESOURCE); - ToscaElement toscaElement = new TopologyTemplate(); - toscaElement.setComponentType(ComponentTypeEnum.SERVICE); - when(titanDaoMock.getVertexById(id, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex)); - when(titanDaoMock.getParentVertex(graphVertex, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex)); - when(topologyTemplateOperationMock.deleteToscaElement(graphVertex)).thenReturn(Either.left(toscaElement)); - when(nodeTypeOperation.createToscaElement(any(ToscaElement.class))).thenReturn(Either.left(nodeType)); - when(titanDaoMock.getVertexById(null, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex)); - when(titanDaoMock.createEdge(graphVertex, graphVertex, EdgeLabelEnum.VERSION, null)).thenReturn(TitanOperationStatus.OK); - result = testInstance.overrideComponent(resource, resource); - assertTrue(result.isLeft()); - } - - @Test - public void testGetToscaElement() { - Either result; - String id = "id"; - GraphVertex graphVertex = getTopologyTemplateVertex(); - ToscaElement toscaElement = getToscaElementForTest(); - when(titanDaoMock.getVertexById(id, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex)); - when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement)); - result = testInstance.getToscaElement(id, JsonParseFlagEnum.ParseAll); - assertTrue(result.isLeft()); - } - - @Test - public void testMarkComponentToDelete() { - StorageOperationStatus result; - Component component = new Resource(); - String id = "id"; - component.setUniqueId(id); - GraphVertex graphVertex = getTopologyTemplateVertex(); - when(titanDaoMock.getVertexById(id, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex)); - when(nodeTypeOperation.markComponentToDelete(graphVertex)).thenReturn(Either.left(graphVertex)); - result = testInstance.markComponentToDelete(component); - assertEquals(result, StorageOperationStatus.OK); - } - - @Test - public void testDelToscaComponent() { - Either result; - String componentId = "compId"; - GraphVertex graphVertex = getTopologyTemplateVertex(); - ToscaElement toscaElement = getToscaElementForTest(); - when(titanDaoMock.getVertexById(componentId, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex)); - when(topologyTemplateOperationMock.deleteToscaElement(graphVertex)).thenReturn(Either.left(toscaElement)); - result = testInstance.deleteToscaComponent(componentId); - assertTrue(result.isLeft()); - } - - @Test - public void testGetLatestByToscaResourceName() { - Either result; - String toscaResourceName = "name"; - ToscaElement toscaElement = getToscaElementForTest(); - - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - List graphVertexList = new ArrayList<>(); - GraphVertex graphVertex = getTopologyTemplateVertex(); - graphVertex.setUniqueId(toscaResourceName); - Map props = new HashMap<>(); - props.put(GraphPropertyEnum.VERSION, "1.0"); - graphVertex.setMetadataProperties(props); - graphVertexList.add(graphVertex); - - when(titanDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(graphVertexList)); - when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement)); - result = testInstance.getLatestByToscaResourceName(toscaResourceName); - assertTrue(result.isLeft()); - } - - @Test - public void testGetFollowed() { - Either, StorageOperationStatus> result; - String userId = "id"; - Set lifecycleStates = new HashSet<>(); - Set lastStateStates = new HashSet<>(); - lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - lifecycleStates.add(LifecycleStateEnum.CERTIFIED); - lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - ComponentTypeEnum componentType = ComponentTypeEnum.RESOURCE; - List toscaEleList = new ArrayList<>(); - ToscaElement toscaElement = getToscaElementForTest(); - toscaEleList.add(toscaElement); - when(nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType)).thenReturn(Either.left(toscaEleList)); - result = testInstance.getFollowed(userId, lifecycleStates, lastStateStates, componentType); - assertTrue(result.isLeft()); - assertEquals(1, result.left().value().size()); - } - - @Test - public void testGetBySystemName() { - Either, StorageOperationStatus> result; - String sysName = "sysName"; - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE; - ToscaElement toscaElement = getToscaElementForTest(); - List componentVertices = new ArrayList<>(); - GraphVertex graphVertex = getTopologyTemplateVertex(); - componentVertices.add(graphVertex); - Map propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - - propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, sysName); - propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentTypeEnum.name()); - - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - when(titanDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(componentVertices)); - when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement)); - result = testInstance.getBySystemName(componentTypeEnum, sysName); - assertTrue(result.isLeft()); - assertEquals(1, result.left().value().size()); - } - - @Test - public void testGetCompByNameAndVersion() { - Either result; - ComponentTypeEnum componentType = ComponentTypeEnum.RESOURCE; - String name = "name"; - String version = "1.0"; - JsonParseFlagEnum parseFlag = JsonParseFlagEnum.ParseAll; - List graphVertexList = new ArrayList<>(); - GraphVertex graphVertex = getTopologyTemplateVertex(); - graphVertexList.add(graphVertex); - ToscaElement toscaElement = getToscaElementForTest(); - Map hasProperties = new EnumMap<>(GraphPropertyEnum.class); - Map hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); - - hasProperties.put(GraphPropertyEnum.NAME, name); - hasProperties.put(GraphPropertyEnum.VERSION, version); - hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); - hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - when(titanDaoMock.getByCriteria(null, hasProperties, hasNotProperties, parseFlag)).thenReturn(Either.left(graphVertexList)); - when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement)); - result = testInstance.getComponentByNameAndVersion(componentType, name, version, parseFlag); - assertTrue(result.isLeft()); - } - - private ToscaElement getToscaElementForTest() { - ToscaElement toscaElement = new TopologyTemplate(); - toscaElement.setComponentType(ComponentTypeEnum.RESOURCE); - return toscaElement; - } - - @Test - public void addDataTypesToComponentSuccessTest(){ - Either, StorageOperationStatus> result = addDataTypesToComponentWithStatus(StorageOperationStatus.OK); - assertTrue(result.isLeft()); - } - - @Test - public void addDataTypesToComponentFailureTest_BadRequest(){ - Either, StorageOperationStatus> result = addDataTypesToComponentWithStatus(StorageOperationStatus.BAD_REQUEST); - assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.BAD_REQUEST); - } - - private Either, StorageOperationStatus> addDataTypesToComponentWithStatus(StorageOperationStatus status) { - Map dataTypes = new HashMap<>(); - String componentId = "componentid"; - String Id = "id"; - - PropertyDefinition noDefaultProp = new PropertyDefinition(); - noDefaultProp.setName("noDefaultProp"); - PropertyDefinition prop1 = new PropertyDefinition(); - prop1.setDefaultValue("def1"); - prop1.setName("prop1"); - PropertyDefinition prop2 = new PropertyDefinition(); - prop2.setType("dataType1"); - prop2.setName("prop2"); - PropertyDefinition prop3 = new PropertyDefinition(); - prop3.setDefaultValue("def3"); - prop3.setName("prop3"); - - DataTypeDefinition noDefaultValue = new DataTypeDefinition(); - noDefaultValue.setProperties(Collections.singletonList(noDefaultProp)); - noDefaultValue.setDerivedFromName("name0"); - - DataTypeDefinition dataType1 = new DataTypeDefinition(); - dataType1.setProperties(Arrays.asList(prop1, prop3)); - dataType1.setName("name1"); - dataType1.setDerivedFromName("derivedfromname1"); - - DataTypeDefinition dataType2 = new DataTypeDefinition(); - dataType2.setDerivedFrom(dataType1); - dataType2.setName("name2"); - dataType2.setDerivedFromName("derivedfromname2"); - - DataTypeDefinition dataType3 = new DataTypeDefinition(); - dataType3.setProperties(Collections.singletonList(prop2)); - dataType3.setDerivedFrom(noDefaultValue); - dataType3.setName("name3"); - dataType3.setDerivedFromName("derivedfromname3"); - - dataTypes.put("noDefault", noDefaultValue); - dataTypes.put("dataType1", dataType1); - dataTypes.put("dataType2", dataType2); - dataTypes.put("dataType3", dataType3); - - GraphVertex vertex; - if(status == StorageOperationStatus.OK){ - vertex = getTopologyTemplateVertex(); - } else { - vertex = getNodeTypeVertex(); - } - Either getVertexEither = Either.left(vertex); - when(titanDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(getVertexEither); - when(topologyTemplateOperationMock.addToscaDataToToscaElement(eq(vertex), - eq(EdgeLabelEnum.DATA_TYPES), eq(VertexTypeEnum.DATA_TYPES), anyMap(), eq(JsonPresentationFields.NAME))).thenReturn(status); - return testInstance.addDataTypesToComponent(dataTypes, componentId); - } - - @Test - public void testDataTypesToComponentFailureTest_NotFound() { - Either, StorageOperationStatus> result; - String componentId = "componentId"; - GraphVertex vertex = getNodeTypeVertex(); - Map dataTypes = new HashMap<>(); - when(titanDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); - result = testInstance.addDataTypesToComponent(dataTypes, componentId); - assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND); - } - - @Test - public void testDeleteDataTypeOfComponent() { - StorageOperationStatus result; - Component component = new Resource(); - String id = "id"; - component.setUniqueId(id); - String datatype = null; - - DataTypeDefinition dataType1 = new DataTypeDefinition(); - dataType1.setName("name1"); - Map dataTypeDataMap = new HashMap<>(); - dataTypeDataMap.put("datatype1", dataType1); - List dataTypeMap = dataTypeDataMap.values().stream().map(e -> { DataTypeDefinition dataType = new DataTypeDefinition(e);return dataType; }).collect(Collectors.toList()); - component.setDataTypes(dataTypeMap); - GraphVertex graphVertex = getTopologyTemplateVertex(); - result = testInstance.deleteDataTypeOfComponent(component, "datatype1"); - assertEquals(datatype, result); - } - - @Test - public void testAddComponentInstancePropertiesToComponent() { - // set up component object - Component component = new Resource(); - component.setUniqueId(COMPONENT_ID); - List instanceProps = new ArrayList<>(); - ComponentInstanceProperty instanceProp = new ComponentInstanceProperty(); - instanceProp.setName(PROPERTY1_NAME); - instanceProp.setType(PROPERTY1_TYPE); - instanceProps.add(instanceProp); - instanceProp = new ComponentInstanceProperty(); - instanceProp.setName(PROPERTY2_NAME); - instanceProp.setType(PROPERTY2_TYPE); - instanceProps.add(instanceProp); - Map> instancePropsMap = - Collections.singletonMap(COMPONENT_ID, instanceProps); - component.setComponentInstancesProperties(Collections.singletonMap(COMPONENT_ID, new ArrayList<>())); - - when(nodeTemplateOperationMock.addComponentInstanceProperty(any(), any(), any())) - .thenReturn(StorageOperationStatus.OK); - - Either>, StorageOperationStatus> result = - testInstance.addComponentInstancePropertiesToComponent(component, instancePropsMap); - assertTrue(result.isLeft()); - verify(nodeTemplateOperationMock, times(2)).addComponentInstanceProperty(any(), any(), any()); - List resultProps = result.left().value().get(COMPONENT_ID); - assertTrue(resultProps.stream().anyMatch(e -> e.getName().equals(PROPERTY1_NAME))); - assertTrue(resultProps.stream().anyMatch(e -> e.getName().equals(PROPERTY2_NAME))); - } - - private Either associatePolicyToComponentWithStatus(StorageOperationStatus status) { - PolicyDefinition policy = new PolicyDefinition(); - String componentId = "componentId"; - int counter = 0; - GraphVertex vertex; - if(status == StorageOperationStatus.OK){ - vertex = getTopologyTemplateVertex(); - } else { - vertex = getNodeTypeVertex(); - } - Either getVertexEither = Either.left(vertex); - when(titanDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(getVertexEither); - when(topologyTemplateOperationMock.addPolicyToToscaElement(eq(vertex), any(PolicyDefinition.class), anyInt())).thenReturn(status); - return testInstance.associatePolicyToComponent(componentId, policy, counter); - } - - private Either updatePolicyOfComponentWithStatus(StorageOperationStatus status) { - PolicyDefinition policy = new PolicyDefinition(); - String componentId = "componentId"; - GraphVertex vertex = getTopologyTemplateVertex(); - when(titanDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.NoParse))).thenReturn(Either.left(vertex)); - when(topologyTemplateOperationMock.updatePolicyOfToscaElement(eq(vertex), any(PolicyDefinition.class))).thenReturn(status); - return testInstance.updatePolicyOfComponent(componentId, policy); - } - - private void removePolicyFromComponentWithStatus(StorageOperationStatus status) { - String componentId = "componentId"; - String policyId = "policyId"; - GraphVertex vertex = getTopologyTemplateVertex(); - Either getVertexEither = Either.left(vertex); - when(titanDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.NoParse))).thenReturn(getVertexEither); - when(topologyTemplateOperationMock.removePolicyFromToscaElement(eq(vertex), eq(policyId))).thenReturn(status); - StorageOperationStatus result = testInstance.removePolicyFromComponent(componentId, policyId); - assertSame(result, status); - } - - private List getMockVertices(int numOfVertices) { - return IntStream.range(0, numOfVertices).mapToObj(i -> getTopologyTemplateVertex()).collect(Collectors.toList()); - } - - private ToscaElement getResourceToscaElement(String id) { - ToscaElement toscaElement = new TopologyTemplate(); - toscaElement.setMetadata(new HashMap<>()); - toscaElement.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), "RESOURCE"); - toscaElement.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), id); - return toscaElement; - } - - private GraphVertex getTopologyTemplateVertex() { - GraphVertex graphVertex = new GraphVertex(); - graphVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); - return graphVertex; - } - - private GraphVertex getNodeTypeVertex() { - GraphVertex graphVertex = new GraphVertex(); - graphVertex.setLabel(VertexTypeEnum.NODE_TYPE); - return graphVertex; - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/UpgradeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/UpgradeOperationTest.java deleted file mode 100644 index acb9af6a33..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/UpgradeOperationTest.java +++ /dev/null @@ -1,183 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.operations; - -import fj.data.Either; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -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.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.utils.GraphTestUtils; -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.UserAdminOperation; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:application-context-test.xml") -public class UpgradeOperationTest extends ModelTestBase { - - private boolean isInitialized; - @Resource - private TitanDao titanDao; - @Resource - private UpgradeOperation upgradeOperation; - @Resource - private TopologyTemplateOperation topologyTemplateOperation; - @Resource - private NodeTemplateOperation nodeTemplateOperation; - @Resource - private UserAdminOperation userAdminOperation; - @javax.annotation.Resource - private IElementOperation elementOperation; - - private User user; - - private CategoryDefinition resourceCategory; - private CategoryDefinition serviceCategory; - - - @BeforeClass - public static void initTest() { - ModelTestBase.init(); - } - - @Before - public void beforeTest() { - if (!isInitialized) { - GraphTestUtils.clearGraph(titanDao); - initGraphForTest(); - isInitialized = true; - } - } - - @Test - public void testGetSimpleDependency() { - - TopologyTemplate vf = createVf("vf1"); - - TopologyTemplate service = createServiceWitnInstance("service1", vf); - - - Either, StorageOperationStatus> result = upgradeOperation.getComponentDependencies(vf.getUniqueId()); - assertThat(result.isLeft()).isTrue(); - List dependencies = result.left().value(); - assertThat(dependencies).hasSize(1); - - ComponentDependency dependency = dependencies.get(0); - assertThat(dependency.getName()).isEqualTo(vf.getName()); - assertThat(dependency.getVersion()).isEqualTo(vf.getVersion()); - assertThat(dependency.getDependencies()).hasSize(1); - - ComponentDependency container = dependency.getDependencies().get(0); - assertThat(container.getName()).isEqualTo(service.getName()); - assertThat(container.getVersion()).isEqualTo(service.getVersion()); - assertThat(container.getDependencies()).isNull(); - - } - - /******************************* - * Preperation Methods - *******************************/ - private void initGraphForTest() { - - user = new User("Jim", "Tom", "jt123a", "1@mail.com", "DESIGNER", System.currentTimeMillis()); - Either saveUserData = userAdminOperation.saveUserData(user); - assertThat(saveUserData.isLeft()).isTrue(); - - GraphTestUtils.createRootCatalogVertex(titanDao); - resourceCategory = createResourceCategories(); - serviceCategory = createServiceCategory(); - - } - - private TopologyTemplate createServiceWitnInstance(String name, TopologyTemplate createdVf) { - - TopologyTemplate serviceNew = createTopologyTemplate(ComponentTypeEnum.SERVICE, name); - List categoriesService = new ArrayList<>(); - categoriesService.add(serviceCategory); - serviceNew.setCategories(categoriesService); - - Either createService = topologyTemplateOperation.createTopologyTemplate(serviceNew); - assertThat(createService.isLeft()).isTrue(); - - ComponentInstance vfInstance = new ComponentInstance(); - vfInstance.setUniqueId(createdVf.getUniqueId() + createdVf.getName()); - vfInstance.setComponentUid(createdVf.getUniqueId()); - vfInstance.setName(createdVf.getName()); - Either, StorageOperationStatus> addInstance = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(serviceNew, createdVf, "0", vfInstance, false, user); - assertThat(addInstance.isLeft()).isTrue(); - return serviceNew; - } - - private CategoryDefinition createServiceCategory() { - CategoryDefinition categoryService = new CategoryDefinition(); - categoryService.setName("servicecategory"); - categoryService.setNormalizedName("servicecategory"); - categoryService.setUniqueId("servicecategory"); - Either createCategory = elementOperation.createCategory(categoryService , NodeTypeEnum.ServiceNewCategory); - - assertThat(createCategory.isLeft()).isTrue(); - return categoryService; - } - - private TopologyTemplate createVf(String name) { - - TopologyTemplate resource = createTopologyTemplate(ComponentTypeEnum.RESOURCE, name); - - resource.setResourceType(ResourceTypeEnum.VF); - List categories = new ArrayList<>(); - categories.add(resourceCategory); - resource.setCategories(categories); - Either createVf = topologyTemplateOperation.createTopologyTemplate(resource); - assertThat( createVf.isLeft()).isTrue(); - return resource; - } - - private CategoryDefinition createResourceCategories() { - CategoryDefinition category = new CategoryDefinition(); - category.setName("category1"); - category.setNormalizedName("category1"); - category.setUniqueId("category1"); - Either createCategory = elementOperation.createCategory(category , NodeTypeEnum.ResourceNewCategory); - assertThat(createCategory.isLeft()).isTrue(); - - SubCategoryDefinition subCategory = new SubCategoryDefinition(); - - subCategory.setName("subcategory1"); - subCategory.setNormalizedName("subcategory1"); - subCategory.setUniqueId("subcategory1"); - elementOperation.createSubCategory(createCategory.left().value().getUniqueId(), subCategory, NodeTypeEnum.ResourceSubcategory); - category.addSubCategory(subCategory); - return category; - } - - private TopologyTemplate createTopologyTemplate(ComponentTypeEnum type, String name) { - TopologyTemplate template = new TopologyTemplate(); - template.setUniqueId(IdBuilderUtils.generateUniqueId()); - template.setComponentType(type); - template.setHighestVersion(true); - template.setLifecycleState(LifecycleStateEnum.CERTIFIED); - template.setMetadataValue(JsonPresentationFields.NAME, name); - template.setMetadataValue(JsonPresentationFields.VERSION, "1.0"); - template.setCreatorUserId(user.getUserId()); - return template; - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/CapabilityTestUtils.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/CapabilityTestUtils.java deleted file mode 100644 index 6f6b7eacad..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/CapabilityTestUtils.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright © 2016-2018 European Support Limited - * - * 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. - */ - -package org.openecomp.sdc.be.model.jsontitan.utils; - -import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class CapabilityTestUtils { - - public static Map createCapPropsForTopologyTemplate(TopologyTemplate topologyTemplate) { - Map capabilitiesMap = new HashMap<>(); - - List capabilityDefinitions = new ArrayList<>(); - CapabilityDefinition capabilityDefinition = createCapabilityDefinition(); - - capabilityDefinitions.add(capabilityDefinition); - ListCapabilityDataDefinition listCapabilityDataDefinition = new ListCapabilityDataDefinition(capabilityDefinitions); - capabilitiesMap.put(capabilityDefinition.getType(), listCapabilityDataDefinition); - topologyTemplate.setCapabilities(capabilitiesMap); - - List capPropList = new ArrayList<>(); - ComponentInstanceProperty instanceProperty = createProperties(); - capPropList.add(instanceProperty); - - MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); - for (ComponentInstanceProperty cip : capPropList) { - PropertyDataDefinition propertyDataDefinition = new PropertyDataDefinition(cip); - dataToCreate.put(cip.getName(), propertyDataDefinition); - } - - Map capabilitiesProperties = new HashMap<>(); - capabilitiesProperties.put(capabilityDefinition.getType() + ModelConverter.CAP_PROP_DELIM + - capabilityDefinition.getName(), dataToCreate); - return capabilitiesProperties; - } - - private static CapabilityDefinition createCapabilityDefinition() { - CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); - capabilityDefinition.setName("cap" + Math.random()); - capabilityDefinition.setType("tosca.capabilities.network.Bindable"); - capabilityDefinition.setOwnerId("resourceId"); - capabilityDefinition.setUniqueId("capUniqueId"); - List path = new ArrayList<>(); - path.add("path1"); - capabilityDefinition.setPath(path); - return capabilityDefinition; - } - - private static ComponentInstanceProperty createProperties() { - ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); - instanceProperty.setUniqueId("ComponentInput1_uniqueId"); - instanceProperty.setType("Integer"); - instanceProperty.setName("prop_name"); - instanceProperty.setDescription("prop_description_prop_desc"); - instanceProperty.setOwnerId("capUniqueId"); - instanceProperty.setValue("{\"get_input\":\"extcp20_order\"}"); - instanceProperty.setSchema(new SchemaDefinition()); - return instanceProperty; - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java deleted file mode 100644 index 71dd472a1c..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java +++ /dev/null @@ -1,129 +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.jsontitan.utils; - -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; -import fj.data.Either; -import org.apache.tinkerpop.gremlin.structure.io.IoCore; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.util.Iterator; -import java.util.Map; -import java.util.UUID; - -public final class GraphTestUtils { - - public static GraphVertex createRootCatalogVertex(TitanDao titanDao) { - GraphVertex catalogRootVertex = new GraphVertex(VertexTypeEnum.CATALOG_ROOT); - catalogRootVertex.setUniqueId(IdBuilderUtils.generateUniqueId()); - return titanDao.createVertex(catalogRootVertex) - .either(v -> v, s -> null); - } - - public static GraphVertex createRootArchiveVertex(TitanDao titanDao) { - GraphVertex archiveRootVertex = new GraphVertex(VertexTypeEnum.ARCHIVE_ROOT); - archiveRootVertex.setUniqueId(IdBuilderUtils.generateUniqueId()); - return titanDao.createVertex(archiveRootVertex) - .either(v -> v, s -> null); - } - - public static GraphVertex createResourceVertex(TitanDao titanDao, Map metadataProps, ResourceTypeEnum type) { - GraphVertex vertex = new GraphVertex(); - if (type == ResourceTypeEnum.VF) { - vertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); - vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE); - } else { - vertex.setLabel(VertexTypeEnum.NODE_TYPE); - vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.NODE_TYPE); - } - String uuid = UUID.randomUUID().toString(); - vertex.setUniqueId(uuid); - - vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid); - vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - vertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, type.name()); - vertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, false); - for (Map.Entry prop : metadataProps.entrySet()) { - vertex.addMetadataProperty(prop.getKey(), prop.getValue()); - } - titanDao.createVertex(vertex); - titanDao.commit(); - return vertex; - } - - public static GraphVertex createServiceVertex(TitanDao titanDao, Map metadataProps){ - GraphVertex vertex = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); - String uuid = UUID.randomUUID().toString(); - vertex.setUniqueId(uuid); - vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE); - vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid); - vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - for (Map.Entry prop : metadataProps.entrySet()) { - vertex.addMetadataProperty(prop.getKey(), prop.getValue()); - } - titanDao.createVertex(vertex); - titanDao.commit(); - return vertex; - } - - public static void clearGraph(TitanDao titanDao) { - 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(); - vertex.remove(); - } - } - titanDao.commit(); - } - - public static String exportGraphMl(TitanGraph graph, String outputDirectory) { - String result = null; - String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml"; - 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; - } -} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapperTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapperTest.java deleted file mode 100644 index 39ea68c3fe..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapperTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.utils; - -import org.junit.Test; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; - -public class IdMapperTest { - - private IdMapper createTestSubject() { - return new IdMapper(); - } - - - @Test - public void testMapComponentNameToUniqueId() throws Exception { - IdMapper testSubject; - String componentInstanceName = ""; - GraphVertex serviceVertex = null; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.mapComponentNameToUniqueId(componentInstanceName, serviceVertex); - } - - - @Test - public void testMapUniqueIdToComponentNameTo() throws Exception { - IdMapper testSubject; - String compUniqueId = ""; - GraphVertex serviceVertex = null; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.mapUniqueIdToComponentNameTo(compUniqueId, serviceVertex); - } -} \ No newline at end of file diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverterTest.java deleted file mode 100644 index a927f5a461..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverterTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - - * Copyright (c) 2018 Huawei Intellectual Property. - - * - - * 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. - - */ -package org.openecomp.sdc.be.model.jsontitan.utils; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.junit.MockitoJUnitRunner; -import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; - -import java.util.Map; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -@RunWith(MockitoJUnitRunner.class) -public class ModelConverterTest { - @InjectMocks - private ModelConverter test; - - @Test - public void testConvertToToscaElementService() - { - Service service = new Service(); - service.setComponentType(ComponentTypeEnum.SERVICE); - TopologyTemplate template = test.convertToToscaElement(service); - assertThat(template.getToscaType()).isEqualTo(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE); - } - - @Test - public void testConvertToToscaElementResource() - { - Resource resource = new Resource(); - resource.setComponentType(ComponentTypeEnum.RESOURCE); - NodeType nodeType = test.convertToToscaElement(resource); - assertThat(nodeType.getToscaType()).isEqualTo(ToscaElementTypeEnum.NODE_TYPE); - } - - @Test - public void testConvertFromToscaElementService() - { - TopologyTemplate topologyTemplate = new TopologyTemplate(); - topologyTemplate.setComponentType(ComponentTypeEnum.SERVICE); - Component component = test.convertFromToscaElement(topologyTemplate); - assertThat(component.getToscaType()).isEqualTo(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE.getValue()); - } - - @Test - public void testConvertFromToscaElementServiceWithSelfCapabilities() - { - TopologyTemplate topologyTemplate = new TopologyTemplate(); - - Map capabilitiesProperties = CapabilityTestUtils - .createCapPropsForTopologyTemplate(topologyTemplate); - - topologyTemplate.setCapabilitiesProperties(capabilitiesProperties); - - topologyTemplate.setComponentType(ComponentTypeEnum.SERVICE); - Component component = test.convertFromToscaElement(topologyTemplate); - assertThat(component.getToscaType()).isEqualTo(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE.getValue()); - } - - @Test - public void testConvertFromToscaElementResource() - { - TopologyTemplate topologyTemplate = new TopologyTemplate(); - topologyTemplate.setComponentType(ComponentTypeEnum.RESOURCE); - Component component = test.convertFromToscaElement(topologyTemplate); - assertThat(component.getToscaType()).isEqualTo(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE.getValue()); - } - - @Test - public void testConvertFromToscaElementResourceType() - { - TopologyTemplate topologyTemplate = new TopologyTemplate(); - topologyTemplate.setComponentType(ComponentTypeEnum.RESOURCE); - topologyTemplate.setResourceType(ResourceTypeEnum.PNF); - Resource resource = test.convertFromToscaElement(topologyTemplate); - assertSame(ResourceTypeEnum.PNF, resource.getResourceType()); - } - - @Test - public void testIsAtomicComponent() - { - Resource component = new Resource(); - component.setComponentType(ComponentTypeEnum.RESOURCE); - boolean result = test.isAtomicComponent(component); - assertTrue(result); - } - - @Test - public void testGetVertexType() - { - VertexTypeEnum result; - Resource component = new Resource(); - component.setComponentType(ComponentTypeEnum.RESOURCE); - result = test.getVertexType(component); - assertThat(result.getName()).isEqualTo("node_type"); - } -} 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 6fd04c18bb..dedf84cd76 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,9 +20,9 @@ package org.openecomp.sdc.be.model.operations.impl; -import com.thinkaurelius.titan.core.TitanEdge; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphEdge; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import static org.assertj.core.api.Assertions.assertThat; @@ -31,10 +31,10 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; 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.AdditionalInformationDefinition; import org.openecomp.sdc.be.model.ModelTestBase; @@ -55,14 +55,14 @@ import static org.mockito.Mockito.when; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context-test.xml") public class AdditionalInformationOperationTest extends ModelTestBase { - private static final TitanGenericDao titanGenericDao = mock(TitanGenericDao.class); + private static final JanusGraphGenericDao JANUS_GRAPH_GENERIC_DAO = mock(JanusGraphGenericDao.class); private static String USER_ID = "muUserId"; private static String CATEGORY_NAME = "category/mycategory"; @Mock - private TitanVertex titanVertex; + private JanusGraphVertex janusGraphVertex; - @javax.annotation.Resource(name = "titan-generic-dao") - private TitanGenericDao titanDao; + @javax.annotation.Resource(name = "janusgraph-generic-dao") + private JanusGraphGenericDao janusGraphDao; @javax.annotation.Resource(name = "additional-information-operation") private IAdditionalInformationOperation additionalInformationOperation; @@ -90,10 +90,10 @@ public class AdditionalInformationOperationTest extends ModelTestBase { @Test public void testAddInfoParameter_InvalidId(){ - Either result; + Either result; String uid = "uid"; String componentId = "componentId"; - when(titanGenericDao.getVertexByProperty(eq(uid),eq(componentId))).thenReturn(Either.left(titanVertex)); + when(JANUS_GRAPH_GENERIC_DAO.getVertexByProperty(eq(uid),eq(componentId))).thenReturn(Either.left(janusGraphVertex)); result = additionalInformationOperation.addAdditionalInformationParameter (NodeTypeEnum.Resource,componentId,"key","value"); assertThat(result.isRight()); @@ -101,10 +101,10 @@ public class AdditionalInformationOperationTest extends ModelTestBase { @Test public void testUpdateInfoParameter_InvalidId(){ - Either result; + Either result; String uid = "uid"; String componentId = "componentId"; - when(titanGenericDao.getVertexByProperty(eq(uid),eq(componentId))).thenReturn(Either.left(titanVertex)); + when(JANUS_GRAPH_GENERIC_DAO.getVertexByProperty(eq(uid),eq(componentId))).thenReturn(Either.left(janusGraphVertex)); result = additionalInformationOperation.updateAdditionalInformationParameter (NodeTypeEnum.Resource,componentId,"id","key","value"); assertTrue(result.isRight()); @@ -112,17 +112,17 @@ public class AdditionalInformationOperationTest extends ModelTestBase { @Test public void testDelAdditionalInfoParam_InvalidId() { - Either result; + Either result; String id = "uid"; String componentId = "componentId"; - TitanGraph graph = titanDao.getGraph().left().value(); - TitanVertex v1 = graph.addVertex(); + JanusGraph graph = janusGraphDao.getGraph().left().value(); + JanusGraphVertex v1 = graph.addVertex(); v1.property("uid", componentId); v1.property(GraphPropertiesDictionary.LABEL.getProperty(), "resource"); - TitanVertex v2 = graph.addVertex(); + JanusGraphVertex v2 = graph.addVertex(); v2.property(id,id); - TitanEdge addEdge = v1.addEdge(GraphEdgeLabels.ADDITIONAL_INFORMATION.getProperty(), v2); + JanusGraphEdge addEdge = v1.addEdge(GraphEdgeLabels.ADDITIONAL_INFORMATION.getProperty(), v2); addEdge.property("edgeProp", "resource"); graph.tx().commit(); @@ -132,18 +132,18 @@ public class AdditionalInformationOperationTest extends ModelTestBase { } private void clearGraph() { - Either graphResult = titanDao.getGraph(); - TitanGraph graph = graphResult.left().value(); + Either graphResult = janusGraphDao.getGraph(); + JanusGraph graph = graphResult.left().value(); - Iterable vertices = graph.query().vertices(); + Iterable vertices = graph.query().vertices(); if (vertices != null) { - Iterator iterator = vertices.iterator(); + Iterator iterator = vertices.iterator(); while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); + JanusGraphVertex vertex = iterator.next(); vertex.remove(); } } - titanDao.commit(); + janusGraphDao.commit(); } private UserData deleteAndCreateUser(String userId, String firstName, String lastName) { @@ -152,16 +152,16 @@ public class AdditionalInformationOperationTest extends ModelTestBase { userData.setFirstName(firstName); userData.setLastName(lastName); - titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); - titanDao.createNode(userData, UserData.class); - titanDao.commit(); + janusGraphDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); + janusGraphDao.createNode(userData, UserData.class); + janusGraphDao.commit(); return userData; } private void deleteAndCreateCategory(String category) { String[] names = category.split("/"); - OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); + OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], janusGraphDao); } } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperationsTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperationsTest.java index 9a3c66689e..24a263a89b 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperationsTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperationsTest.java @@ -5,7 +5,7 @@ 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.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.model.AnnotationTypeDefinition; import org.openecomp.sdc.be.model.ModelTestBase; import org.openecomp.sdc.be.model.PropertyDefinition; @@ -29,7 +29,7 @@ public class AnnotationTypeOperationsTest extends ModelTestBase { static final String NEW_DESCRIPTION = "new description"; @Resource - private TitanGenericDao titanGenericDao; + private JanusGraphGenericDao janusGraphGenericDao; @Resource private CommonTypeOperations commonTypeOperations; @@ -47,13 +47,13 @@ public class AnnotationTypeOperationsTest extends ModelTestBase { @Before public void initTestData() { - removeGraphVertices(titanGenericDao.getGraph()); + removeGraphVertices(janusGraphGenericDao.getGraph()); prop1 = createSimpleProperty("val1", "prop1", "string"); } @After public void tearDown() { - titanGenericDao.rollback(); + janusGraphGenericDao.rollback(); } @SuppressWarnings("unchecked") @@ -86,7 +86,7 @@ public class AnnotationTypeOperationsTest extends ModelTestBase { public void addAnnotationType() { prepareInitialType(); annotationTypeOperations.addType(initialAnnotationDefinition); - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } @Test 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 8e92549f4f..10553a0f89 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 @@ -23,18 +23,17 @@ package org.openecomp.sdc.be.model.operations.impl; 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; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; 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.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; 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.*; @@ -60,8 +59,8 @@ public class ArtifactOperationTest extends ModelTestBase { private static final String ARTIFACT_NAME = "myHeatArtifact"; - @javax.annotation.Resource(name = "titan-generic-dao") - private TitanGenericDao titanDao; + @javax.annotation.Resource(name = "janusgraph-generic-dao") + private JanusGraphGenericDao janusGraphDao; @javax.annotation.Resource(name = "tosca-operation-facade") private ToscaOperationFacade toscaOperationFacade; @@ -99,20 +98,20 @@ public class ArtifactOperationTest extends ModelTestBase { assertEquals(1, heatParameters.size()); HeatParameterDefinition parameter = heatParameters.get(0); HeatParameterData parameterData = new HeatParameterData(parameter); - Either parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + Either parameterNode = janusGraphDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); assertTrue(parameterNode.isLeft()); Either removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); assertTrue(removeArifact.isLeft()); ArtifactData artifactData = new ArtifactData(artifactWithHeat); - Either artifactAfterDelete = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + Either artifactAfterDelete = janusGraphDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); assertTrue(artifactAfterDelete.isRight()); - Either parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + Either parameterNodeAfterDelete = janusGraphDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); assertTrue(parameterNodeAfterDelete.isRight()); - titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); + janusGraphDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); } @Test @@ -125,7 +124,7 @@ public class ArtifactOperationTest extends ModelTestBase { assertEquals(1, heatParameters.size()); HeatParameterDefinition parameter = heatParameters.get(0); HeatParameterData parameterData = new HeatParameterData(parameter); - Either parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + Either parameterNode = janusGraphDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); assertTrue(parameterNode.isLeft()); // update to artifact without params @@ -139,18 +138,18 @@ public class ArtifactOperationTest extends ModelTestBase { assertTrue(updateArifact.isLeft()); ArtifactData artifactData = new ArtifactData(artifactWithHeat); - Either artifactAfterUpdate = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + Either artifactAfterUpdate = janusGraphDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); assertTrue(artifactAfterUpdate.isLeft()); ArtifactData artifactAfterUpdateValue = artifactAfterUpdate.left().value(); assertEquals(artifactNoParams.getArtifactVersion(), artifactAfterUpdateValue.getArtifactDataDefinition() .getArtifactVersion()); - Either parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + Either parameterNodeAfterDelete = janusGraphDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); assertTrue(parameterNodeAfterDelete.isRight()); artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); - titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); - titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); + janusGraphDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); + janusGraphDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); } @Test @@ -163,7 +162,7 @@ public class ArtifactOperationTest extends ModelTestBase { assertEquals(1, heatParameters.size()); HeatParameterDefinition parameter = heatParameters.get(0); HeatParameterData parameterData = new HeatParameterData(parameter); - Either parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + Either parameterNode = janusGraphDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); assertTrue(parameterNode.isLeft()); // update to artifact without params @@ -175,19 +174,19 @@ public class ArtifactOperationTest extends ModelTestBase { assertTrue(updateArifact.isLeft()); ArtifactData artifactData = new ArtifactData(artifactWithHeat); - Either artifactAfterUpdate = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + Either artifactAfterUpdate = janusGraphDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); assertTrue(artifactAfterUpdate.isLeft()); ArtifactData artifactAfterUpdateValue = artifactAfterUpdate.left().value(); assertEquals(artifactWithHeat.getArtifactVersion(), artifactAfterUpdateValue.getArtifactDataDefinition() .getArtifactVersion()); - Either parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + Either parameterNodeAfterDelete = janusGraphDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); assertTrue(parameterNodeAfterDelete.isLeft()); Either removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID_2, (String) artifactAfterUpdateValue.getUniqueId(), NodeTypeEnum.Resource, true, false); removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); - titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); - titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); + janusGraphDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); + janusGraphDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); } @@ -198,7 +197,7 @@ public class ArtifactOperationTest extends ModelTestBase { ResourceMetadataData resource2 = createResource(RESOURCE_ID_2); Map props = new HashMap<>(); props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), ArtifactGroupTypeEnum.DEPLOYMENT.name()); - Either createRelation = titanDao.createRelation(resource2, new ArtifactData(artifactWithHeat), GraphEdgeLabels.ARTIFACT_REF, props); + Either createRelation = janusGraphDao.createRelation(resource2, new ArtifactData(artifactWithHeat), GraphEdgeLabels.ARTIFACT_REF, props); assertTrue(createRelation.isLeft()); List heatParameters = artifactWithHeat.getListHeatParameters(); @@ -206,7 +205,7 @@ public class ArtifactOperationTest extends ModelTestBase { assertEquals(1, heatParameters.size()); HeatParameterDefinition parameter = heatParameters.get(0); HeatParameterData parameterData = new HeatParameterData(parameter); - Either parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + Either parameterNode = janusGraphDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); assertTrue(parameterNode.isLeft()); ArtifactDefinition atifactToUpdate = new ArtifactDefinition(artifactWithHeat); @@ -227,19 +226,19 @@ public class ArtifactOperationTest extends ModelTestBase { // verify old artifact and parameter still exist ArtifactData artifactData = new ArtifactData(artifactWithHeat); - Either origArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + Either origArtifact = janusGraphDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); assertTrue(origArtifact.isLeft()); ArtifactData origArtifactData = origArtifact.left().value(); assertEquals(artifactWithHeat.getArtifactVersion(), origArtifactData.getArtifactDataDefinition() .getArtifactVersion()); - Either parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + Either parameterNodeAfterDelete = janusGraphDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); assertTrue(parameterNodeAfterDelete.isLeft()); // verify new artifact and new parameter ArtifactDefinition artifactDefinitionUpdated = updateArifact.left().value(); ArtifactData artifactDataUpdated = new ArtifactData(artifactDefinitionUpdated); - Either updatedArtifact = titanDao.getNode(artifactDataUpdated.getUniqueIdKey(), artifactDataUpdated.getUniqueId(), ArtifactData.class); + Either updatedArtifact = janusGraphDao.getNode(artifactDataUpdated.getUniqueIdKey(), artifactDataUpdated.getUniqueId(), ArtifactData.class); assertTrue(updatedArtifact.isLeft()); ArtifactData updatedArtifactData = updatedArtifact.left().value(); assertEquals(atifactToUpdate.getArtifactVersion(), updatedArtifactData.getArtifactDataDefinition() @@ -251,7 +250,7 @@ public class ArtifactOperationTest extends ModelTestBase { assertEquals(1, heatParametersAfterUpdate.size()); HeatParameterDefinition UpdatedHeatParameter = heatParametersAfterUpdate.get(0); assertFalse(UpdatedHeatParameter.getUniqueId().equalsIgnoreCase((String) parameterData.getUniqueId())); - Either parameterNodeAfterUpdate = titanDao.getNode(new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), UpdatedHeatParameter.getUniqueId(), HeatParameterData.class); + Either parameterNodeAfterUpdate = janusGraphDao.getNode(new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), UpdatedHeatParameter.getUniqueId(), HeatParameterData.class); assertTrue(parameterNodeAfterUpdate.isLeft()); // delete new artifact @@ -259,25 +258,25 @@ public class ArtifactOperationTest extends ModelTestBase { assertTrue(removeArifact.isLeft()); // verify old artifact and parameter still exist - origArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + origArtifact = janusGraphDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); assertTrue(origArtifact.isLeft()); origArtifactData = origArtifact.left().value(); assertEquals(artifactWithHeat.getArtifactVersion(), origArtifactData.getArtifactDataDefinition() .getArtifactVersion()); - parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + parameterNodeAfterDelete = janusGraphDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); assertTrue(parameterNodeAfterDelete.isLeft()); // verify new artifact is deleted - Either artifactAfterDelete = titanDao.getNode(artifactDataUpdated.getUniqueIdKey(), artifactDataUpdated.getUniqueId(), ArtifactData.class); + Either artifactAfterDelete = janusGraphDao.getNode(artifactDataUpdated.getUniqueIdKey(), artifactDataUpdated.getUniqueId(), ArtifactData.class); assertTrue(artifactAfterDelete.isRight()); - parameterNodeAfterDelete = titanDao.getNode(new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), new HeatParameterData(UpdatedHeatParameter).getUniqueId(), HeatParameterData.class); + parameterNodeAfterDelete = janusGraphDao.getNode(new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), new HeatParameterData(UpdatedHeatParameter).getUniqueId(), HeatParameterData.class); assertTrue(parameterNodeAfterDelete.isRight()); artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); - titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); - titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); + janusGraphDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); + janusGraphDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); } private ArtifactDefinition createResourceWithHeat() { @@ -369,8 +368,8 @@ public class ArtifactOperationTest extends ModelTestBase { private void deleteAndCreateCategory(String category) { String[] names = category.split("/"); - OperationTestsUtil.deleteAndCreateServiceCategory(category, titanDao); - OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); + OperationTestsUtil.deleteAndCreateServiceCategory(category, janusGraphDao); + OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], janusGraphDao); } private UserData deleteAndCreateUser(String userId, String firstName, String lastName, String role) { @@ -384,9 +383,9 @@ public class ArtifactOperationTest extends ModelTestBase { userData.setRole("ADMIN"); } - titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); - titanDao.createNode(userData, UserData.class); - titanDao.commit(); + janusGraphDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); + janusGraphDao.createNode(userData, UserData.class); + janusGraphDao.commit(); return userData; } @@ -395,7 +394,7 @@ public class ArtifactOperationTest extends ModelTestBase { ResourceMetadataData serviceData1 = new ResourceMetadataData(); serviceData1.getMetadataDataDefinition().setUniqueId(resourceName); - Either createNode = titanDao.createNode(serviceData1, ResourceMetadataData.class); + Either createNode = janusGraphDao.createNode(serviceData1, ResourceMetadataData.class); assertTrue("check resource created", createNode.isLeft()); return createNode.left().value(); diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java index f853553911..b003c93fc1 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java @@ -25,8 +25,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import java.util.ArrayList; import java.util.HashMap; @@ -44,10 +44,9 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; -import org.openecomp.sdc.be.dao.titan.HealingTitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.ModelTestBase; @@ -62,23 +61,15 @@ import org.openecomp.sdc.be.resources.data.CapabilityTypeData; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import javax.annotation.Resource; -import java.util.*; -import java.util.Map.Entry; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.*; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context-test.xml") public class CapabilityTypeOperationTest extends ModelTestBase { - @Resource(name = "titan-generic-dao") - private HealingTitanGenericDao titanDao; + @Resource(name = "janusgraph-generic-dao") + private HealingJanusGraphGenericDao janusGraphDao; @Resource(name = "capability-type-operation") private CapabilityTypeOperation capabilityTypeOperation; @@ -90,20 +81,20 @@ public class CapabilityTypeOperationTest extends ModelTestBase { @Before public void cleanUp() { - HealingTitanGenericDao titanGenericDao = capabilityTypeOperation.titanGenericDao; - Either graphResult = titanGenericDao.getGraph(); - TitanGraph graph = graphResult.left().value(); + HealingJanusGraphGenericDao janusGraphGenericDao = capabilityTypeOperation.janusGraphGenericDao; + Either graphResult = janusGraphGenericDao.getGraph(); + JanusGraph graph = graphResult.left().value(); - Iterable vertices = graph.query().vertices(); + Iterable vertices = graph.query().vertices(); if (vertices != null) { - Iterator iterator = vertices.iterator(); + Iterator iterator = vertices.iterator(); while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); + JanusGraphVertex vertex = iterator.next(); vertex.remove(); } } - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } @Test @@ -124,7 +115,7 @@ public class CapabilityTypeOperationTest extends ModelTestBase { CapabilityTypeDefinition capabilityTypeAdded = addCapabilityType1.left().value(); compareBetweenCreatedToSent(capabilityTypeDefinition, capabilityTypeAdded); - Either capabilityTypeByUid = capabilityTypeOperation.getCapabilityTypeByUid(capabilityTypeAdded.getUniqueId()); + Either capabilityTypeByUid = capabilityTypeOperation.getCapabilityTypeByUid(capabilityTypeAdded.getUniqueId()); compareBetweenCreatedToSent(capabilityTypeByUid.left().value(), capabilityTypeDefinition); Either addCapabilityType2 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true); @@ -441,7 +432,7 @@ public class CapabilityTypeOperationTest extends ModelTestBase { } private void verifyDerivedFromNodeEqualsToRootCapabilityType(CapabilityTypeDefinition rootCapabilityType, String parentCapabilityId) { - Either, TitanOperationStatus> derivedFromRelation = titanDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), parentCapabilityId, GraphEdgeLabels.DERIVED_FROM, + Either, JanusGraphOperationStatus> derivedFromRelation = janusGraphDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), parentCapabilityId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.CapabilityType, CapabilityTypeData.class); assertThat(derivedFromRelation.left().value().getLeft().getCapabilityTypeDataDefinition()) .isEqualToComparingFieldByField(rootCapabilityType); 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 index 849a442542..029c638711 100644 --- 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 @@ -29,7 +29,7 @@ */ package org.openecomp.sdc.be.model.operations.impl; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import org.junit.Test; import org.junit.runner.RunWith; @@ -37,10 +37,9 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.HealingTitanGenericDao; -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.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInput; @@ -64,12 +63,12 @@ public class ComponentInstanceOperationTest { private ComponentInstanceOperation componentInstanceOperation; @Mock - protected HealingTitanGenericDao titanGenericDao; + protected HealingJanusGraphGenericDao janusGraphGenericDao; @Test - public void testSetTitanGenericDao() { - componentInstanceOperation.setTitanGenericDao(titanGenericDao); + public void testSetJanusGraphGenericDao() { + componentInstanceOperation.setJanusGraphGenericDao(janusGraphGenericDao); } @Test @@ -87,8 +86,8 @@ public class ComponentInstanceOperationTest { public void testUpdateCustomizationUUID() { StorageOperationStatus result; String componentInstanceId = "instanceId"; - TitanVertex titanVertex = Mockito.mock(TitanVertex.class); - when(titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(),componentInstanceId)).thenReturn(Either.left(titanVertex)); + JanusGraphVertex janusGraphVertex = Mockito.mock(JanusGraphVertex.class); + when(janusGraphGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(),componentInstanceId)).thenReturn(Either.left(janusGraphVertex)); result = componentInstanceOperation.updateCustomizationUUID(componentInstanceId); assertEquals(StorageOperationStatus.OK, result); } @@ -125,7 +124,8 @@ public class ComponentInstanceOperationTest { componentInstance.setUniqueId("INST0.1"); componentInstance.setComponentUid("RES0.1"); componentInstance.setGroupInstances(gilist); - when(titanGenericDao.updateNode(anyObject(),eq(ComponentInstanceData.class))).thenReturn(Either.right(TitanOperationStatus.GENERAL_ERROR)); + when(janusGraphGenericDao.updateNode(anyObject(),eq(ComponentInstanceData.class))).thenReturn(Either.right( + JanusGraphOperationStatus.GENERAL_ERROR)); Either result = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, NodeTypeEnum.Component,234234545L,false); assertEquals(StorageOperationStatus.GENERAL_ERROR, result.right().value()); } @@ -145,7 +145,7 @@ public class ComponentInstanceOperationTest { componentInstance.setComponentUid("RES0.1"); componentInstance.setGroupInstances(gilist); ComponentInstanceData componentInstanceData = new ComponentInstanceData(); - when(titanGenericDao.updateNode(anyObject(),eq(ComponentInstanceData.class))).thenReturn(Either.left(componentInstanceData)); + when(janusGraphGenericDao.updateNode(anyObject(),eq(ComponentInstanceData.class))).thenReturn(Either.left(componentInstanceData)); Either result = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, NodeTypeEnum.Component,234234545L,false); assertEquals(componentInstanceData, result.left().value()); } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java index 9b2a5d93c9..2c00d3d952 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java @@ -26,8 +26,8 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ArtifactType; import org.openecomp.sdc.be.model.ModelTestBase; @@ -56,8 +56,8 @@ public class ElementOperationTest extends ModelTestBase { @javax.annotation.Resource(name = "element-operation") private ElementOperation elementOperation; - @javax.annotation.Resource(name = "titan-generic-dao") - private TitanGenericDao titanDao; + @javax.annotation.Resource(name = "janusgraph-generic-dao") + private JanusGraphGenericDao janusGraphDao; private static String CATEGORY = "category"; private static String SUBCATEGORY = "subcategory"; @@ -112,7 +112,7 @@ public class ElementOperationTest extends ModelTestBase { // @Test public void testGetResourceAndServiceCategoty() { - String id = OperationTestsUtil.deleteAndCreateResourceCategory(CATEGORY, SUBCATEGORY, titanDao); + String id = OperationTestsUtil.deleteAndCreateResourceCategory(CATEGORY, SUBCATEGORY, janusGraphDao); Either res = elementOperation.getCategory(NodeTypeEnum.ResourceNewCategory, id); assertTrue(res.isLeft()); @@ -120,7 +120,7 @@ public class ElementOperationTest extends ModelTestBase { assertEquals(CATEGORY, categoryDefinition.getName()); assertEquals(SUBCATEGORY, categoryDefinition.getSubcategories().get(0).getName()); - id = OperationTestsUtil.deleteAndCreateServiceCategory(CATEGORY, titanDao); + id = OperationTestsUtil.deleteAndCreateServiceCategory(CATEGORY, janusGraphDao); res = elementOperation.getCategory(NodeTypeEnum.ServiceNewCategory, id); assertTrue(res.isLeft()); @@ -129,7 +129,7 @@ public class ElementOperationTest extends ModelTestBase { } private ElementOperation createTestSubject() { - return new ElementOperation(new TitanGenericDao(new TitanGraphClient())); + return new ElementOperation(new JanusGraphGenericDao(new JanusGraphClient())); } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperationTest.java index 0f8e294459..8e1e5d3d04 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperationTest.java @@ -1,7 +1,7 @@ package org.openecomp.sdc.be.model.operations.impl; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Edge; @@ -10,11 +10,10 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.HealingTitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.GroupTypeDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.*; @@ -44,8 +43,8 @@ public class GroupTypeOperationTest extends ModelTestBase { private static final String TOSCA_GROUPS_ROOT = "tosca.groups.Root"; private static final String NULL_STRING = null; - @Resource(name = "titan-generic-dao") - private HealingTitanGenericDao titanDao; + @Resource(name = "janusgraph-generic-dao") + private HealingJanusGraphGenericDao janusGraphDao; @Resource(name = "capability-type-operation") private CapabilityTypeOperation capabilityTypeOperation; @@ -60,7 +59,7 @@ public class GroupTypeOperationTest extends ModelTestBase { @After public void tearDown() { - titanDao.rollback(); + janusGraphDao.rollback(); cleanUp(); } @@ -120,10 +119,12 @@ public class GroupTypeOperationTest extends ModelTestBase { assertTrue("check group type added", addGroupTypeResult.isLeft()); compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value()); - Either groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class); + Either groupTypeResult = janusGraphDao + .getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class); GroupTypeData groupTypeNode = extractVal(groupTypeResult); - Either edgeResult = titanDao.getEdgeByNodes(groupTypeNode, rootNode, GraphEdgeLabels.DERIVED_FROM); + Either edgeResult = janusGraphDao + .getEdgeByNodes(groupTypeNode, rootNode, GraphEdgeLabels.DERIVED_FROM); validate(edgeResult); } @@ -132,7 +133,8 @@ public class GroupTypeOperationTest extends ModelTestBase { getOrCreateRootGroupTypeNode(); CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(null); - Either capabilityTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); + Either capabilityTypeResult = janusGraphDao + .getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); extractVal(capabilityTypeResult); GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); @@ -171,7 +173,8 @@ public class GroupTypeOperationTest extends ModelTestBase { buildProperty("vfc_instance_group_reference", null, "Ability to recognize capability per vfc instance group on vnf instance")); CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(capTypeProperties); - Either capabilityTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); + Either capabilityTypeResult = janusGraphDao + .getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); extractVal(capabilityTypeResult); GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); @@ -199,7 +202,8 @@ public class GroupTypeOperationTest extends ModelTestBase { assertTrue("check group type added", addGroupTypeResult.isLeft()); compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value()); - Either groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class); + Either groupTypeResult = janusGraphDao + .getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class); GroupTypeData groupTypeNode = extractVal(groupTypeResult); Either groupTypeDefResult = groupTypeOperation.getGroupTypeByUid(groupTypeNode.getUniqueId()); @@ -213,7 +217,8 @@ public class GroupTypeOperationTest extends ModelTestBase { CapabilityDefinition updatedCapabilityDef = capabilityDefs.get("vlan_assignment"); assertEquals(2, updatedCapabilityDef.getProperties().size()); - Either edgeDerivedFromResult = titanDao.getEdgeByNodes(groupTypeNode, rootNode, GraphEdgeLabels.DERIVED_FROM); + Either edgeDerivedFromResult = janusGraphDao + .getEdgeByNodes(groupTypeNode, rootNode, GraphEdgeLabels.DERIVED_FROM); validate(edgeDerivedFromResult); } @@ -226,7 +231,8 @@ public class GroupTypeOperationTest extends ModelTestBase { Map capTypeProperties = new HashMap<>(); capTypeProperties.put("vfc_instance_group_reference", property); CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(capTypeProperties); - Either capabilityTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); + Either capabilityTypeResult = janusGraphDao + .getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); extractVal(capabilityTypeResult); GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); @@ -254,7 +260,8 @@ public class GroupTypeOperationTest extends ModelTestBase { assertTrue("check group type added", addGroupTypeResult.isLeft()); compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value()); - Either groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class); + Either groupTypeResult = janusGraphDao + .getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class); GroupTypeData groupTypeNode = extractVal(groupTypeResult); Either groupTypeDefResult = groupTypeOperation.getGroupTypeByUid(groupTypeNode.getUniqueId()); @@ -281,7 +288,8 @@ public class GroupTypeOperationTest extends ModelTestBase { Map capTypeProperties = new HashMap<>(); capTypeProperties.put("vfc_instance_group_reference", property); CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(capTypeProperties); - Either capabilityTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); + Either capabilityTypeResult = janusGraphDao + .getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); extractVal(capabilityTypeResult); GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); @@ -317,7 +325,8 @@ public class GroupTypeOperationTest extends ModelTestBase { Map capTypeProperties = new HashMap<>(); capTypeProperties.put("vfc_instance_group_reference", property); CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(capTypeProperties); - Either capabilityTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); + Either capabilityTypeResult = janusGraphDao + .getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); extractVal(capabilityTypeResult); GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); @@ -362,7 +371,8 @@ public class GroupTypeOperationTest extends ModelTestBase { Map capTypeProperties = new HashMap<>(); capTypeProperties.put("vfc_instance_group_reference", property); CapabilityTypeDefinition capabilityTypeDef = createCapabilityType(capTypeProperties); - Either capabilityTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); + Either capabilityTypeResult = janusGraphDao + .getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class); extractVal(capabilityTypeResult); GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(); @@ -501,7 +511,8 @@ public class GroupTypeOperationTest extends ModelTestBase { private GroupTypeData getOrCreateRootGroupTypeNode() { - Either groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), TOSCA_GROUPS_ROOT, GroupTypeData.class); + Either groupTypeResult = janusGraphDao + .getNode(GraphPropertiesDictionary.TYPE.getProperty(), TOSCA_GROUPS_ROOT, GroupTypeData.class); if(groupTypeResult.isLeft()) { return groupTypeResult.left().value(); } @@ -514,7 +525,8 @@ public class GroupTypeOperationTest extends ModelTestBase { Either addGroupTypeResult = groupTypeOperation.addGroupType(rootGroupDefinition, false); assertTrue("check group type added", addGroupTypeResult.isLeft()); - Either groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), rootGroupDefinition.getType(), GroupTypeData.class); + Either groupTypeResult = janusGraphDao + .getNode(GraphPropertiesDictionary.TYPE.getProperty(), rootGroupDefinition.getType(), GroupTypeData.class); return extractVal(groupTypeResult); } @@ -603,11 +615,11 @@ public class GroupTypeOperationTest extends ModelTestBase { assertEquals(expected.getDescription(), actual.getDescription()); } - private void validate(Either result) { + private void validate(Either result) { extractVal(result); } - private T extractVal(Either result) { + private T extractVal(Either result) { assertTrue(result.isLeft()); T t = result.left().value(); assertNotNull(t); @@ -616,19 +628,19 @@ public class GroupTypeOperationTest extends ModelTestBase { } private void cleanUp() { - Either graphResult = titanDao.getGraph(); - TitanGraph graph = graphResult.left().value(); + Either graphResult = janusGraphDao.getGraph(); + JanusGraph graph = graphResult.left().value(); - Iterable vertices = graph.query().vertices(); + Iterable vertices = graph.query().vertices(); if (vertices != null) { - Iterator iterator = vertices.iterator(); + Iterator iterator = vertices.iterator(); while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); + JanusGraphVertex vertex = iterator.next(); vertex.remove(); } } - titanDao.commit(); + janusGraphDao.commit(); } @@ -764,17 +776,19 @@ public class GroupTypeOperationTest extends ModelTestBase { } private void verifyDerivedFromNodeEqualsToRootGroupType(GroupTypeDefinition rootGroupType, String parentGroupId) { - Either, TitanOperationStatus> derivedFromRelation = titanDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), parentGroupId, GraphEdgeLabels.DERIVED_FROM, + Either, JanusGraphOperationStatus> derivedFromRelation = janusGraphDao + .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), parentGroupId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.GroupType, GroupTypeData.class); assertThat(derivedFromRelation.left().value().getLeft().getGroupTypeDataDefinition()) .isEqualToComparingFieldByField(rootGroupType); } private void verifyDerivedFromRelationDoesntExist(String parentGroupId) { - Either, TitanOperationStatus> derivedFromRelation = titanDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), parentGroupId, GraphEdgeLabels.DERIVED_FROM, + Either, JanusGraphOperationStatus> derivedFromRelation = janusGraphDao + .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), parentGroupId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.GroupType, GroupTypeData.class); assertThat(derivedFromRelation.right().value()) - .isEqualTo(TitanOperationStatus.NOT_FOUND); + .isEqualTo(JanusGraphOperationStatus.NOT_FOUND); } private GroupTypeDefinition createGroupTypeDef() { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java index 61504db727..958f7c878b 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java @@ -26,9 +26,9 @@ import org.junit.Test; import org.mockito.Mockito; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; 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.HeatParameterDefinition; import org.openecomp.sdc.be.model.ModelTestBase; @@ -48,11 +48,11 @@ public class HeatParametersOperationTest extends ModelTestBase { HeatParametersOperation heatParametersOperation = new HeatParametersOperation(); - TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + JanusGraphGenericDao janusGraphGenericDao = Mockito.mock(JanusGraphGenericDao.class); @Before public void setup() { - heatParametersOperation.setTitanGenericDao(titanGenericDao); + heatParametersOperation.setJanusGraphGenericDao(janusGraphGenericDao); } @@ -64,15 +64,15 @@ public class HeatParametersOperationTest extends ModelTestBase { HeatParameterData propertyData = new HeatParameterData(property); - Either either = Either.left(propertyData); + Either either = Either.left(propertyData); GraphRelation graphRelation = new GraphRelation(); - Either relationResult = Either.left(graphRelation); + Either relationResult = Either.left(graphRelation); - when(titanGenericDao.createNode(any(HeatParameterData.class), eq(HeatParameterData.class))).thenReturn(either); - when(titanGenericDao.createRelation(any(GraphNode.class), any(GraphNode.class), eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult); + when(janusGraphGenericDao.createNode(any(HeatParameterData.class), eq(HeatParameterData.class))).thenReturn(either); + when(janusGraphGenericDao.createRelation(any(GraphNode.class), any(GraphNode.class), eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult); - Either result = heatParametersOperation.addPropertyToGraph(propName, property, "resourceId.artifactId", NodeTypeEnum.ArtifactRef); + Either result = heatParametersOperation.addPropertyToGraph(propName, property, "resourceId.artifactId", NodeTypeEnum.ArtifactRef); assertTrue(result.isLeft()); @@ -91,13 +91,13 @@ public class HeatParametersOperationTest extends ModelTestBase { HeatParameterData propertyData = new HeatParameterData(property); - Either either = Either.left(propertyData); + Either either = Either.left(propertyData); GraphRelation graphRelation = new GraphRelation(); - Either relationResult = Either.left(graphRelation); + Either relationResult = Either.left(graphRelation); - when(titanGenericDao.createNode(any(HeatParameterData.class), eq(HeatParameterData.class))).thenReturn(either); - when(titanGenericDao.createRelation(any(GraphNode.class), any(GraphNode.class), eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult); + when(janusGraphGenericDao.createNode(any(HeatParameterData.class), eq(HeatParameterData.class))).thenReturn(either); + when(janusGraphGenericDao.createRelation(any(GraphNode.class), any(GraphNode.class), eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult); StorageOperationStatus result = heatParametersOperation.addPropertiesToGraph(parameters, "resourceId.artifactId", NodeTypeEnum.ArtifactRef); @@ -222,16 +222,16 @@ public class HeatParametersOperationTest extends ModelTestBase { propertyData.setUniqueId("bla"); propertyData.setValue("value1"); - Either either = Either.left(propertyData); + Either either = Either.left(propertyData); GraphRelation graphRelation = new GraphRelation(); - Either relationResult = Either.left(graphRelation); + Either relationResult = Either.left(graphRelation); - when(titanGenericDao.createNode(any(HeatParameterValueData.class), eq(HeatParameterValueData.class))).thenReturn(either); - when(titanGenericDao.createRelation(any(GraphNode.class), any(GraphNode.class), eq(GraphEdgeLabels.PARAMETER_VALUE), anyMap())).thenReturn(relationResult); - when(titanGenericDao.createRelation(any(GraphNode.class), any(GraphNode.class), eq(GraphEdgeLabels.PARAMETER_IMPL), isNull())).thenReturn(relationResult); + when(janusGraphGenericDao.createNode(any(HeatParameterValueData.class), eq(HeatParameterValueData.class))).thenReturn(either); + when(janusGraphGenericDao.createRelation(any(GraphNode.class), any(GraphNode.class), eq(GraphEdgeLabels.PARAMETER_VALUE), anyMap())).thenReturn(relationResult); + when(janusGraphGenericDao.createRelation(any(GraphNode.class), any(GraphNode.class), eq(GraphEdgeLabels.PARAMETER_IMPL), isNull())).thenReturn(relationResult); - Either result = heatParametersOperation.addHeatValueToGraph(property, "artifactLabel", "resourceInstanceId.artifactId", "resourceInstanceId"); + Either result = heatParametersOperation.addHeatValueToGraph(property, "artifactLabel", "resourceInstanceId.artifactId", "resourceInstanceId"); assertTrue(result.isLeft()); diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperationTest.java index 3e8b087fb2..532e76bba8 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperationTest.java @@ -33,8 +33,8 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; 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.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; @@ -72,7 +72,7 @@ public class InterfaceLifecycleOperationTest { private static String USER_ID = "muUserId"; private static String CATEGORY_NAME = "category/mycategory"; - TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + JanusGraphGenericDao janusGraphGenericDao = Mockito.mock(JanusGraphGenericDao.class); @InjectMocks private InterfaceLifecycleOperation interfaceLifecycleOperation = new InterfaceLifecycleOperation(); @@ -87,7 +87,7 @@ public class InterfaceLifecycleOperationTest { MockitoAnnotations.initMocks(this); final String UNIQUE_ID = "UNIQUE_ID"; CategoryData categoryData = new CategoryData(NodeTypeEnum.ResourceCategory); - when(titanGenericDao.createNode(any(),any())).thenReturn(Either.left(categoryData)); + when(janusGraphGenericDao.createNode(any(),any())).thenReturn(Either.left(categoryData)); deleteAndCreateCategory(CATEGORY_NAME); deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID); } @@ -124,7 +124,7 @@ public class InterfaceLifecycleOperationTest { String reqRelationship = "myrelationship"; ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + resourceOperationTest.setOperations(janusGraphDao, resourceOperation, propertyOperation); Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "100.0", null, true, true); @@ -161,7 +161,7 @@ public class InterfaceLifecycleOperationTest { String softwareCompName = "tosca.nodes.SoftwareComponent"; ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); - resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + resourceOperationTest.setOperations(janusGraphDao, resourceOperation, propertyOperation); Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "200.0", null, true, true); @@ -178,7 +178,7 @@ public class InterfaceLifecycleOperationTest { ResourceMetadataData resourceData = new ResourceMetadataData(); resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); - Either updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); + Either updateNode = janusGraphDao.updateNode(resourceData, ResourceMetadataData.class); assertTrue(updateNode.isLeft()); Either fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId()); @@ -198,7 +198,7 @@ public class InterfaceLifecycleOperationTest { Either opResult = interfaceOperation.updateInterfaceOperation(softwareComponent.getUniqueId(), "standard", "create", op); // PrintGraph pg = new PrintGraph(); - // System.out.println(pg.buildGraphForWebgraphWiz(titanDao.getGraph().left().value())); + // System.out.println(pg.buildGraphForWebgraphWiz(janusGraphDao.getGraph().left().value())); assertTrue(opResult.isLeft()); log.debug("{}", opResult.left().value()); @@ -247,12 +247,12 @@ public class InterfaceLifecycleOperationTest { private void deleteAndCreateCategory(String category) { String[] names = category.split("/"); - OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanGenericDao); + OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], janusGraphGenericDao); /* * 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); + * janusGraphDao.deleteNode(categoryData, CategoryData.class); Either createNode = janusGraphDao .createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode); */ } @@ -263,18 +263,18 @@ public class InterfaceLifecycleOperationTest { userData.setFirstName(firstName); userData.setLastName(lastName); - titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, + janusGraphGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); - titanGenericDao.createNode(userData, UserData.class); - titanGenericDao.commit(); + janusGraphGenericDao.createNode(userData, UserData.class); + janusGraphGenericDao.commit(); return userData; } @Test public void testGetAllInterfaceLifecycleTypes_TypesNotFound() { - when(titanGenericDao.getByCriteria(NodeTypeEnum.Interface, Collections.emptyMap(), - InterfaceData.class)).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); + when(janusGraphGenericDao.getByCriteria(NodeTypeEnum.Interface, Collections.emptyMap(), + InterfaceData.class)).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)); Either, StorageOperationStatus> types = interfaceLifecycleOperation.getAllInterfaceLifecycleTypes(); Assert.assertEquals(types.isRight(), Boolean.TRUE); } @@ -288,12 +288,13 @@ public class InterfaceLifecycleOperationTest { interfaceData.getInterfaceDataDefinition().setType(TYPE); List interfaceDataList = new ArrayList<>(); interfaceDataList.add(interfaceData); - Either, TitanOperationStatus> allInterfaceTypes = Either.left(interfaceDataList); - when(titanGenericDao.getByCriteria(NodeTypeEnum.Interface, Collections.emptyMap(), InterfaceData.class)).thenReturn(allInterfaceTypes); + Either, JanusGraphOperationStatus> allInterfaceTypes = Either.left(interfaceDataList); + when(janusGraphGenericDao + .getByCriteria(NodeTypeEnum.Interface, Collections.emptyMap(), InterfaceData.class)).thenReturn(allInterfaceTypes); List> list = new ArrayList<>(); - Either>, TitanOperationStatus> childrenNodes = Either.left(list); - when(titanGenericDao.getChildrenNodes(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class)).thenReturn(childrenNodes); + Either>, JanusGraphOperationStatus> childrenNodes = Either.left(list); + when(janusGraphGenericDao.getChildrenNodes(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class)).thenReturn(childrenNodes); Either, StorageOperationStatus> types = interfaceLifecycleOperation.getAllInterfaceLifecycleTypes(); Assert.assertEquals(types.left().value().size(),1); diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java index ef1025f77e..f5197f05c5 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java @@ -26,8 +26,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import java.util.Iterator; import java.util.List; @@ -39,10 +39,10 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; -import org.openecomp.sdc.be.dao.titan.HealingTitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; import org.openecomp.sdc.be.datatypes.elements.PolicyTypeDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ModelTestBase; @@ -64,7 +64,7 @@ public class PolicyTypeOperationTest extends ModelTestBase { private PolicyTypeOperation policyTypeOperation; @Autowired - private HealingTitanGenericDao titanGenericDao; + private HealingJanusGraphGenericDao janusGraphGenericDao; @BeforeClass public static void setupBeforeClass() { @@ -74,20 +74,20 @@ public class PolicyTypeOperationTest extends ModelTestBase { @Before public void cleanUp() { - TitanGenericDao titanGenericDao = policyTypeOperation.titanGenericDao; - Either graphResult = titanGenericDao.getGraph(); - TitanGraph graph = graphResult.left().value(); + JanusGraphGenericDao janusGraphGenericDao = policyTypeOperation.janusGraphGenericDao; + Either graphResult = janusGraphGenericDao.getGraph(); + JanusGraph graph = graphResult.left().value(); - Iterable vertices = graph.query().vertices(); + Iterable vertices = graph.query().vertices(); if (vertices != null) { - Iterator iterator = vertices.iterator(); + Iterator iterator = vertices.iterator(); while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); + JanusGraphVertex vertex = iterator.next(); vertex.remove(); } } - titanGenericDao.commit(); + janusGraphGenericDao.commit(); } @Test @@ -310,17 +310,17 @@ public class PolicyTypeOperationTest extends ModelTestBase { } private void verifyDerivedFromNodeEqualsToRootPolicyType(PolicyTypeDefinition rootPolicyType, String parentPolicyId) { - Either, TitanOperationStatus> derivedFromRelation = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), parentPolicyId, GraphEdgeLabels.DERIVED_FROM, + Either, JanusGraphOperationStatus> derivedFromRelation = janusGraphGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), parentPolicyId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.PolicyType, PolicyTypeData.class); assertThat(derivedFromRelation.left().value().getLeft().getPolicyTypeDataDefinition()) .isEqualToComparingFieldByField(rootPolicyType); } private void verifyDerivedFromRelationDoesntExist(String parentPolicyId) { - Either, TitanOperationStatus> derivedFromRelation = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), parentPolicyId, GraphEdgeLabels.DERIVED_FROM, + Either, JanusGraphOperationStatus> derivedFromRelation = janusGraphGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), parentPolicyId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.PolicyType, PolicyTypeData.class); assertThat(derivedFromRelation.right().value()) - .isEqualTo(TitanOperationStatus.NOT_FOUND); + .isEqualTo(JanusGraphOperationStatus.NOT_FOUND); } private PolicyTypeDefinition createRootPolicyTypeOnGraph() { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java index ae428bdaff..8535c3a9f3 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java @@ -20,17 +20,17 @@ package org.openecomp.sdc.be.model.operations.impl; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; -import org.openecomp.sdc.be.dao.titan.HealingTitanGenericDao; -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.dao.janusgraph.HealingJanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -51,13 +51,13 @@ import static org.junit.Assert.*; public class PropertyOperationTest extends ModelTestBase { - HealingTitanGenericDao titanGenericDao = Mockito.mock(HealingTitanGenericDao.class); + HealingJanusGraphGenericDao janusGraphGenericDao = Mockito.mock(HealingJanusGraphGenericDao.class); - PropertyOperation propertyOperation = new PropertyOperation(titanGenericDao, null); + PropertyOperation propertyOperation = new PropertyOperation(janusGraphGenericDao, null); @Before public void setup() { - propertyOperation.setTitanGenericDao(titanGenericDao); + propertyOperation.setJanusGraphGenericDao(janusGraphGenericDao); } @@ -68,10 +68,10 @@ public class PropertyOperationTest extends ModelTestBase { * * PropertyData propertyData = new PropertyData(property, propertyOperation.convertConstraintsToString(constraints)); * - * Either either = Either.left(propertyData); //when(propertyDao.create((GraphNeighbourTable)anyObject(), eq(PropertyData.class), eq(NodeTypeEnum.Property))).thenReturn(either); GraphRelation graphRelation = - * new GraphRelation(); Either relationResult = Either.left(graphRelation); + * Either either = Either.left(propertyData); //when(propertyDao.create((GraphNeighbourTable)anyObject(), eq(PropertyData.class), eq(NodeTypeEnum.Property))).thenReturn(either); GraphRelation graphRelation = + * new GraphRelation(); Either relationResult = Either.left(graphRelation); * - * when(titanGenericDao.createNode((PropertyData)anyObject(), eq(PropertyData.class))).thenReturn(either); when(titanGenericDao.createRelation((GraphNode)anyObject(), (GraphNode)anyObject(), eq(GraphEdgeLabels.PROPERTY), + * when(janusGraphGenericDao.createNode((PropertyData)anyObject(), eq(PropertyData.class))).thenReturn(either); when(janusGraphGenericDao.createRelation((GraphNode)anyObject(), (GraphNode)anyObject(), eq(GraphEdgeLabels.PROPERTY), * anyMap())).thenReturn(relationResult); * * Either result = propertyOperation.addPropertyToResource(propName, property, NodeTypeEnum.Resource, "my-resource.1.0"); @@ -512,7 +512,7 @@ public class PropertyOperationTest extends ModelTestBase { } private PropertyOperation createTestSubject() { - return new PropertyOperation(new HealingTitanGenericDao(new TitanGraphClient()), null); + return new PropertyOperation(new HealingJanusGraphGenericDao(new JanusGraphClient()), null); } @@ -572,7 +572,7 @@ public class PropertyOperationTest extends ModelTestBase { String propertyName = ""; PropertyDefinition propertyDefinition = new PropertyDefinition(); String resourceId = ""; - Either result; + Either result; // default test testSubject = createTestSubject(); @@ -583,11 +583,11 @@ public class PropertyOperationTest extends ModelTestBase { @Test public void testAddPropertyToGraphByVertex() throws Exception { PropertyOperation testSubject; - TitanVertex metadataVertex = null; + JanusGraphVertex metadataVertex = null; String propertyName = ""; PropertyDefinition propertyDefinition = new PropertyDefinition(); String resourceId = ""; - TitanOperationStatus result; + JanusGraphOperationStatus result; // default test testSubject = createTestSubject(); @@ -596,20 +596,20 @@ public class PropertyOperationTest extends ModelTestBase { @Test - public void testGetTitanGenericDao() throws Exception { + public void testGetJanusGraphGenericDao() throws Exception { PropertyOperation testSubject; - TitanGenericDao result; + JanusGraphGenericDao result; // default test testSubject = createTestSubject(); - result = testSubject.getTitanGenericDao(); + result = testSubject.getJanusGraphGenericDao(); } @Test public void testDeletePropertyFromGraph() throws Exception { PropertyOperation testSubject; String propertyId = ""; - Either result; + Either result; // default test testSubject = createTestSubject(); @@ -636,7 +636,7 @@ public class PropertyOperationTest extends ModelTestBase { PropertyOperation testSubject; String propertyId = ""; PropertyDefinition propertyDefinition = null; - Either result; + Either result; // default test testSubject = createTestSubject(); @@ -645,14 +645,14 @@ public class PropertyOperationTest extends ModelTestBase { @Test - public void testSetTitanGenericDao() { + public void testSetJanusGraphGenericDao() { PropertyOperation testSubject; - HealingTitanGenericDao titanGenericDao = null; + HealingJanusGraphGenericDao janusGraphGenericDao = null; // default test testSubject = createTestSubject(); - testSubject.setTitanGenericDao(titanGenericDao); + testSubject.setJanusGraphGenericDao(janusGraphGenericDao); } @@ -663,7 +663,7 @@ public class PropertyOperationTest extends ModelTestBase { PropertyDefinition propertyDefinition = new PropertyDefinition(); NodeTypeEnum nodeType = NodeTypeEnum.Attribute; String uniqueId = ""; - Either result; + Either result; // default test testSubject = createTestSubject(); @@ -676,7 +676,7 @@ public class PropertyOperationTest extends ModelTestBase { PropertyOperation testSubject; NodeTypeEnum nodeType = null; String uniqueId = ""; - Either, TitanOperationStatus> result; + Either, JanusGraphOperationStatus> result; // default test testSubject = createTestSubject(); @@ -760,7 +760,7 @@ public class PropertyOperationTest extends ModelTestBase { PropertyOperation testSubject; String resourceInstanceId = ""; String propertyId = ""; - ImmutablePair result; + ImmutablePair result; // default test testSubject = createTestSubject(); @@ -785,7 +785,7 @@ public class PropertyOperationTest extends ModelTestBase { public void testGetAllPropertiesOfResourceInstanceOnlyPropertyDefId() throws Exception { PropertyOperation testSubject; String resourceInstanceUid = ""; - Either, TitanOperationStatus> result; + Either, JanusGraphOperationStatus> result; // default test testSubject = createTestSubject(); @@ -798,7 +798,7 @@ public class PropertyOperationTest extends ModelTestBase { PropertyOperation testSubject; String propertyValueUid = ""; String resourceInstanceId = ""; - Either result; + Either result; // default test testSubject = createTestSubject(); @@ -882,7 +882,7 @@ public class PropertyOperationTest extends ModelTestBase { PropertyOperation testSubject; String resourceInstanceUid = ""; NodeTypeEnum instanceNodeType = null; - Either, TitanOperationStatus> result; + Either, JanusGraphOperationStatus> result; // default test testSubject = createTestSubject(); @@ -896,7 +896,7 @@ public class PropertyOperationTest extends ModelTestBase { List pathOfComponentInstances = null; String propertyUniqueId = ""; String defaultValue = ""; - Either result; + Either result; // test 1 testSubject = createTestSubject(); @@ -927,7 +927,7 @@ public class PropertyOperationTest extends ModelTestBase { public void testGetDataTypeByUid() throws Exception { PropertyOperation testSubject; String uniqueId = ""; - Either result; + Either result; // default test testSubject = createTestSubject(); @@ -988,7 +988,7 @@ public class PropertyOperationTest extends ModelTestBase { public void testGetDataTypeByUidWithoutDerivedDataTypes() throws Exception { PropertyOperation testSubject; String uniqueId = ""; - Either result; + Either result; // default test testSubject = createTestSubject(); @@ -1000,7 +1000,7 @@ public class PropertyOperationTest extends ModelTestBase { public void testIsDefinedInDataTypes() throws Exception { PropertyOperation testSubject; String propertyType = ""; - Either result; + Either result; // default test testSubject = createTestSubject(); @@ -1011,7 +1011,7 @@ public class PropertyOperationTest extends ModelTestBase { @Test public void testGetAllDataTypes() throws Exception { PropertyOperation testSubject; - Either, TitanOperationStatus> result; + Either, JanusGraphOperationStatus> result; // default test testSubject = createTestSubject(); @@ -1023,7 +1023,7 @@ public class PropertyOperationTest extends ModelTestBase { public void testCheckInnerType() throws Exception { PropertyOperation testSubject; PropertyDataDefinition propDataDef = new PropertyDataDefinition(); - Either result; + Either result; // default test testSubject = createTestSubject(); @@ -1034,7 +1034,7 @@ public class PropertyOperationTest extends ModelTestBase { @Test public void testGetAllDataTypeNodes() throws Exception { PropertyOperation testSubject; - Either, TitanOperationStatus> result; + Either, JanusGraphOperationStatus> result; // default test testSubject = createTestSubject(); @@ -1083,7 +1083,7 @@ public class PropertyOperationTest extends ModelTestBase { String uniqueId = ""; NodeTypeEnum elementType = null; List properties = null; - Either, TitanOperationStatus> result; + Either, JanusGraphOperationStatus> result; // test 1 testSubject = createTestSubject(); diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RelationshipTypeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RelationshipTypeOperationTest.java index 3d60a650f3..30463e9982 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RelationshipTypeOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RelationshipTypeOperationTest.java @@ -44,9 +44,8 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; -import org.openecomp.sdc.be.dao.titan.HealingTitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ModelTestBase; @@ -70,7 +69,7 @@ public class RelationshipTypeOperationTest extends ModelTestBase { private static final String PROP = "prop"; @Mock - HealingTitanGenericDao titanGenericDao; + HealingJanusGraphGenericDao janusGraphGenericDao; @Mock PropertyOperation propertyOperation; @@ -101,16 +100,16 @@ public class RelationshipTypeOperationTest extends ModelTestBase { public void setUp() throws Exception { MockitoAnnotations.initMocks(this); - Mockito.doReturn(TitanOperationStatus.OK).when(titanGenericDao).commit(); - Mockito.doReturn(TitanOperationStatus.OK).when(titanGenericDao).rollback(); + Mockito.doReturn(JanusGraphOperationStatus.OK).when(janusGraphGenericDao).commit(); + Mockito.doReturn(JanusGraphOperationStatus.OK).when(janusGraphGenericDao).rollback(); } @Test public void getRelationshipTypeByNameNotCreated() { - Mockito.doReturn(Either.right(TitanOperationStatus.NOT_CREATED)) + Mockito.doReturn(Either.right(JanusGraphOperationStatus.NOT_CREATED)) .when(relationshipTypeOperation).getRelationshipTypeByUid(Mockito.anyString()); - Either either = + Either either = relationshipTypeOperation.getRelationshipTypeByName("name"); assertTrue(either.isRight()); } @@ -122,7 +121,7 @@ public class RelationshipTypeOperationTest extends ModelTestBase { @Test public void testAddRelationshipTypeValidationFailStatusNullInTransactionFalse() { - Mockito.doReturn(Either.right(TitanOperationStatus.NOT_CONNECTED)) + Mockito.doReturn(Either.right(JanusGraphOperationStatus.NOT_CONNECTED)) .when(propertyOperation) .getAllTypePropertiesFromAllDerivedFrom(Mockito.anyString(), Mockito.any(), Mockito.any()); @@ -137,7 +136,7 @@ public class RelationshipTypeOperationTest extends ModelTestBase { public void testAddRelationshipTypeValidationFailStatusPropertiesReturnedInTransactionFalse() { Mockito.doReturn(Either.left(Collections.singletonMap("prop1", new PropertyDefinition()))).when(propertyOperation) .getAllTypePropertiesFromAllDerivedFrom(Mockito.anyString(), Mockito.any(), Mockito.any()); - Mockito.doReturn(Either.right(TitanOperationStatus.NOT_FOUND)).when(propertyOperation) + Mockito.doReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)).when(propertyOperation) .validatePropertiesUniqueness(Mockito.any(), Mockito.any()); Either addRelationshipType = @@ -148,20 +147,22 @@ public class RelationshipTypeOperationTest extends ModelTestBase { @Test public void testGetAllRelationshipTypesNotFound() { - Mockito.doReturn(Either.right(TitanOperationStatus.NOT_FOUND)).when(titanGenericDao).getByCriteria(NodeTypeEnum.RelationshipType, null, + Mockito.doReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND)).when( + janusGraphGenericDao).getByCriteria(NodeTypeEnum.RelationshipType, null, RelationshipTypeData.class); - Either, TitanOperationStatus> either = relationshipTypeOperation.getAllRelationshipTypes(); + Either, JanusGraphOperationStatus> either = relationshipTypeOperation.getAllRelationshipTypes(); assertTrue(either.isLeft() && MapUtils.isEmpty(either.left().value())); } @Test public void testGetAllRelationshipTypesNotConnnected() { - Mockito.doReturn(Either.right(TitanOperationStatus.NOT_CONNECTED)).when(titanGenericDao).getByCriteria(NodeTypeEnum.RelationshipType, null, + Mockito.doReturn(Either.right(JanusGraphOperationStatus.NOT_CONNECTED)).when( + janusGraphGenericDao).getByCriteria(NodeTypeEnum.RelationshipType, null, RelationshipTypeData.class); - Either, TitanOperationStatus> either = relationshipTypeOperation.getAllRelationshipTypes(); + Either, JanusGraphOperationStatus> either = relationshipTypeOperation.getAllRelationshipTypes(); - assertTrue(either.isRight() && TitanOperationStatus.NOT_CONNECTED == either.right().value()); + assertTrue(either.isRight() && JanusGraphOperationStatus.NOT_CONNECTED == either.right().value()); } @Test @@ -177,10 +178,10 @@ public class RelationshipTypeOperationTest extends ModelTestBase { relationshipTypeDataList.add(relationshipTypeData1); Mockito.doReturn(Either.left(relationshipTypeDataList)) - .when(titanGenericDao).getByCriteria(NodeTypeEnum.RelationshipType, null, + .when(janusGraphGenericDao).getByCriteria(NodeTypeEnum.RelationshipType, null, RelationshipTypeData.class); - Mockito.doReturn(Either.left(relationshipTypeData1)).when(titanGenericDao) + Mockito.doReturn(Either.left(relationshipTypeData1)).when(janusGraphGenericDao) .getNode(Mockito.anyString(), Mockito.anyString(), Mockito.eq(RelationshipTypeData.class)); Mockito.doReturn(Either.left(createPropertyData("prop1"))).when(propertyOperation) @@ -194,7 +195,7 @@ public class RelationshipTypeOperationTest extends ModelTestBase { .when(derivedFromOperation) .getDerivedFromChild("tosca.relationships.Root1", NodeTypeEnum.RelationshipType, RelationshipTypeData.class); - Either, TitanOperationStatus> either = + Either, JanusGraphOperationStatus> either = relationshipTypeOperation.getAllRelationshipTypes(); assertTrue(either.isLeft()); @@ -352,7 +353,7 @@ public class RelationshipTypeOperationTest extends ModelTestBase { Mockito.doReturn(Either.left(new ArrayList<>(relationshipTypeDefinition.getProperties().values()))).when(propertyOperation) .validatePropertiesUniqueness(Mockito.any(), Mockito.any()); - Mockito.doReturn(Either.left(relationshipTypeData)).when(titanGenericDao) + Mockito.doReturn(Either.left(relationshipTypeData)).when(janusGraphGenericDao) .createNode(Mockito.any(), Mockito.eq(RelationshipTypeData.class)); Mockito.doReturn(Either.left(new HashMap())).when(propertyOperation) @@ -376,7 +377,7 @@ public class RelationshipTypeOperationTest extends ModelTestBase { @Test public void testGetRelationshipTypeNotConnected() { - Mockito.doReturn(Either.right(TitanOperationStatus.NOT_CONNECTED)) + Mockito.doReturn(Either.right(JanusGraphOperationStatus.NOT_CONNECTED)) .when(relationshipTypeOperation).getRelationshipTypeByUid(Mockito.anyString()); Either either = @@ -405,7 +406,8 @@ public class RelationshipTypeOperationTest extends ModelTestBase { newRelationshipTypeDefinition.setDerivedFrom("tosca.relationships.Root"); newRelationshipTypeDefinition.setProperties(createPropertyData("prop1")); - Mockito.doReturn(Either.left(new RelationshipTypeData(newRelationshipTypeDefinition))).when(titanGenericDao) + Mockito.doReturn(Either.left(new RelationshipTypeData(newRelationshipTypeDefinition))).when( + janusGraphGenericDao) .updateNode(Mockito.any(), Mockito.eq(RelationshipTypeData.class)); Mockito.doReturn(Either.left(newRelationshipTypeDefinition.getProperties())) @@ -435,7 +437,7 @@ public class RelationshipTypeOperationTest extends ModelTestBase { public void testGetRelationshipTypeByUid() { RelationshipTypeData relationshipTypeData = new RelationshipTypeData(relationshipTypeDefinition); - Mockito.doReturn(Either.left(relationshipTypeData)).when(titanGenericDao) + Mockito.doReturn(Either.left(relationshipTypeData)).when(janusGraphGenericDao) .getNode(Mockito.anyString(), Mockito.any(), Mockito.eq(RelationshipTypeData.class)); Mockito.doReturn(Either.left(relationshipTypeDefinition.getProperties())) @@ -444,11 +446,12 @@ public class RelationshipTypeOperationTest extends ModelTestBase { RelationshipTypeDefinition childRelationshipTypeDefinition = new RelationshipTypeDefinition(); childRelationshipTypeDefinition.setType("tosca.relationships.ContainerChild"); - Mockito.doReturn(Either.left(new ImmutablePair(new RelationshipTypeData(childRelationshipTypeDefinition), null))).when(titanGenericDao) + Mockito.doReturn(Either.left(new ImmutablePair(new RelationshipTypeData(childRelationshipTypeDefinition), null))).when( + janusGraphGenericDao) .getChild(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.eq(RelationshipTypeData.class)); - Either either = + Either either = relationshipTypeOperation.getRelationshipTypeByUid("tosca.relationships.Container1"); assertTrue(either.isLeft() diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java index c70e41b2f1..aef1642e3f 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java @@ -20,18 +20,18 @@ package org.openecomp.sdc.be.model.operations.impl; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import org.junit.*; import org.junit.rules.TestName; import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; -import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; @@ -47,13 +47,13 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.catalog.CatalogComponent; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType; -import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; -import org.openecomp.sdc.be.model.jsontitan.utils.GraphTestUtils; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.NodeType; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTypeOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.utils.GraphTestUtils; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.util.ValidationUtils; import org.springframework.test.context.ContextConfiguration; @@ -70,7 +70,7 @@ import static org.junit.Assert.assertTrue; public class ToscaElementLifecycleOperationTest extends ModelTestBase { @javax.annotation.Resource - protected TitanDao titanDao; + protected JanusGraphDao janusGraphDao; @javax.annotation.Resource private NodeTypeOperation nodeTypeOperation; @@ -105,7 +105,7 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase { createUsers(); createResourceCategory(); createServiceCategory(); - GraphTestUtils.createRootCatalogVertex(titanDao); + GraphTestUtils.createRootCatalogVertex(janusGraphDao); rootVertex = createRootNodeType(); createNodeType("firstVf"); serviceVertex = createTopologyTemplate("firstService"); @@ -263,7 +263,7 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase { assertTrue(res.isLeft()); id = res.left().value().getUniqueId(); verifyInCatalogData(4, null); - // exportGraphMl(titanDao.getGraph().left().value()); + // exportGraphMl(janusGraphDao.getGraph().left().value()); } @@ -322,7 +322,7 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase { public void testGetToscaElOwner_Fail(){ Either result; String toscaEleId = "toscaElementId"; - titanDao.getVertexById(toscaEleId, JsonParseFlagEnum.NoParse); + janusGraphDao.getVertexById(toscaEleId, JsonParseFlagEnum.NoParse); result = lifecycleOperation.getToscaElementOwner(toscaEleId); assertEquals(StorageOperationStatus.NOT_FOUND, result.right().value()); } @@ -351,12 +351,14 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase { subCat.setMetadataProperties(metadataProperties); subCat.updateMetadataJsonWithCurrentMetadataProperties(); - Either catRes = titanDao.createVertex(cat); + Either catRes = janusGraphDao.createVertex(cat); - Either subCatRes = titanDao.createVertex(subCat); + Either subCatRes = janusGraphDao.createVertex(subCat); - TitanOperationStatus status = titanDao.createEdge(catRes.left().value().getVertex(), subCatRes.left().value().getVertex(), EdgeLabelEnum.SUB_CATEGORY, new HashMap<>()); - assertEquals(TitanOperationStatus.OK, status); + JanusGraphOperationStatus + status = janusGraphDao + .createEdge(catRes.left().value().getVertex(), subCatRes.left().value().getVertex(), EdgeLabelEnum.SUB_CATEGORY, new HashMap<>()); + assertEquals(JanusGraphOperationStatus.OK, status); } private void createServiceCategory() { @@ -372,7 +374,7 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase { cat.setMetadataProperties(metadataProperties); cat.updateMetadataJsonWithCurrentMetadataProperties(); - Either catRes = titanDao.createVertex(cat); + Either catRes = janusGraphDao.createVertex(cat); assertTrue(catRes.isLeft()); } @@ -398,7 +400,8 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase { Either createRes = topologyTemplateOperation.createTopologyTemplate(service); assertTrue(createRes.isLeft()); - Either getNodeTyeRes = titanDao.getVertexById(createRes.left().value().getUniqueId()); + Either getNodeTyeRes = janusGraphDao + .getVertexById(createRes.left().value().getUniqueId()); assertTrue(getNodeTyeRes.isLeft()); // serviceVertex = getNodeTyeRes.left().value(); @@ -436,7 +439,8 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase { Either createVFRes = nodeTypeOperation.createNodeType(vf); assertTrue(createVFRes.isLeft()); - Either getNodeTyeRes = titanDao.getVertexById(createVFRes.left().value().getUniqueId()); + Either getNodeTyeRes = janusGraphDao + .getVertexById(createVFRes.left().value().getUniqueId()); assertTrue(getNodeTyeRes.isLeft()); vfVertex = getNodeTyeRes.left().value(); @@ -482,7 +486,7 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase { Either res = nodeTypeOperation.associateElementToData(vfVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, capProps); - // exportGraphMl(titanDao.getGraph().left().value()); + // exportGraphMl(janusGraphDao.getGraph().left().value()); List pathKeys = new ArrayList<>(); pathKeys.add("capName"); @@ -542,7 +546,8 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase { Either createVFRes = nodeTypeOperation.createNodeType(vf); assertTrue(createVFRes.isLeft()); - Either getNodeTyeRes = titanDao.getVertexById(createVFRes.left().value().getUniqueId()); + Either getNodeTyeRes = janusGraphDao + .getVertexById(createVFRes.left().value().getUniqueId()); assertTrue(getNodeTyeRes.isLeft()); return getNodeTyeRes.left().value(); } @@ -559,7 +564,7 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase { ownerV.setMetadataProperties(metadataProperties); ownerV.updateMetadataJsonWithCurrentMetadataProperties(); ownerV.setJson(new HashMap<>()); - Either createUserRes = titanDao.createVertex(ownerV); + Either createUserRes = janusGraphDao.createVertex(ownerV); assertTrue(createUserRes.isLeft()); ownerVertex = createUserRes.left().value(); @@ -574,12 +579,12 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase { modifierV.setMetadataProperties(metadataProperties); modifierV.updateMetadataJsonWithCurrentMetadataProperties(); modifierV.setJson(new HashMap<>()); - createUserRes = titanDao.createVertex(modifierV); + createUserRes = janusGraphDao.createVertex(modifierV); assertTrue(createUserRes.isLeft()); modifierVertex = createUserRes.left().value(); - Either getOwnerRes = lifecycleOperation.findUser(ownerVertex.getUniqueId()); + Either getOwnerRes = lifecycleOperation.findUser(ownerVertex.getUniqueId()); assertTrue(getOwnerRes.isLeft()); } @@ -602,17 +607,17 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase { } private void clearGraph() { - Either graphResult = titanDao.getGraph(); - TitanGraph graph = graphResult.left().value(); + Either graphResult = janusGraphDao.getGraph(); + JanusGraph graph = graphResult.left().value(); - Iterable vertices = graph.query().vertices(); + Iterable vertices = graph.query().vertices(); if (vertices != null) { - Iterator iterator = vertices.iterator(); + Iterator iterator = vertices.iterator(); while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); + JanusGraphVertex vertex = iterator.next(); vertex.remove(); } } - titanDao.commit(); + janusGraphDao.commit(); } } 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 5226a468d7..c094999ebc 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,10 +20,10 @@ package org.openecomp.sdc.be.model.operations.impl; -import com.thinkaurelius.titan.core.*; -import com.thinkaurelius.titan.graphdb.relations.StandardVertexProperty; -import com.thinkaurelius.titan.graphdb.types.system.EmptyVertex; -import com.thinkaurelius.titan.graphdb.types.system.ImplicitKey; +import org.janusgraph.core.*; +import org.janusgraph.graphdb.relations.StandardVertexProperty; +import org.janusgraph.graphdb.types.system.EmptyVertex; +import org.janusgraph.graphdb.types.system.ImplicitKey; import fj.data.Either; import org.apache.tinkerpop.gremlin.structure.*; import org.junit.Before; @@ -34,9 +34,9 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.stubbing.Answer; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; 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.UserStatusEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ModelTestBase; @@ -59,9 +59,10 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; public class UserAdminOperationTest extends ModelTestBase { - private static final TitanGenericDao titanGenericDao = mock(TitanGenericDao.class); + private static final JanusGraphGenericDao JANUS_GRAPH_GENERIC_DAO = mock(JanusGraphGenericDao.class); @InjectMocks - private static final UserAdminOperation userAdminOperation = new UserAdminOperation(titanGenericDao); + private static final UserAdminOperation userAdminOperation = new UserAdminOperation( + JANUS_GRAPH_GENERIC_DAO); private static final String ADMIN = "admin"; @BeforeClass @@ -72,20 +73,20 @@ public class UserAdminOperationTest extends ModelTestBase { @Before public void initMocks() { MockitoAnnotations.initMocks(this); - Mockito.reset(titanGenericDao); - mockTitanUpdate(); - mockTitanDelete(); + Mockito.reset(JANUS_GRAPH_GENERIC_DAO); + mockJanusGraphUpdate(); + mockJanusGraphDelete(); } @Test public void testDeActivateUserDataSuccess() { - UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, true); + UserData userData = mockJanusGraphGet(ADMIN, UserRoleEnum.ADMIN, true); Either eitherUser = userAdminOperation.deActivateUser(userAdminOperation.convertToUser(userData)); - verify(titanGenericDao, times(1)).updateNode(eq(userData), eq(UserData.class)); - verify(titanGenericDao, times(0)).deleteNode(any(UserData.class), eq(UserData.class)); + verify(JANUS_GRAPH_GENERIC_DAO, times(1)).updateNode(eq(userData), eq(UserData.class)); + verify(JANUS_GRAPH_GENERIC_DAO, times(0)).deleteNode(any(UserData.class), eq(UserData.class)); assertTrue(eitherUser.isLeft()); User user = eitherUser.left().value(); assertSame(user.getStatus(), UserStatusEnum.INACTIVE); @@ -93,33 +94,33 @@ public class UserAdminOperationTest extends ModelTestBase { @Test public void testDeleteUserWithoutResources() { - UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, true); + UserData userData = mockJanusGraphGet(ADMIN, UserRoleEnum.ADMIN, true); List edgesList = new ArrayList<>(); - Either, TitanOperationStatus> eitherResult = Either.left(edgesList); - when(titanGenericDao.getEdgesForNode(userData, Direction.BOTH)).thenReturn(eitherResult); + Either, JanusGraphOperationStatus> eitherResult = Either.left(edgesList); + when(JANUS_GRAPH_GENERIC_DAO.getEdgesForNode(userData, Direction.BOTH)).thenReturn(eitherResult); Either eitherUser = userAdminOperation.deleteUserData(ADMIN); - verify(titanGenericDao, times(0)).updateNode(any(UserData.class), eq(UserData.class)); - verify(titanGenericDao, times(1)).deleteNode(userData, UserData.class); + verify(JANUS_GRAPH_GENERIC_DAO, times(0)).updateNode(any(UserData.class), eq(UserData.class)); + verify(JANUS_GRAPH_GENERIC_DAO, times(1)).deleteNode(userData, UserData.class); assertTrue(eitherUser.isLeft()); } @Test public void testDeleteUserWithResources() { - UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, true); + UserData userData = mockJanusGraphGet(ADMIN, UserRoleEnum.ADMIN, true); List edgesList = new ArrayList<>(); edgesList.add(getEmptyEdgeImpl()); - Either, TitanOperationStatus> eitherResult = Either.left(edgesList); - when(titanGenericDao.getEdgesForNode(userData, Direction.BOTH)).thenReturn(eitherResult); + Either, JanusGraphOperationStatus> eitherResult = Either.left(edgesList); + when(JANUS_GRAPH_GENERIC_DAO.getEdgesForNode(userData, Direction.BOTH)).thenReturn(eitherResult); Either eitherUser = userAdminOperation.deleteUserData(ADMIN); - verify(titanGenericDao, times(0)).updateNode(any(UserData.class), eq(UserData.class)); - verify(titanGenericDao, times(0)).deleteNode(any(UserData.class), eq(UserData.class)); + verify(JANUS_GRAPH_GENERIC_DAO, times(0)).updateNode(any(UserData.class), eq(UserData.class)); + verify(JANUS_GRAPH_GENERIC_DAO, times(0)).deleteNode(any(UserData.class), eq(UserData.class)); assertTrue(eitherUser.isRight()); assertSame(eitherUser.right().value(), ActionStatus.USER_HAS_ACTIVE_ELEMENTS); @@ -131,7 +132,7 @@ public class UserAdminOperationTest extends ModelTestBase { String userKey = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User); User user = new User(); user.setUserId(userId); - TitanVertex userVertex = null; + JanusGraphVertex userVertex = null; TestVertex component1 = new TestVertex(null); TestVertex component2 = new TestVertex(true); TestVertex component3 = new TestVertex(false); @@ -142,8 +143,8 @@ public class UserAdminOperationTest extends ModelTestBase { edges.add(edge1); edges.add(edge2); edges.add(edge3); - when(titanGenericDao.getVertexByProperty(userKey, userId)).thenReturn(Either.left(userVertex)); - when(titanGenericDao.getOutgoingEdgesByCriteria(any(), any(), any())).thenReturn(Either.left(edges)); + when(JANUS_GRAPH_GENERIC_DAO.getVertexByProperty(userKey, userId)).thenReturn(Either.left(userVertex)); + when(JANUS_GRAPH_GENERIC_DAO.getOutgoingEdgesByCriteria(any(), any(), any())).thenReturn(Either.left(edges)); Either, StorageOperationStatus> result = userAdminOperation.getUserPendingTasksList(user, new HashMap<>()); assertThat(result.isLeft()).isTrue(); List pendingTasks = result.left().value(); @@ -152,7 +153,7 @@ public class UserAdminOperationTest extends ModelTestBase { assertThat(((TestEdge)pendingTasks.get(1)).getName()).isNotEqualTo("2"); } - private class TestVertex implements TitanVertex { + private class TestVertex implements JanusGraphVertex { private final Boolean isDeleted; @@ -161,12 +162,12 @@ public class UserAdminOperationTest extends ModelTestBase { } @Override - public TitanEdge addEdge(String s, Vertex vertex, Object... objects) { + public JanusGraphEdge addEdge(String s, Vertex vertex, Object... objects) { return null; } @Override - public TitanVertexProperty property(String s, V v, Object... objects) { + public JanusGraphVertexProperty property(String s, V v, Object... objects) { return null; } @@ -181,7 +182,7 @@ public class UserAdminOperationTest extends ModelTestBase { } @Override - public TitanVertexProperty property(VertexProperty.Cardinality cardinality, String s, V v, Object... objects) { + public JanusGraphVertexProperty property(VertexProperty.Cardinality cardinality, String s, V v, Object... objects) { return null; } @@ -221,7 +222,7 @@ public class UserAdminOperationTest extends ModelTestBase { } @Override - public TitanVertexQuery query() { + public JanusGraphVertexQuery query() { return null; } @@ -231,7 +232,7 @@ public class UserAdminOperationTest extends ModelTestBase { } @Override - public TitanTransaction graph() { + public JanusGraphTransaction graph() { return null; } @@ -369,27 +370,28 @@ public class UserAdminOperationTest extends ModelTestBase { }; } - private UserData mockTitanGet(String userId, UserRoleEnum role, boolean isActive) { + private UserData mockJanusGraphGet(String userId, UserRoleEnum role, boolean isActive) { UserData userData = buildUserData(userId, role, isActive); - Either eitherUserData = Either.left(userData); - when(titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class)).thenReturn(eitherUserData); + Either eitherUserData = Either.left(userData); + when(JANUS_GRAPH_GENERIC_DAO + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class)).thenReturn(eitherUserData); return userData; } - private static void mockTitanUpdate() { - doAnswer((Answer>) invocation -> { + private static void mockJanusGraphUpdate() { + doAnswer((Answer>) invocation -> { Object[] args = invocation.getArguments(); UserData retValue = (UserData) args[0]; return Either.left(retValue); - }).when(titanGenericDao).updateNode(any(UserData.class), eq(UserData.class)); + }).when(JANUS_GRAPH_GENERIC_DAO).updateNode(any(UserData.class), eq(UserData.class)); } - private static void mockTitanDelete() { - doAnswer((Answer>) invocation -> { + private static void mockJanusGraphDelete() { + doAnswer((Answer>) invocation -> { Object[] args = invocation.getArguments(); UserData retValue = (UserData) args[0]; return Either.left(retValue); - }).when(titanGenericDao).deleteNode(any(UserData.class), eq(UserData.class)); + }).when(JANUS_GRAPH_GENERIC_DAO).deleteNode(any(UserData.class), eq(UserData.class)); } private static UserData buildUserData(String userId, UserRoleEnum role, boolean isActive) { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/OperationTestsUtil.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/OperationTestsUtil.java index a0b6ea6fd3..71dc5d9517 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/OperationTestsUtil.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/OperationTestsUtil.java @@ -21,9 +21,9 @@ package org.openecomp.sdc.be.model.operations.impl.util; import fj.data.Either; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; 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.User; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; @@ -36,20 +36,20 @@ import org.openecomp.sdc.common.util.ValidationUtils; public class OperationTestsUtil { - public static String deleteAndCreateServiceCategory(String category, TitanGenericDao titanDao) { + public static String deleteAndCreateServiceCategory(String category, JanusGraphGenericDao janusGraphDao) { CategoryData categoryData = new CategoryData(NodeTypeEnum.ServiceNewCategory); categoryData.getCategoryDataDefinition().setName(category); categoryData.getCategoryDataDefinition() .setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(category)); categoryData.getCategoryDataDefinition().setUniqueId(UniqueIdBuilder.buildCategoryUid( ValidationUtils.normalizeCategoryName4Uniqueness(category), NodeTypeEnum.ServiceNewCategory)); - titanDao.deleteNode(categoryData, CategoryData.class); - Either createNode = titanDao.createNode(categoryData, CategoryData.class); + janusGraphDao.deleteNode(categoryData, CategoryData.class); + Either createNode = janusGraphDao.createNode(categoryData, CategoryData.class); return (String) createNode.left().value().getUniqueId(); } public static String deleteAndCreateResourceCategory(String category, String subcategory, - TitanGenericDao titanDao) { + JanusGraphGenericDao janusGraphDao) { CategoryData categoryData = new CategoryData(NodeTypeEnum.ResourceNewCategory); categoryData.getCategoryDataDefinition().setName(category); @@ -64,22 +64,22 @@ public class OperationTestsUtil { .setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(subcategory)); subcategoryData.getSubCategoryDataDefinition().setUniqueId(UniqueIdBuilder .buildSubCategoryUid(categoryData.getCategoryDataDefinition().getUniqueId(), subcategory)); - titanDao.deleteNode(categoryData, CategoryData.class); - titanDao.deleteNode(subcategoryData, SubCategoryData.class); - Either createNode = titanDao.createNode(categoryData, CategoryData.class); - titanDao.createNode(subcategoryData, SubCategoryData.class); - titanDao.createRelation(categoryData, subcategoryData, GraphEdgeLabels.SUB_CATEGORY, null); + janusGraphDao.deleteNode(categoryData, CategoryData.class); + janusGraphDao.deleteNode(subcategoryData, SubCategoryData.class); + Either createNode = janusGraphDao.createNode(categoryData, CategoryData.class); + janusGraphDao.createNode(subcategoryData, SubCategoryData.class); + janusGraphDao.createRelation(categoryData, subcategoryData, GraphEdgeLabels.SUB_CATEGORY, null); return (String) createNode.left().value().getUniqueId(); } - public static void deleteServiceCategory(String category, TitanGenericDao titanDao) { + public static void deleteServiceCategory(String category, JanusGraphGenericDao janusGraphDao) { ServiceCategoryData categoryData = new ServiceCategoryData(category); - titanDao.deleteNode(categoryData, ServiceCategoryData.class); + janusGraphDao.deleteNode(categoryData, ServiceCategoryData.class); } - public static void deleteResourceCategory(String category, String subcategory, TitanGenericDao titanDao) { + public static void deleteResourceCategory(String category, String subcategory, JanusGraphGenericDao janusGraphDao) { ResourceCategoryData categoryData = new ResourceCategoryData(category, subcategory); - titanDao.deleteNode(categoryData, ResourceCategoryData.class); + janusGraphDao.deleteNode(categoryData, ResourceCategoryData.class); } public static User convertUserDataToUser(UserData modifierData) { diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java index 7ba2e097c2..6bd206725b 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java @@ -20,9 +20,9 @@ package org.openecomp.sdc.be.model.operations.impl.util; -import com.thinkaurelius.titan.core.TitanEdge; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphEdge; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Element; import org.apache.tinkerpop.gremlin.structure.Property; @@ -40,12 +40,12 @@ import java.util.Set; public class PrintGraph { - public void printGraphVertices(TitanGraph graph) { + public void printGraphVertices(JanusGraph graph) { - Iterable vertices = graph.query().vertices(); + Iterable vertices = graph.query().vertices(); if (vertices != null) { - Iterator iterator = vertices.iterator(); + Iterator iterator = vertices.iterator(); while (iterator.hasNext()) { Vertex vertex = iterator.next(); } @@ -55,11 +55,11 @@ public class PrintGraph { graph.tx().commit(); } - public void printGraphEdges(TitanGraph graph) { - Iterable vertices = graph.query().edges(); + public void printGraphEdges(JanusGraph graph) { + Iterable vertices = graph.query().edges(); if (vertices != null) { - Iterator iterator = vertices.iterator(); + Iterator iterator = vertices.iterator(); while (iterator.hasNext()) { Edge edge = iterator.next(); @@ -69,16 +69,16 @@ public class PrintGraph { graph.tx().commit(); } - public String buildGraphForWebgraphWiz(TitanGraph graph) { + public String buildGraphForWebgraphWiz(JanusGraph graph) { StringBuilder builder = new StringBuilder(); builder.append("digraph finite_state_machine {\n"); builder.append("rankdir=LR;\n"); builder.append("size=\"15,10\" \n"); - Iterable vertices = graph.query().vertices(); + Iterable vertices = graph.query().vertices(); if (vertices != null) { - Iterator iterator = vertices.iterator(); + Iterator iterator = vertices.iterator(); while (iterator.hasNext()) { Vertex vertex = iterator.next(); @@ -98,10 +98,10 @@ public class PrintGraph { } - Iterable edges = graph.query().edges(); + Iterable edges = graph.query().edges(); if (edges != null) { - Iterator iterator = edges.iterator(); + Iterator iterator = edges.iterator(); while (iterator.hasNext()) { Edge edge = iterator.next(); @@ -309,12 +309,12 @@ public class PrintGraph { return key; } - public int getNumberOfVertices(TitanGraph graph) { + public int getNumberOfVertices(JanusGraph graph) { int counter = 0; - Iterable vertices = graph.query().vertices(); + Iterable vertices = graph.query().vertices(); if (vertices != null) { - Iterator iterator = vertices.iterator(); + Iterator iterator = vertices.iterator(); while (iterator.hasNext()) { Vertex vertex = iterator.next(); counter++; @@ -323,14 +323,14 @@ public class PrintGraph { return counter; } - public Set getVerticesSet(TitanGraph titanGraph) { + public Set getVerticesSet(JanusGraph janusGraph) { Set set = new HashSet<>(); - Iterable vertices = titanGraph.query().vertices(); + Iterable vertices = janusGraph.query().vertices(); if (vertices != null) { - Iterator iterator = vertices.iterator(); + Iterator iterator = vertices.iterator(); while (iterator.hasNext()) { Vertex vertex = iterator.next(); diff --git a/catalog-model/src/test/resources/application-context-test.xml b/catalog-model/src/test/resources/application-context-test.xml index a39a1ee199..475760f51a 100644 --- a/catalog-model/src/test/resources/application-context-test.xml +++ b/catalog-model/src/test/resources/application-context-test.xml @@ -7,12 +7,12 @@ diff --git a/catalog-model/src/test/resources/config/catalog-model/configuration.yaml b/catalog-model/src/test/resources/config/catalog-model/configuration.yaml index 0dbd73995d..96fb28b2f5 100644 --- a/catalog-model/src/test/resources/config/catalog-model/configuration.yaml +++ b/catalog-model/src/test/resources/config/catalog-model/configuration.yaml @@ -26,15 +26,15 @@ released: 2012-11-30 toscaConformanceLevel: 8.0 minToscaConformanceLevel: 3.0 -titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties -titanInMemoryGraph: false -titanLockTimeout: 1800 +janusGraphCfgFile: /home/vagrant/catalog-be/config/catalog-be/janusgraph.properties +janusGraphInMemoryGraph: false +janusGraphLockTimeout: 1800 -# The interval to try and reconnect to titan DB when it is down during ASDC startup: -titanReconnectIntervalInSeconds: 3 +# The interval to try and reconnect to janus graph DB when it is down during ASDC startup: +janusGraphReconnectIntervalInSeconds: 3 -# The read timeout towards Titan DB when health check is invoked: -titanHealthCheckReadTimeout: 1 +# The read timeout towards JanusGraph DB when health check is invoked: +janusGraphHealthCheckReadTimeout: 1 # The interval to try and reconnect to Elasticsearch when it is down during ASDC startup: esReconnectIntervalInSeconds: 3 diff --git a/catalog-model/src/test/resources/config/configuration.yaml b/catalog-model/src/test/resources/config/configuration.yaml index c95715dabd..3dc326e8a0 100644 --- a/catalog-model/src/test/resources/config/configuration.yaml +++ b/catalog-model/src/test/resources/config/configuration.yaml @@ -26,15 +26,15 @@ released: 2012-11-30 toscaConformanceLevel: 8.0 minToscaConformanceLevel: 3.0 -titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties -titanInMemoryGraph: false -titanLockTimeout: 1800 +janusGraphCfgFile: /home/vagrant/catalog-be/config/catalog-be/janusgraph.properties +janusGraphInMemoryGraph: false +janusGraphLockTimeout: 1800 -# The interval to try and reconnect to titan DB when it is down during ASDC startup: -titanReconnectIntervalInSeconds: 3 +# The interval to try and reconnect to janus graph DB when it is down during ASDC startup: +janusGraphReconnectIntervalInSeconds: 3 -# The read timeout towards Titan DB when health check is invoked: -titanHealthCheckReadTimeout: 1 +# The read timeout towards JanusGraph DB when health check is invoked: +janusGraphHealthCheckReadTimeout: 1 # The interval to try and reconnect to Elasticsearch when it is down during ASDC startup: esReconnectIntervalInSeconds: 3 diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java index 3cb7974c06..bf6a022464 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java @@ -71,8 +71,8 @@ public class BeEcompErrorManager extends AbsEcompErrorManager { processEcompError(context, EcompErrorEnum.BeHealthCheckRecovery); } - public void logBeHealthCheckTitanRecovery(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckTitanRecovery); + public void logBeHealthCheckJanusGraphRecovery(String context) { + processEcompError(context, EcompErrorEnum.BeHealthCheckJanusGraphRecovery); } public void logBeHealthCheckElasticSearchRecovery(String context) { @@ -99,8 +99,8 @@ public class BeEcompErrorManager extends AbsEcompErrorManager { processEcompError(context, EcompErrorEnum.BeHealthCheckError); } - public void logBeHealthCheckTitanError(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckTitanError); + public void logBeHealthCheckJanusGraphError(String context) { + processEcompError(context, EcompErrorEnum.BeHealthCheckJanusGraphError); } public void logBeHealthCheckElasticSearchError(String context) { diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java index a9c4ed362a..05e705ce14 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java @@ -69,14 +69,14 @@ public class Configuration extends BasicConfiguration { private Map users; private Map neo4j; private ElasticSearchConfig elasticSearch; - private String titanCfgFile; - private String titanMigrationKeySpaceCfgFile; - private Boolean titanInMemoryGraph; + private String janusGraphCfgFile; + private String janusGraphMigrationKeySpaceCfgFile; + private Boolean janusGraphInMemoryGraph; private int startMigrationFrom; - private Long titanLockTimeout; - private Long titanReconnectIntervalInSeconds; + private Long janusGraphLockTimeout; + private Long janusGraphReconnectIntervalInSeconds; private List healthStatusExclude; - private Long titanHealthCheckReadTimeout; + private Long janusGraphHealthCheckReadTimeout; private Long esReconnectIntervalInSeconds; private Long uebHealthCheckReconnectIntervalInSeconds; private Long uebHealthCheckReadTimeout; @@ -374,28 +374,28 @@ public class Configuration extends BasicConfiguration { this.elasticSearch = elasticSearch; } - public String getTitanCfgFile() { - return titanCfgFile; + public String getJanusGraphCfgFile() { + return janusGraphCfgFile; } - public void setTitanCfgFile(String titanCfgFile) { - this.titanCfgFile = titanCfgFile; + public void setJanusGraphCfgFile(String janusGraphCfgFile) { + this.janusGraphCfgFile = janusGraphCfgFile; } - public String getTitanMigrationKeySpaceCfgFile() { - return titanMigrationKeySpaceCfgFile; + public String getJanusGraphMigrationKeySpaceCfgFile() { + return janusGraphMigrationKeySpaceCfgFile; } - public void setTitanMigrationKeySpaceCfgFile(String titanMigrationKeySpaceCfgFile) { - this.titanMigrationKeySpaceCfgFile = titanMigrationKeySpaceCfgFile; + public void setJanusGraphMigrationKeySpaceCfgFile(String janusGraphMigrationKeySpaceCfgFile) { + this.janusGraphMigrationKeySpaceCfgFile = janusGraphMigrationKeySpaceCfgFile; } - public Boolean getTitanInMemoryGraph() { - return titanInMemoryGraph; + public Boolean getJanusGraphInMemoryGraph() { + return janusGraphInMemoryGraph; } - public void setTitanInMemoryGraph(Boolean titanInMemoryGraph) { - this.titanInMemoryGraph = titanInMemoryGraph; + public void setJanusGraphInMemoryGraph(Boolean janusGraphInMemoryGraph) { + this.janusGraphInMemoryGraph = janusGraphInMemoryGraph; } public int getStartMigrationFrom() { @@ -406,36 +406,36 @@ public class Configuration extends BasicConfiguration { this.startMigrationFrom = startMigrationFrom; } - public Long getTitanLockTimeout() { - return titanLockTimeout; + public Long getJanusGraphLockTimeout() { + return janusGraphLockTimeout; } - public void setTitanLockTimeout(Long titanLockTimeout) { - this.titanLockTimeout = titanLockTimeout; + public void setJanusGraphLockTimeout(Long janusGraphLockTimeout) { + this.janusGraphLockTimeout = janusGraphLockTimeout; } - public Long getTitanHealthCheckReadTimeout() { - return titanHealthCheckReadTimeout; + public Long getJanusGraphHealthCheckReadTimeout() { + return janusGraphHealthCheckReadTimeout; } - public Long getTitanHealthCheckReadTimeout(long defaultVal) { - return titanHealthCheckReadTimeout == null ? defaultVal : titanHealthCheckReadTimeout; + public Long getJanusGraphHealthCheckReadTimeout(long defaultVal) { + return janusGraphHealthCheckReadTimeout == null ? defaultVal : janusGraphHealthCheckReadTimeout; } - public void setTitanHealthCheckReadTimeout(Long titanHealthCheckReadTimeout) { - this.titanHealthCheckReadTimeout = titanHealthCheckReadTimeout; + public void setJanusGraphHealthCheckReadTimeout(Long janusGraphHealthCheckReadTimeout) { + this.janusGraphHealthCheckReadTimeout = janusGraphHealthCheckReadTimeout; } - public Long getTitanReconnectIntervalInSeconds() { - return titanReconnectIntervalInSeconds; + public Long getJanusGraphReconnectIntervalInSeconds() { + return janusGraphReconnectIntervalInSeconds; } - public Long getTitanReconnectIntervalInSeconds(long defaultVal) { - return titanReconnectIntervalInSeconds == null ? defaultVal : titanReconnectIntervalInSeconds; + public Long getJanusGraphReconnectIntervalInSeconds(long defaultVal) { + return janusGraphReconnectIntervalInSeconds == null ? defaultVal : janusGraphReconnectIntervalInSeconds; } - public void setTitanReconnectIntervalInSeconds(Long titanReconnectIntervalInSeconds) { - this.titanReconnectIntervalInSeconds = titanReconnectIntervalInSeconds; + public void setJanusGraphReconnectIntervalInSeconds(Long janusGraphReconnectIntervalInSeconds) { + this.janusGraphReconnectIntervalInSeconds = janusGraphReconnectIntervalInSeconds; } public Long getEsReconnectIntervalInSeconds() { @@ -1365,10 +1365,11 @@ public class Configuration extends BasicConfiguration { .append(format("Released: %s%n", released)).append(format("Supported protocols: %s%n", protocols)) .append(format("Users: %s%n", users)).append(format("Neo4j: %s%n", neo4j)) .append(format("ElasticSearch: %s%n", elasticSearch)) - .append(format("Titan Cfg File: %s%n", titanCfgFile)) - .append(format("Titan In memory: %s%n", titanInMemoryGraph)) - .append(format("Titan lock timeout: %s%n", titanLockTimeout)) - .append(format("Titan reconnect interval seconds: %s%n", titanReconnectIntervalInSeconds)) + .append(format("JanusGraph Cfg File: %s%n", janusGraphCfgFile)) + .append(format("JanusGraph In memory: %s%n", janusGraphInMemoryGraph)) + .append(format("JanusGraph lock timeout: %s%n", janusGraphLockTimeout)) + .append(format("JanusGraph reconnect interval seconds: %s%n", + janusGraphReconnectIntervalInSeconds)) .append(format("excludeResourceCategory: %s%n", excludeResourceCategory)) .append(format("informationalResourceArtifacts: %s%n", informationalResourceArtifacts)) .append(format("deploymentResourceArtifacts: %s%n", deploymentResourceArtifacts)) diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java index b106472f4d..646c655bf0 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java @@ -133,7 +133,7 @@ public final class Constants { //SDC HealthCheck components public static final String HC_COMPONENT_FE = "FE"; public static final String HC_COMPONENT_BE = "BE"; - public static final String HC_COMPONENT_TITAN = "TITAN"; + public static final String HC_COMPONENT_JANUSGRAPH = "JANUSGRAPH"; public static final String HC_COMPONENT_ES = "ES"; public static final String HC_COMPONENT_CASSANDRA = "CASSANDRA"; public static final String HC_COMPONENT_DISTRIBUTION_ENGINE = "DE"; diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java index c887c09149..4d2fb00094 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java @@ -94,7 +94,7 @@ public class HealthCheckInfo { } /*public enum HealthCheckComponent { - FE, BE, TITAN, DE, ON_BOARDING, CASSANDRA, DCAE, + FE, BE, JANUSGRAPH, DE, ON_BOARDING, CASSANDRA, DCAE, CAS, ZU;//Amdocs components }*/ diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java index aabd6d9305..a423354e86 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java @@ -26,16 +26,16 @@ public enum EcompErrorCode { "An Authentication failure occured during access to UEB server. Please check that UEB keys are configured correctly in ASDC BE distribution configuration."), E_199( "Internal authentication problem. Description: %s"), - E_200("ASDC Backend probably lost connectivity to either one of the following components: Titan DB, Cassandra, Onboarding, UEB Cluster. Please check the logs for more information."), E_201( - "ASDC Backend probably lost connectivity to Titan DB. Please check the logs for more information."), E_202( + E_200("ASDC Backend probably lost connectivity to either one of the following components: JanusGraph DB, Cassandra, Onboarding, UEB Cluster. Please check the logs for more information."), E_201( + "ASDC Backend probably lost connectivity to JanusGraph DB. Please check the logs for more information."), E_202( "ASDC Backend probably lost connectivity to ElasticSearch. Please check the logs for more information."), E_203( "ASDC Backend probably lost connectivity to UEB Cluster. Please check the logs for more information.", "Check connectivity to UEB cluster which is configured under parameter uebServers in distribution-configuration.yaml."), E_204( "Unable to connect to a valid ASDC Backend Server", "Please check connectivity from this FE instance towards BE or BE Load Balancer. Please check that parameters in FE configuration.yaml: beHost, beHttpPort and beSslPort point to a valid host and port values."), - E_205("ASDC Backend Recovery to either one of the following components: Titan DB, Cassandra, Onboarding, UEB Cluster."), E_206( - "ASDC Backend connection recovery to Titan DB."), E_207( + E_205("ASDC Backend Recovery to either one of the following components: JanusGraph DB, Cassandra, Onboarding, UEB Cluster."), E_206( + "ASDC Backend connection recovery to JanusGraph DB."), E_207( "ASDC Backend connection recovery to ElasticSearch."), E_208( "ASDC Backend connection recovery to UEB Cluster."), E_209( "Connectivity to ASDC BE Server is recovered."), E_210( @@ -82,7 +82,7 @@ public enum EcompErrorCode { "System Error occured in ASDC Distribution Engine. Please check ASDC logs for more details."), E_504( "Failed adding node of type %s to graph."), E_505( "Operation towards database failed.", - "Please check Titan DB health or look at the logs for more details."), E_506( + "Please check JanusGraph DB health or look at the logs for more details."), E_506( "Unexpected error during operation"), E_507( "Going to execute rollback on graph."), E_508( "Failed to lock object for update. Type = %s, Id = %s"), E_509( diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java index 575cbe9e7e..9d53f7bc2d 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java @@ -40,7 +40,7 @@ public enum EcompErrorEnum { EcompClassification.FATAL), BeHealthCheckRecovery(EcompErrorCode.E_205, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, - EcompClassification.INFORMATION, null), BeHealthCheckTitanRecovery(EcompErrorCode.E_206, ErrorType.RECOVERY, + EcompClassification.INFORMATION, null), BeHealthCheckJanusGraphRecovery(EcompErrorCode.E_206, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), BeHealthCheckElasticSearchRecovery(EcompErrorCode.E_207, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, @@ -54,8 +54,8 @@ public enum EcompErrorEnum { AlarmSeverity.CRITICAL, EcompClassification.ERROR, BeHealthCheckRecovery), - BeHealthCheckTitanError(EcompErrorCode.E_201, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, - EcompClassification.ERROR, BeHealthCheckTitanRecovery), BeHealthCheckElasticSearchError( + BeHealthCheckJanusGraphError(EcompErrorCode.E_201, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, + EcompClassification.ERROR, BeHealthCheckJanusGraphRecovery), BeHealthCheckElasticSearchError( EcompErrorCode.E_202, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR, BeHealthCheckElasticSearchRecovery), BeHealthCheckUebClusterError(EcompErrorCode.E_203, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR, @@ -245,7 +245,7 @@ public enum EcompErrorEnum { * * BeHealthCheckRecovery(EcompErrorCode.E_205, ErrorType.RECOVERY, * AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), - * BeHealthCheckTitanRecovery(EcompErrorCode.E_206, ErrorType.RECOVERY, + * BeHealthCheckJanusGraphRecovery(EcompErrorCode.E_206, ErrorType.RECOVERY, * AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), * BeHealthCheckElasticSearchRecovery(EcompErrorCode.E_207, * ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, @@ -258,9 +258,9 @@ public enum EcompErrorEnum { * AlarmSeverity.CRITICAL, EcompClassification.ERROR, * BeHealthCheckRecovery), * - * BeHealthCheckTitanError(EcompErrorCode.E_201, ErrorType.SYSTEM_ERROR, + * BeHealthCheckJanusGraphError(EcompErrorCode.E_201, ErrorType.SYSTEM_ERROR, * AlarmSeverity.CRITICAL, EcompClassification.ERROR, - * BeHealthCheckTitanRecovery), + * BeHealthCheckJanusGraphRecovery), * BeHealthCheckElasticSearchError(EcompErrorCode.E_202, * ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, * EcompClassification.ERROR, BeHealthCheckElasticSearchRecovery), diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java b/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java index 49caf61bcc..9faaaf9931 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java @@ -43,7 +43,7 @@ public class BaseConfDependent { configurationManager = new ConfigurationManager(configurationSource); - configurationManager.getConfiguration().setTitanInMemoryGraph(true); + configurationManager.getConfiguration().setJanusGraphInMemoryGraph(true); } diff --git a/common-app-api/src/test/java/org/openecomp/sdc/be/config/BeEcompErrorManagerTest.java b/common-app-api/src/test/java/org/openecomp/sdc/be/config/BeEcompErrorManagerTest.java index 440f7587c7..fec97143c6 100644 --- a/common-app-api/src/test/java/org/openecomp/sdc/be/config/BeEcompErrorManagerTest.java +++ b/common-app-api/src/test/java/org/openecomp/sdc/be/config/BeEcompErrorManagerTest.java @@ -58,13 +58,13 @@ public class BeEcompErrorManagerTest { @Test - public void testLogBeHealthCheckTitanRecovery() throws Exception { + public void testLogBeHealthCheckJanusGraphRecovery() throws Exception { BeEcompErrorManager testSubject; String context = ""; // default test testSubject = createTestSubject(); - testSubject.logBeHealthCheckTitanRecovery(context); + testSubject.logBeHealthCheckJanusGraphRecovery(context); } @@ -113,13 +113,13 @@ public class BeEcompErrorManagerTest { @Test - public void testLogBeHealthCheckTitanError() throws Exception { + public void testLogBeHealthCheckJanusGraphError() throws Exception { BeEcompErrorManager testSubject; String context = ""; // default test testSubject = createTestSubject(); - testSubject.logBeHealthCheckTitanError(context); + testSubject.logBeHealthCheckJanusGraphError(context); } diff --git a/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationTest.java b/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationTest.java index 0604e80ffc..49b93c5f58 100644 --- a/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationTest.java +++ b/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationTest.java @@ -402,68 +402,68 @@ public class ConfigurationTest { @Test - public void testGetTitanCfgFile() throws Exception { + public void testGetJanusGraphCfgFile() throws Exception { Configuration testSubject; String result; // default test testSubject = createTestSubject(); - result = testSubject.getTitanCfgFile(); + result = testSubject.getJanusGraphCfgFile(); } @Test - public void testSetTitanCfgFile() throws Exception { + public void testSetJanusGraphCfgFile() throws Exception { Configuration testSubject; - String titanCfgFile = ""; + String janusGraphCfgFile = ""; // default test testSubject = createTestSubject(); - testSubject.setTitanCfgFile(titanCfgFile); + testSubject.setJanusGraphCfgFile(janusGraphCfgFile); } @Test - public void testGetTitanMigrationKeySpaceCfgFile() throws Exception { + public void testGetJanusGraphMigrationKeySpaceCfgFile() throws Exception { Configuration testSubject; String result; // default test testSubject = createTestSubject(); - result = testSubject.getTitanMigrationKeySpaceCfgFile(); + result = testSubject.getJanusGraphMigrationKeySpaceCfgFile(); } @Test - public void testSetTitanMigrationKeySpaceCfgFile() throws Exception { + public void testSetJanusGraphMigrationKeySpaceCfgFile() throws Exception { Configuration testSubject; - String titanMigrationKeySpaceCfgFile = ""; + String janusGraphMigrationKeySpaceCfgFile = ""; // default test testSubject = createTestSubject(); - testSubject.setTitanMigrationKeySpaceCfgFile(titanMigrationKeySpaceCfgFile); + testSubject.setJanusGraphMigrationKeySpaceCfgFile(janusGraphMigrationKeySpaceCfgFile); } @Test - public void testGetTitanInMemoryGraph() throws Exception { + public void testGetJanusGraphInMemoryGraph() throws Exception { Configuration testSubject; Boolean result; // default test testSubject = createTestSubject(); - result = testSubject.getTitanInMemoryGraph(); + result = testSubject.getJanusGraphInMemoryGraph(); } @Test - public void testSetTitanInMemoryGraph() throws Exception { + public void testSetJanusGraphInMemoryGraph() throws Exception { Configuration testSubject; - Boolean titanInMemoryGraph = null; + Boolean janusGraphInMemoryGraph = null; // default test testSubject = createTestSubject(); - testSubject.setTitanInMemoryGraph(titanInMemoryGraph); + testSubject.setJanusGraphInMemoryGraph(janusGraphInMemoryGraph); } @@ -490,72 +490,72 @@ public class ConfigurationTest { @Test - public void testGetTitanLockTimeout() throws Exception { + public void testGetJanusGraphLockTimeout() throws Exception { Configuration testSubject; Long result; // default test testSubject = createTestSubject(); - result = testSubject.getTitanLockTimeout(); + result = testSubject.getJanusGraphLockTimeout(); } @Test - public void testSetTitanLockTimeout() throws Exception { + public void testSetJanusGraphLockTimeout() throws Exception { Configuration testSubject; - Long titanLockTimeout = null; + Long janusGraphLockTimeout = null; // default test testSubject = createTestSubject(); - testSubject.setTitanLockTimeout(titanLockTimeout); + testSubject.setJanusGraphLockTimeout(janusGraphLockTimeout); } @Test - public void testGetTitanHealthCheckReadTimeout() throws Exception { + public void testGetJanusGraphHealthCheckReadTimeout() throws Exception { Configuration testSubject; Long result; // default test testSubject = createTestSubject(); - result = testSubject.getTitanHealthCheckReadTimeout(); + result = testSubject.getJanusGraphHealthCheckReadTimeout(); } @Test - public void testSetTitanHealthCheckReadTimeout() throws Exception { + public void testSetJanusGraphHealthCheckReadTimeout() throws Exception { Configuration testSubject; - Long titanHealthCheckReadTimeout = null; + Long janusGraphHealthCheckReadTimeout = null; // default test testSubject = createTestSubject(); - testSubject.setTitanHealthCheckReadTimeout(titanHealthCheckReadTimeout); + testSubject.setJanusGraphHealthCheckReadTimeout(janusGraphHealthCheckReadTimeout); } @Test - public void testGetTitanReconnectIntervalInSeconds() throws Exception { + public void testGetJanusGraphReconnectIntervalInSeconds() throws Exception { Configuration testSubject; Long result; // default test testSubject = createTestSubject(); - result = testSubject.getTitanReconnectIntervalInSeconds(); + result = testSubject.getJanusGraphReconnectIntervalInSeconds(); } @Test - public void testSetTitanReconnectIntervalInSeconds() throws Exception { + public void testSetJanusGraphReconnectIntervalInSeconds() throws Exception { Configuration testSubject; - Long titanReconnectIntervalInSeconds = null; + Long janusGraphReconnectIntervalInSeconds = null; // default test testSubject = createTestSubject(); - testSubject.setTitanReconnectIntervalInSeconds(titanReconnectIntervalInSeconds); + testSubject.setJanusGraphReconnectIntervalInSeconds(janusGraphReconnectIntervalInSeconds); } diff --git a/common-app-api/src/test/resources/config/common/configuration.yaml b/common-app-api/src/test/resources/config/common/configuration.yaml index 59d4121116..24c7936d7f 100644 --- a/common-app-api/src/test/resources/config/common/configuration.yaml +++ b/common-app-api/src/test/resources/config/common/configuration.yaml @@ -22,15 +22,15 @@ released: 2012-11-30 toscaConformanceLevel: 8.0 minToscaConformanceLevel: 3.0 -titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties -titanInMemoryGraph: false -titanLockTimeout: 1800 +janusGraphCfgFile: /home/vagrant/catalog-be/config/catalog-be/janusgraph.properties +janusGraphInMemoryGraph: false +janusGraphLockTimeout: 1800 -# The interval to try and reconnect to titan DB when it is down during ASDC startup: -titanReconnectIntervalInSeconds: 3 +# The interval to try and reconnect to JanusGraph DB when it is down during ASDC startup: +janusGraphReconnectIntervalInSeconds: 3 -# The read timeout towards Titan DB when health check is invoked: -titanHealthCheckReadTimeout: 1 +# The read timeout towards JanusGraph DB when health check is invoked: +janusGraphHealthCheckReadTimeout: 1 # The interval to try and reconnect to Elasticsearch when it is down during ASDC startup: esReconnectIntervalInSeconds: 3 diff --git a/docs/configuration.rst b/docs/configuration.rst index d9aaea11a5..10bab0d2a1 100644 --- a/docs/configuration.rst +++ b/docs/configuration.rst @@ -125,7 +125,7 @@ environment.json "commitlog_dir": "/var/lib/cassandra/commitlog", "socket_read_timeout": "20000", "socket_connect_timeout": "20000", - "titan_connection_timeout": "10000" + "janusgraph_connection_timeout": "10000" } } } @@ -180,20 +180,20 @@ BE-configuration.yaml # Catalog minimum tosca conformance version minToscaConformanceLevel: 3.0 - # Titan configuration file location - titanCfgFile: /var/lib/jetty/config/catalog-be/titan.properties + # JanusGraph configuration file location + janusGraphCfgFile: /var/lib/jetty/config/catalog-be/janusgraph.properties - # Does titan hold the persistence data in memory - titanInMemoryGraph: false + # Does JanusGraph hold the persistence data in memory + janusGraphInMemoryGraph: false - # The timeout for titan to lock on an object in a transaction - titanLockTimeout: 1800 + # The timeout for JanusGraph to lock on an object in a transaction + janusGraphLockTimeout: 1800 - # The interval to try and reconnect to titan DB when it is down during SDC startup - titanReconnectIntervalInSeconds: 3 + # The interval to try and reconnect to JanusGraph DB when it is down during SDC startup + janusGraphReconnectIntervalInSeconds: 3 - # The read timeout towards Titan DB when health check is invoked - titanHealthCheckReadTimeout: 1 + # The read timeout towards JanusGraph DB when health check is invoked + janusGraphHealthCheckReadTimeout: 1 # The interval to try and reconnect to Elasticsearch when it is down during SDC startup esReconnectIntervalInSeconds: 3 @@ -1118,42 +1118,42 @@ BE-distribution-engine-configuration.yaml currentArtifactInstallationTimeout: 120 -BE-titan.properties +BE-janusgraph.properties ******************* :: - # Titan storage backend + # JanusGraph storage backend storage.backend=cassandra - # Titan storage hostname + # JanusGraph storage hostname storage.hostname=<%= @CASSANDRA_IP %> - # Titan storage port + # JanusGraph storage port storage.port=9160 - # Titan storage username + # JanusGraph storage username storage.username=<%= @CASSANDRA_USR %> - # Titan storage password + # JanusGraph storage password storage.password=<%= @CASSANDRA_PWD %> - # Titan storage connection timeout + # JanusGraph storage connection timeout storage.connection-timeout=10000 - # Titan cassandra keyspace name + # JanusGraph cassandra keyspace name storage.cassandra.keyspace=sdctitan - # Is Titan cassandra ssl is enabled + # Is JanusGraph cassandra ssl is enabled storage.cassandra.ssl.enabled=false - # Titan cassandra ssl truststore file location + # JanusGraph cassandra ssl truststore file location storage.cassandra.ssl.truststore.location=/var/lib/jetty/config/.truststore - # Titan cassandra ssl truststore file password + # JanusGraph cassandra ssl truststore file password storage.cassandra.ssl.truststore.password=Aa123456 - # Should titan use cache + # Should JanusGraph use cache cache.db-cache = false # How long in milliseconds should the cache keep entries before flushing them @@ -1162,22 +1162,22 @@ BE-titan.properties # Default expiration time in milliseconds for entries in the cache cache.db-cache-time = 180000 - # Size of titan database cache + # Size of JanusGraph database cache cache.db-cache-size = 0.5 - # Titan cassandra read consistency level + # JanusGraph cassandra read consistency level storage.cassandra.read-consistency-level=LOCAL_QUORUM - # Titan cassandra write consistency level + # JanusGraph cassandra write consistency level storage.cassandra.write-consistency-level=LOCAL_QUORUM - # Titan cassandra replication strategy class name + # JanusGraph cassandra replication strategy class name storage.cassandra.replication-strategy-class=org.apache.cassandra.locator.NetworkTopologyStrategy - # Titan cassandra replication startegy options + # JanusGraph cassandra replication startegy options storage.cassandra.replication-strategy-options=<%= @DC_NAME %>,<%= @rep_factor %> - # Titan cassandra local data center name + # JanusGraph cassandra local data center name storage.cassandra.astyanax.local-datacenter=<%= @DC_NAME %> # Number of times the system attempts to acquire a lock before giving up and throwing an exception diff --git a/docs/release-notes.rst b/docs/release-notes.rst index 38e7d73de0..38eea464fa 100644 --- a/docs/release-notes.rst +++ b/docs/release-notes.rst @@ -399,7 +399,6 @@ Workflow information is available in readthedocs - [`SDC-951 `__\ ] - update SDC-TOSCA packages - [`SDC-952 `__\ ] - update SDC-DISTRIBUTION-CLIENT packages - [`SDC-953 `__\ ] - update SDC-DOCKER-BASE packages -- [`SDC-954 `__\ ] - update SDC-TITAN-CASSANDRA packages - [`SDC-955 `__\ ] - configuration ovriding capabilities. - [`SDC-957 `__\ ] - add ignore conformance level option - [`SDC-969 `__\ ] - sync1802E to ONAP part 1 diff --git a/docs/sdcsdks.rst b/docs/sdcsdks.rst index df8815f093..67f76cb245 100644 --- a/docs/sdcsdks.rst +++ b/docs/sdcsdks.rst @@ -14,7 +14,6 @@ The sdc project consists of a few additional sub projects listed below: - sdc-tosca - sdc-jtosca - sdc-distribution-client -- sdc-titan-cassandra SDC SDKs Explanations ===================== @@ -26,16 +25,3 @@ SDC-TOSCA and SDC-DISTRIBUTION-CLIENT | The link describes the use of distribution client and the sdc-tosca. | jtosca is used by sdc-tosca as a dependency and is not used separately -SDC-TITAN-CASSANDRA -------------------- - -| This is a link to the github page of Titan Project for extra reading regarding Titan DB: ``_ -| -| SDC forked part of the project to override the default Titan configuration for Cassandra. -| The change allows the use of Titan as an active passive deployment for geo-redundancy. -| -| Titan by default uses QUORUM in Cassandra on write and read operations. -| Using our change allows the use of local QUORUM to read and write only to a specific data center. -| Since the project is at the end of life state the change cannot be merged back to the project. - - diff --git a/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/attributes/default.rb b/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/attributes/default.rb index 9865f8025e..844af469aa 100644 --- a/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/attributes/default.rb +++ b/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/attributes/default.rb @@ -17,7 +17,7 @@ default['cassandra']['datacenter_name'] = "DC-" default['cassandra']['cluster_name'] = "SDC-CS-" default['cassandra']['socket_read_timeout'] = 20000 default['cassandra']['socket_connect_timeout'] = 20000 -default['cassandra']['titan_connection_timeout'] = 10000 +default['cassandra']['janusgraph_connection_timeout'] = 10000 #ExternalTesting diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/resources/configuration.yaml b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/resources/configuration.yaml index 1551d867b5..75f2cc8995 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/resources/configuration.yaml +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/resources/configuration.yaml @@ -22,11 +22,11 @@ beSslPort: 8443 version: 1.0 released: 2012-11-30 -titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties -titanInMemoryGraph: false -titanLockTimeout: 30 -titanReconnectIntervalInSeconds: 3 -titanHealthCheckReadTimeout: 1 +janusGraphCfgFile: /home/vagrant/catalog-be/config/catalog-be/janusgraph.properties +janusGraphInMemoryGraph: false +janusGraphLockTimeout: 30 +janusGraphReconnectIntervalInSeconds: 3 +janusGraphHealthCheckReadTimeout: 1 esReconnectIntervalInSeconds: 3 uebHealthCheckReconnectIntervalInSeconds: 15 uebHealthCheckReadTimeout: 4 diff --git a/openecomp-be/tools/zusammen-tools/src/test/resources/configuration.yaml b/openecomp-be/tools/zusammen-tools/src/test/resources/configuration.yaml index 6636e20726..ecfdfe0e69 100644 --- a/openecomp-be/tools/zusammen-tools/src/test/resources/configuration.yaml +++ b/openecomp-be/tools/zusammen-tools/src/test/resources/configuration.yaml @@ -22,11 +22,11 @@ beSslPort: 8443 version: 1.0 released: 2012-11-30 -titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties -titanInMemoryGraph: false -titanLockTimeout: 30 -titanReconnectIntervalInSeconds: 3 -titanHealthCheckReadTimeout: 1 +janusGraphCfgFile: /home/vagrant/catalog-be/config/catalog-be/janusgraph.properties +janusGraphInMemoryGraph: false +janusGraphLockTimeout: 30 +janusGraphReconnectIntervalInSeconds: 3 +janusGraphHealthCheckReadTimeout: 1 esReconnectIntervalInSeconds: 3 uebHealthCheckReconnectIntervalInSeconds: 15 uebHealthCheckReadTimeout: 4 diff --git a/pom.xml b/pom.xml index 04d4a24746..0df3e3663a 100644 --- a/pom.xml +++ b/pom.xml @@ -38,8 +38,7 @@ Modifications copyright (c) 2018 Nokia 3.3.2 3.3.2 18.0 - 1.0.0 - 1.2.0 + 0.3.1 4.3.18.RELEASE 3.2.3.RELEASE 2.0.1.RELEASE diff --git a/sdc-os-chef/environments/Template.json b/sdc-os-chef/environments/Template.json index 6946a0c24a..e049258cad 100644 --- a/sdc-os-chef/environments/Template.json +++ b/sdc-os-chef/environments/Template.json @@ -88,7 +88,7 @@ "commitlog_dir": "/var/lib/cassandra/commitlog", "socket_read_timeout": "20000", "socket_connect_timeout": "20000", - "titan_connection_timeout": "10000", + "janusgraph_connection_timeout": "10000", "replication_factor": "1" } } diff --git a/sdc-os-chef/kubernetes/sdc/templates/configmaps/sdc-environment-configmap.yaml b/sdc-os-chef/kubernetes/sdc/templates/configmaps/sdc-environment-configmap.yaml index 56cb854aed..0eb5289c64 100644 --- a/sdc-os-chef/kubernetes/sdc/templates/configmaps/sdc-environment-configmap.yaml +++ b/sdc-os-chef/kubernetes/sdc/templates/configmaps/sdc-environment-configmap.yaml @@ -103,7 +103,7 @@ data: "commitlog_dir": "/var/lib/cassandra/commitlog", "socket_read_timeout": "20000", "socket_connect_timeout": "20000", - "titan_connection_timeout": "10000" + "janusgraph_connection_timeout": "10000" } } } diff --git a/test-apis-ci/pom.xml b/test-apis-ci/pom.xml index 6c1f8079a5..f5b36598ad 100644 --- a/test-apis-ci/pom.xml +++ b/test-apis-ci/pom.xml @@ -224,11 +224,10 @@ compile - - com.thinkaurelius.titan - titan-core - ${titan.version} + org.janusgraph + janusgraph-core + ${janusgraph.version} compile @@ -247,9 +246,9 @@ - org.onap.sdc.sdc-titan-cassandra - sdc-titan-cassandra - ${sdc.titan.version} + org.janusgraph + janusgraph-cassandra + ${janusgraph.version} compile diff --git a/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/files/default/conf/log4j.properties b/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/files/default/conf/log4j.properties index d313e92b55..02f783076a 100644 --- a/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/files/default/conf/log4j.properties +++ b/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/files/default/conf/log4j.properties @@ -26,7 +26,7 @@ log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %10c:%L - %m%n log4j.logger.org.apache.cassandra.service.StorageProxy=INFO -log4j.logger.com.thinkaurelius.titan.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout +log4j.logger.org.janusgraph.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout log4j.logger.org.openecomp.sdc.ci.tests.utils=INFO, FILE, stdout log4j.additivity.org.openecomp.sdc.ci.tests.utils=false diff --git a/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/recipes/sanityApiTests_2_setup_configuration.rb b/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/recipes/sanityApiTests_2_setup_configuration.rb index 5fdc55fe18..782bba249d 100644 --- a/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/recipes/sanityApiTests_2_setup_configuration.rb +++ b/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/recipes/sanityApiTests_2_setup_configuration.rb @@ -12,7 +12,7 @@ template "sdc-yaml-config" do :catalogBE_port => node['BE'][:http_port], :webportal_ip => node['Nodes']['FE'], :webportal_port => node['FE'][:http_port], - :titan_file => "#{tests_base}/conf/titan.properties", + :janusgraph_file => "#{tests_base}/conf/janusgraph.properties", :tests_base_ci => "#{tests_base}/CI/tests", :components_path => "#{tests_base}/CI/components", :importResourceConfigDir => "#{tests_base}/CI/importResource", @@ -26,9 +26,9 @@ template "sdc-yaml-config" do }) end -template "titan.properties" do - path "/#{tests_base}/conf/titan.properties" - source "BE-titan.properties.erb" +template "janusgraph.properties" do + path "/#{tests_base}/conf/janusgraph.properties" + source "BE-janusgraph.properties.erb" owner "root" group "root" mode "0755" diff --git a/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/templates/default/BE-janusgraph.properties.erb b/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/templates/default/BE-janusgraph.properties.erb new file mode 100644 index 0000000000..a42c7bf206 --- /dev/null +++ b/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/templates/default/BE-janusgraph.properties.erb @@ -0,0 +1,25 @@ +storage.backend=cassandra +storage.hostname=<%= @CASSANDRA_IP %> +storage.port=9160 +storage.username=<%= @CASSANDRA_USR %> +storage.password=<%= @CASSANDRA_PWD %> +storage.connection-timeout=10000 +storage.cassandra.keyspace=sdctitan + +storage.cassandra.ssl.enabled=false +storage.cassandra.ssl.truststore.location=/var/lib/jetty/config/.truststore +storage.cassandra.ssl.truststore.password=Aa123456 + +cache.db-cache = false +cache.db-cache-clean-wait = 20 +cache.db-cache-time = 180000 +cache.db-cache-size = 0.5 + +storage.cassandra.read-consistency-level=LOCAL_QUORUM +storage.cassandra.write-consistency-level=LOCAL_QUORUM +storage.cassandra.replication-strategy-class=org.apache.cassandra.locator.NetworkTopologyStrategy +storage.cassandra.replication-strategy-options=<%= @DC_NAME %>,<%= @rep_factor %> +storage.cassandra.astyanax.local-datacenter=<%= @DC_NAME %> + +storage.lock.retries=5 +storage.lock.wait-time=500 diff --git a/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/templates/default/BE-titan.properties.erb b/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/templates/default/BE-titan.properties.erb deleted file mode 100644 index a42c7bf206..0000000000 --- a/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/templates/default/BE-titan.properties.erb +++ /dev/null @@ -1,25 +0,0 @@ -storage.backend=cassandra -storage.hostname=<%= @CASSANDRA_IP %> -storage.port=9160 -storage.username=<%= @CASSANDRA_USR %> -storage.password=<%= @CASSANDRA_PWD %> -storage.connection-timeout=10000 -storage.cassandra.keyspace=sdctitan - -storage.cassandra.ssl.enabled=false -storage.cassandra.ssl.truststore.location=/var/lib/jetty/config/.truststore -storage.cassandra.ssl.truststore.password=Aa123456 - -cache.db-cache = false -cache.db-cache-clean-wait = 20 -cache.db-cache-time = 180000 -cache.db-cache-size = 0.5 - -storage.cassandra.read-consistency-level=LOCAL_QUORUM -storage.cassandra.write-consistency-level=LOCAL_QUORUM -storage.cassandra.replication-strategy-class=org.apache.cassandra.locator.NetworkTopologyStrategy -storage.cassandra.replication-strategy-options=<%= @DC_NAME %>,<%= @rep_factor %> -storage.cassandra.astyanax.local-datacenter=<%= @DC_NAME %> - -storage.lock.retries=5 -storage.lock.wait-time=500 diff --git a/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/templates/default/sdc-sanity.yaml.erb b/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/templates/default/sdc-sanity.yaml.erb index 3684b38e32..ce20180d63 100644 --- a/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/templates/default/sdc-sanity.yaml.erb +++ b/test-apis-ci/sdc-api-tests/chef-repo/cookbooks/sdc-api-tests/templates/default/sdc-sanity.yaml.erb @@ -25,7 +25,7 @@ importResourceTestsConfigDir: <%= @importResourceTestsConfigDir %> errorConfigurationFile: <%= @errorConfigurationFile %> configurationFile: <%= @ConfigurationFile %> importTypesConfigDir: <%= @importTypesDir %> -titanPropertiesFile: <%= @titan_file %> +janusGraphPropertiesFile: <%= @janusgraph_file %> systemUnderDebug: true cassandraHost: <%= @CASSANDRA_IP %> @@ -42,7 +42,7 @@ localDataCenter: DC-Automate01 stopOnClassFailure: false -#List of non-abstract resources to keep during titan cleanup between tests +#List of non-abstract resources to keep during JanusGraph cleanup between tests #Only 1.0 version will be kept resourcesNotToDelete: - Compute diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java index 4f74345182..8f6d9db4c2 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java @@ -24,7 +24,7 @@ import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.Status; -import com.thinkaurelius.titan.core.TitanGraph; +import org.janusgraph.core.JanusGraph; import org.apache.commons.collections.CollectionUtils; import org.apache.log4j.Logger; import org.junit.rules.TestName; @@ -67,7 +67,7 @@ public abstract class ComponentBaseTest { protected static final String REPORT_FOLDER = "." + File.separator + "ExtentReport" + File.separator; private static final String VERSIONS_INFO_FILE_NAME = "versions.info"; private static final String REPORT_FILE_NAME = "SDC_CI_Extent_Report.html"; - protected static TitanGraph titanGraph; + protected static JanusGraph janusGraph; public static Config config; protected static ITestContext myContext; @@ -151,7 +151,7 @@ public abstract class ComponentBaseTest { } @AfterSuite(alwaysRun = true) - public static void shutdownTitan() throws Exception { + public static void shutdownJanusGraph() throws Exception { performClean(); } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java index c44c029c76..ffdf2fd02a 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java @@ -68,7 +68,7 @@ public class Config { private String neoDBusername; private String neoDBpassword; - private String titanPropertiesFile; + private String januGraphPropertiesFile; private List packages; private List bugs; private List resourcesNotToDelete; @@ -498,12 +498,12 @@ public class Config { this.neoDBpassword = neoDBpassword; } - public String getTitanPropertiesFile() { - return titanPropertiesFile; + public String getjanuGraphPropertiesFile() { + return januGraphPropertiesFile; } - public void setTitanPropertiesFile(String titanPropertiesFile) { - this.titanPropertiesFile = titanPropertiesFile; + public void setjanuGraphPropertiesFile(String januGraphPropertiesFile) { + this.januGraphPropertiesFile = januGraphPropertiesFile; } public List getPackages() { @@ -640,7 +640,7 @@ public class Config { + ", importTypesConfigDir=" + importTypesConfigDir + ", testSuites=" + testSuites + ", catalogFeHost=" + catalogFeHost + ", catalogFePort=" + catalogFePort + ", catalogBePort=" + catalogBePort + ", catalogBeTlsPort=" + catalogBeTlsPort + ", neoDBusername=" + neoDBusername + ", neoDBpassword=" - + neoDBpassword + ", titanPropertiesFile=" + titanPropertiesFile + ", packages=" + packages + ", bugs=" + + neoDBpassword + ", januGraphPropertiesFile=" + januGraphPropertiesFile + ", packages=" + packages + ", bugs=" + bugs + ", resourcesNotToDelete=" + resourcesNotToDelete + ", resourceCategoriesNotToDelete=" + resourceCategoriesNotToDelete + ", serviceCategoriesNotToDelete=" + serviceCategoriesNotToDelete + ", stopOnClassFailure=" + stopOnClassFailure + ", outputFolder=" + outputFolder + ", reportName=" diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java index fc0e33d3a8..bcd00a10b7 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java @@ -31,7 +31,7 @@ import org.apache.tinkerpop.gremlin.structure.Vertex; import org.openecomp.sdc.ci.tests.api.Urls; import org.openecomp.sdc.ci.tests.config.Config; import org.openecomp.sdc.ci.tests.utils.DbUtils; -import org.openecomp.sdc.ci.tests.utils.DbUtils.TitanState; +import org.openecomp.sdc.ci.tests.utils.DbUtils.JanusGraphState; import org.openecomp.sdc.ci.tests.utils.Utils; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; @@ -45,7 +45,7 @@ public class ImportCapabilityTypeCITest { @AfterClass public static void afterClass() { - DbUtils.shutDowntitan(); + DbUtils.shutDownJanusGraph(); } static Config config = Config.instance(); @@ -55,7 +55,7 @@ public class ImportCapabilityTypeCITest { @Test public void testAddingCapabilityTypes() throws IOException { - TitanState originalState = DbUtils.getCurrentTitanState(); + JanusGraphState originalState = DbUtils.getCurrentJanusGraphState(); String importResourceDir = config.getImportResourceConfigDir(); @@ -64,20 +64,20 @@ public class ImportCapabilityTypeCITest { importCapabilityType(capabilityTypes); Either eitherVertex = DbUtils.getVertexByUId("tosca.capabilities.Test.Ci"); AssertJUnit.assertTrue(eitherVertex.isLeft()); - DbUtils.restoreToTitanState(originalState); + DbUtils.restoreToJanusGraphState(originalState); eitherVertex = DbUtils.getVertexByUId("tosca.capabilities.Test.Ci"); AssertJUnit.assertTrue(eitherVertex.isRight()); } @Test public void AddingCapabilityNotFound() throws IOException { - TitanState originalState = DbUtils.getCurrentTitanState(); + JanusGraphState originalState = DbUtils.getCurrentJanusGraphState(); String importResourceTestsDir = config.getImportResourceTestsConfigDir(); String capabilitiesTests = importResourceTestsDir + File.separator + "capabilityTypesCi.zip"; importCapabilityType(capabilitiesTests); Either eitherVertex = DbUtils.getVertexByUId("tosca.capabilities.NonExsitingCapability"); AssertJUnit.assertTrue(eitherVertex.isRight()); - DbUtils.restoreToTitanState(originalState); + DbUtils.restoreToJanusGraphState(originalState); } public static Integer importAllCapabilityTypes() throws IOException { diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java index dea9084149..5ba7062f3b 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java @@ -21,10 +21,10 @@ package org.openecomp.sdc.ci.tests.utils; import com.google.gson.*; -import com.thinkaurelius.titan.core.TitanEdge; -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; +import org.janusgraph.core.JanusGraphEdge; +import org.janusgraph.core.JanusGraphFactory; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Element; @@ -43,8 +43,8 @@ import java.util.Map.Entry; public class DbUtils { - private static String titanConfigFilePath; - private static TitanGraph titanGraph; + private static String janusGraphConfigFilePath; + private static JanusGraph janusGraph; public static void cleanAllAudits() throws IOException { @@ -74,11 +74,11 @@ public class DbUtils { } public Either getVertexByUId(String uid) { - TitanGraph titanGraph = getTitanGraph(); + JanusGraph janusGraph = getJanusGraph(); Either result = Either.right(false); - // Iterator vertexItr = titanGraph.getVertices().iterator(); + // Iterator vertexItr = janusGraph.getVertices().iterator(); - Iterator vertexItr = titanGraph.query().vertices().iterator(); + Iterator vertexItr = janusGraph.query().vertices().iterator(); while (vertexItr.hasNext()) { Vertex vertex = vertexItr.next(); // String uidFoundVal = vertex.getProperty("uid"); @@ -90,14 +90,14 @@ public class DbUtils { return result; } - public static TitanState getCurrentTitanState() { - TitanGraph titanGraph = getTitanGraph(); + public static JanusGraphState getCurrentJanusGraphState() { + JanusGraph janusGraph = getJanusGraph(); List vertices = new ArrayList<>(); List edges = new ArrayList<>(); - // Iterator edgesItr = titanGraph.getEdges().iterator(); - Iterator edgesItr = titanGraph.query().edges().iterator(); - // Iterator verticesItr = titanGraph.getVertices().iterator(); - Iterator verticesItr = titanGraph.query().vertices().iterator(); + // Iterator edgesItr = janusGraph.getEdges().iterator(); + Iterator edgesItr = janusGraph.query().edges().iterator(); + // Iterator verticesItr = janusGraph.getVertices().iterator(); + Iterator verticesItr = janusGraph.query().vertices().iterator(); while (edgesItr.hasNext()) { edges.add(edgesItr.next()); } @@ -105,43 +105,43 @@ public class DbUtils { vertices.add(verticesItr.next()); } - TitanState currState = new TitanState(edges, vertices); + JanusGraphState currState = new JanusGraphState(edges, vertices); return currState; } // - private static TitanGraph getTitanGraph() { - if (titanGraph == null) { - titanGraph = TitanFactory.open(titanConfigFilePath); + private static JanusGraph getJanusGraph() { + if (janusGraph == null) { + janusGraph = JanusGraphFactory.open(janusGraphConfigFilePath); } - return titanGraph; + return janusGraph; } - public void restoreToTitanState(TitanState titanStateToRestoreTo) { + public void restoreToJanusGraphState(JanusGraphState janusGraphStateToRestoreTo) { List verticesToRemove = new ArrayList<>(), verticesToAdd = new ArrayList<>(); List edgesToRemove = new ArrayList<>(), edgesToAdd = new ArrayList<>(); - TitanState currentTitanState = getCurrentTitanState(); + JanusGraphState currentJanusGraphState = getCurrentJanusGraphState(); List joinedEdges = new ArrayList<>(); - joinedEdges.addAll(titanStateToRestoreTo.edges); - joinedEdges.retainAll(currentTitanState.edges); + joinedEdges.addAll(janusGraphStateToRestoreTo.edges); + joinedEdges.retainAll(currentJanusGraphState.edges); List joinedVertices = new ArrayList<>(); - joinedVertices.addAll(titanStateToRestoreTo.vertices); - joinedVertices.retainAll(currentTitanState.vertices); + joinedVertices.addAll(janusGraphStateToRestoreTo.vertices); + joinedVertices.retainAll(currentJanusGraphState.vertices); - edgesToRemove.addAll(currentTitanState.edges); + edgesToRemove.addAll(currentJanusGraphState.edges); edgesToRemove.removeAll(joinedEdges); - verticesToRemove.addAll(currentTitanState.vertices); + verticesToRemove.addAll(currentJanusGraphState.vertices); verticesToRemove.removeAll(joinedVertices); - edgesToAdd.addAll(titanStateToRestoreTo.edges); + edgesToAdd.addAll(janusGraphStateToRestoreTo.edges); edgesToAdd.removeAll(joinedEdges); - verticesToAdd.addAll(titanStateToRestoreTo.vertices); + verticesToAdd.addAll(janusGraphStateToRestoreTo.vertices); verticesToAdd.removeAll(joinedVertices); modifyGraphAccordingToDelta(verticesToRemove, verticesToAdd, edgesToRemove, edgesToAdd); @@ -151,24 +151,24 @@ public class DbUtils { private void modifyGraphAccordingToDelta(List verticesToRemove, List verticesToAdd, List edgesToRemove, List edgesToAdd) { - TitanGraph titanGraph = getTitanGraph(); + JanusGraph janusGraph = getJanusGraph(); for (Vertex vertex : verticesToRemove) { - // titanGraph.removeVertex(vertex); + // janusGraph.removeVertex(vertex); vertex.remove(); } for (Vertex vertex : verticesToAdd) { - TitanVertex titanVertex = titanGraph.addVertex(); - copyProperties(vertex, titanVertex); + JanusGraphVertex janusGraphVertex = janusGraph.addVertex(); + copyProperties(vertex, janusGraphVertex); } for (Edge edge : edgesToRemove) { - // titanGraph.removeEdge(edge); + // janusGraph.removeEdge(edge); edge.remove(); } for (Edge edge : edgesToAdd) { - // Element addedEdge = titanGraph.addEdge(edge.getId(), + // Element addedEdge = janusGraph.addEdge(edge.getId(), // edge.getVertex(Direction.OUT), edge.getVertex(Direction.IN), // edge.getLabel()); @@ -181,8 +181,8 @@ public class DbUtils { } - // titanGraph.commit(); - titanGraph.tx().commit(); + // janusGraph.commit(); + janusGraph.tx().commit(); } @@ -197,26 +197,26 @@ public class DbUtils { } - public static class TitanState { + public static class JanusGraphState { private List edges; private List vertices; - private TitanState(List edges, List vertices) { + private JanusGraphState(List edges, List vertices) { this.edges = edges; this.vertices = vertices; } @Override public String toString() { - return "TitanState [edges=" + edges.size() + ", vertices=" + vertices.size() + "]"; + return "JanusGraphState [edges=" + edges.size() + ", vertices=" + vertices.size() + "]"; } } - public void shutDowntitan() { - if (titanGraph != null) { - // titanGraph.shutdown(); - titanGraph.close(); + public void shutDownJanusGraph() { + if (janusGraph != null) { + // janusGraph.shutdown(); + janusGraph.close(); } } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/post/Install.java b/test-apis-ci/src/main/java/org/openecomp/sdc/post/Install.java index 803e190b59..322a3171ad 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/post/Install.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/post/Install.java @@ -20,9 +20,9 @@ package org.openecomp.sdc.post; -import org.openecomp.sdc.be.dao.DAOTitanStrategy; -import org.openecomp.sdc.be.dao.titan.TitanGraphClient; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.DAOJanusGraphStrategy; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import java.io.File; @@ -30,39 +30,39 @@ public class Install { public static void main(String[] args) { if (args == null || args.length == 0) { - System.out.println("Usage: org.openecomp.sdc.post.Install path_to_titan.properties"); + System.out.println("Usage: org.openecomp.sdc.post.Install path_to_janusgraph.properties"); System.exit(1); } - String titanPropsFile = args[0]; + String janusGraphPropsFile = args[0]; - if (!isFileExists(titanPropsFile)) { + if (!isFileExists(janusGraphPropsFile)) { System.exit(2); } - if (!createTitanSchema(titanPropsFile)) { + if (!createJanusGraphSchema(janusGraphPropsFile)) { System.exit(3); } System.exit(0); } - private static boolean createTitanSchema(String titanPropsFile) { - TitanGraphClient titanGraphClient = new TitanGraphClient(new DAOTitanStrategy()); - TitanOperationStatus status = titanGraphClient.createGraph(titanPropsFile); - if (TitanOperationStatus.OK == status) { - System.out.println("Titan schema ,indexes and default values created successfully."); + private static boolean createJanusGraphSchema(String janusGraphPropsFile) { + JanusGraphClient janusGraphClient = new JanusGraphClient(new DAOJanusGraphStrategy()); + JanusGraphOperationStatus status = janusGraphClient.createGraph(janusGraphPropsFile); + if (JanusGraphOperationStatus.OK == status) { + System.out.println("JanusGraph schema ,indexes and default values created successfully."); return true; } else { System.out.println( - "Problem while creating titan schema ,indexes and default values. (" + status.name() + ")"); + "Problem while creating janusgraph schema ,indexes and default values. (" + status.name() + ")"); return false; } } - private static boolean isFileExists(String titanPropsFile) { - File f = new File(titanPropsFile); + private static boolean isFileExists(String janusGraphPropsFile) { + File f = new File(janusGraphPropsFile); if (!f.exists()) { - System.out.println(titanPropsFile + " not found"); + System.out.println(janusGraphPropsFile + " not found"); return false; } return true; diff --git a/test-apis-ci/src/main/resources/ci/conf/attsdc.yaml b/test-apis-ci/src/main/resources/ci/conf/attsdc.yaml index 21294e76f5..4ef9ce4ccd 100644 --- a/test-apis-ci/src/main/resources/ci/conf/attsdc.yaml +++ b/test-apis-ci/src/main/resources/ci/conf/attsdc.yaml @@ -30,7 +30,7 @@ configurationFile: ../catalog-be/src/main/resources/config/configuration.yaml importTypesConfigDir: src/test/resources/CI/importTypesTest -titanPropertiesFile: src/main/resources/ci/conf/titan.properties +janusGraphPropertiesFile: src/main/resources/ci/conf/janusgraph.properties cassandraHost: 127.0.0.1 cassandraAuthenticate: false cassandraUsername: koko @@ -47,7 +47,7 @@ localDataCenter: DC-Automate01 stopOnClassFailure: false -#List of non-abstract resources to keep during titan cleanup between tests +#List of non-abstract resources to keep during janus graph cleanup between tests #Only 1.0 version will be kept resourcesNotToDelete: - Compute diff --git a/test-apis-ci/src/main/resources/ci/conf/janusgraph.properties b/test-apis-ci/src/main/resources/ci/conf/janusgraph.properties new file mode 100644 index 0000000000..5411a44224 --- /dev/null +++ b/test-apis-ci/src/main/resources/ci/conf/janusgraph.properties @@ -0,0 +1,11 @@ +storage.backend=cassandra +storage.hostname=localhost +storage.port=9160 + +cache.db-cache = false +cache.db-cache-clean-wait = 20 +cache.db-cache-time = 180000 +cache.db-cache-size = 0.5 + +cache.tx-cache-size = 500000 +storage.cassandra.keyspace=sdctitan diff --git a/test-apis-ci/src/main/resources/ci/conf/log4j.properties b/test-apis-ci/src/main/resources/ci/conf/log4j.properties index d313e92b55..02f783076a 100644 --- a/test-apis-ci/src/main/resources/ci/conf/log4j.properties +++ b/test-apis-ci/src/main/resources/ci/conf/log4j.properties @@ -26,7 +26,7 @@ log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %10c:%L - %m%n log4j.logger.org.apache.cassandra.service.StorageProxy=INFO -log4j.logger.com.thinkaurelius.titan.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout +log4j.logger.org.janusgraph.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout log4j.logger.org.openecomp.sdc.ci.tests.utils=INFO, FILE, stdout log4j.additivity.org.openecomp.sdc.ci.tests.utils=false diff --git a/test-apis-ci/src/main/resources/ci/conf/titan.properties b/test-apis-ci/src/main/resources/ci/conf/titan.properties deleted file mode 100644 index 5411a44224..0000000000 --- a/test-apis-ci/src/main/resources/ci/conf/titan.properties +++ /dev/null @@ -1,11 +0,0 @@ -storage.backend=cassandra -storage.hostname=localhost -storage.port=9160 - -cache.db-cache = false -cache.db-cache-clean-wait = 20 -cache.db-cache-time = 180000 -cache.db-cache-size = 0.5 - -cache.tx-cache-size = 500000 -storage.cassandra.keyspace=sdctitan diff --git a/test-apis-ci/src/main/resources/log4j.properties b/test-apis-ci/src/main/resources/log4j.properties index d313e92b55..02f783076a 100644 --- a/test-apis-ci/src/main/resources/log4j.properties +++ b/test-apis-ci/src/main/resources/log4j.properties @@ -26,7 +26,7 @@ log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %10c:%L - %m%n log4j.logger.org.apache.cassandra.service.StorageProxy=INFO -log4j.logger.com.thinkaurelius.titan.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout +log4j.logger.org.janusgraph.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout log4j.logger.org.openecomp.sdc.ci.tests.utils=INFO, FILE, stdout log4j.additivity.org.openecomp.sdc.ci.tests.utils=false diff --git a/test-apis-ci/src/test/resources/config/test-apis-ci/configuration.yaml b/test-apis-ci/src/test/resources/config/test-apis-ci/configuration.yaml index 70a3e5541e..ba1526dd90 100644 --- a/test-apis-ci/src/test/resources/config/test-apis-ci/configuration.yaml +++ b/test-apis-ci/src/test/resources/config/test-apis-ci/configuration.yaml @@ -26,15 +26,15 @@ released: 2012-11-30 toscaConformanceLevel: 8.0 minToscaConformanceLevel: 3.0 -titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties -titanInMemoryGraph: false -titanLockTimeout: 1800 +janusGraphCfgFile: /home/vagrant/catalog-be/config/catalog-be/janusgraph.properties +janusGraphInMemoryGraph: false +janusGraphLockTimeout: 1800 -# The interval to try and reconnect to titan DB when it is down during ASDC startup: -titanReconnectIntervalInSeconds: 3 +# The interval to try and reconnect to janusGraph DB when it is down during ASDC startup: +janusGraphReconnectIntervalInSeconds: 3 -# The read timeout towards Titan DB when health check is invoked: -titanHealthCheckReadTimeout: 1 +# The read timeout towards JanusGraph DB when health check is invoked: +janusGraphHealthCheckReadTimeout: 1 # The interval to try and reconnect to Elasticsearch when it is down during ASDC startup: esReconnectIntervalInSeconds: 3 diff --git a/ui-ci/pom.xml b/ui-ci/pom.xml index be40b0497c..afaf49143b 100644 --- a/ui-ci/pom.xml +++ b/ui-ci/pom.xml @@ -144,31 +144,6 @@ compile - - - com.thinkaurelius.titan - titan-core - ${titan.version} - compile - - - commons-collections - commons-collections - - - groovy - org.codehaus.groovy - - - - - - org.onap.sdc.sdc-titan-cassandra - sdc-titan-cassandra - ${sdc.titan.version} - compile - - org.codehaus.jackson jackson-mapper-asl diff --git a/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/files/default/conf/log4j.properties b/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/files/default/conf/log4j.properties index d313e92b55..02f783076a 100644 --- a/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/files/default/conf/log4j.properties +++ b/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/files/default/conf/log4j.properties @@ -26,7 +26,7 @@ log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %10c:%L - %m%n log4j.logger.org.apache.cassandra.service.StorageProxy=INFO -log4j.logger.com.thinkaurelius.titan.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout +log4j.logger.org.janusgraph.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout log4j.logger.org.openecomp.sdc.ci.tests.utils=INFO, FILE, stdout log4j.additivity.org.openecomp.sdc.ci.tests.utils=false diff --git a/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/recipes/sanityUiTests_2_setup_configuration.rb b/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/recipes/sanityUiTests_2_setup_configuration.rb index 1d4c6d6f6c..04a65413f5 100644 --- a/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/recipes/sanityUiTests_2_setup_configuration.rb +++ b/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/recipes/sanityUiTests_2_setup_configuration.rb @@ -11,7 +11,7 @@ template "sdc-yaml-config" do :catalogBE_port => node['BE'][:http_port], :webportal_ip => node['Nodes']['FE'], :webportal_port => node['FE'][:http_port], - :titan_file => "#{tests_base}/conf/titan.properties", + :janusgraph_file => "#{tests_base}/conf/janusgraph.properties", :tests_base_ci => "#{tests_base}/CI/tests", :components_path => "#{tests_base}/CI/components", :importResourceConfigDir => "#{tests_base}/CI/importResource", @@ -26,9 +26,9 @@ template "sdc-yaml-config" do }) end -template "titan.properties" do - path "/#{tests_base}/conf/titan.properties" - source "BE-titan.properties.erb" +template "janusgraph.properties" do + path "/#{tests_base}/conf/janusgraph.properties" + source "BE-janusgraph.properties.erb" owner "root" group "root" mode "0755" diff --git a/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/templates/default/BE-janusgraph.properties.erb b/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/templates/default/BE-janusgraph.properties.erb new file mode 100644 index 0000000000..a42c7bf206 --- /dev/null +++ b/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/templates/default/BE-janusgraph.properties.erb @@ -0,0 +1,25 @@ +storage.backend=cassandra +storage.hostname=<%= @CASSANDRA_IP %> +storage.port=9160 +storage.username=<%= @CASSANDRA_USR %> +storage.password=<%= @CASSANDRA_PWD %> +storage.connection-timeout=10000 +storage.cassandra.keyspace=sdctitan + +storage.cassandra.ssl.enabled=false +storage.cassandra.ssl.truststore.location=/var/lib/jetty/config/.truststore +storage.cassandra.ssl.truststore.password=Aa123456 + +cache.db-cache = false +cache.db-cache-clean-wait = 20 +cache.db-cache-time = 180000 +cache.db-cache-size = 0.5 + +storage.cassandra.read-consistency-level=LOCAL_QUORUM +storage.cassandra.write-consistency-level=LOCAL_QUORUM +storage.cassandra.replication-strategy-class=org.apache.cassandra.locator.NetworkTopologyStrategy +storage.cassandra.replication-strategy-options=<%= @DC_NAME %>,<%= @rep_factor %> +storage.cassandra.astyanax.local-datacenter=<%= @DC_NAME %> + +storage.lock.retries=5 +storage.lock.wait-time=500 diff --git a/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/templates/default/BE-titan.properties.erb b/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/templates/default/BE-titan.properties.erb deleted file mode 100644 index a42c7bf206..0000000000 --- a/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/templates/default/BE-titan.properties.erb +++ /dev/null @@ -1,25 +0,0 @@ -storage.backend=cassandra -storage.hostname=<%= @CASSANDRA_IP %> -storage.port=9160 -storage.username=<%= @CASSANDRA_USR %> -storage.password=<%= @CASSANDRA_PWD %> -storage.connection-timeout=10000 -storage.cassandra.keyspace=sdctitan - -storage.cassandra.ssl.enabled=false -storage.cassandra.ssl.truststore.location=/var/lib/jetty/config/.truststore -storage.cassandra.ssl.truststore.password=Aa123456 - -cache.db-cache = false -cache.db-cache-clean-wait = 20 -cache.db-cache-time = 180000 -cache.db-cache-size = 0.5 - -storage.cassandra.read-consistency-level=LOCAL_QUORUM -storage.cassandra.write-consistency-level=LOCAL_QUORUM -storage.cassandra.replication-strategy-class=org.apache.cassandra.locator.NetworkTopologyStrategy -storage.cassandra.replication-strategy-options=<%= @DC_NAME %>,<%= @rep_factor %> -storage.cassandra.astyanax.local-datacenter=<%= @DC_NAME %> - -storage.lock.retries=5 -storage.lock.wait-time=500 diff --git a/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/templates/default/sdc-sanity.yaml.erb b/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/templates/default/sdc-sanity.yaml.erb index 70063e00d5..c8a3258625 100644 --- a/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/templates/default/sdc-sanity.yaml.erb +++ b/ui-ci/sdc-ui-tests/chef-repo/cookbooks/sdc-ui-tests/templates/default/sdc-sanity.yaml.erb @@ -40,4 +40,4 @@ importResourceTestsConfigDir: <%= @importResourceTestsConfigDir %> errorConfigurationFile: <%= @errorConfigurationFile %> configurationFile: <%= @ConfigurationFile %> importTypesConfigDir: <%= @importTypesDir %> -titanPropertiesFile: <%= @titan_file %> \ No newline at end of file +janusGraphPropertiesFile: <%= @janusgraph_file %> \ No newline at end of file diff --git a/ui-ci/src/main/resources/ci/conf/attsdc.yaml b/ui-ci/src/main/resources/ci/conf/attsdc.yaml index e6790939cf..36018d7b7f 100644 --- a/ui-ci/src/main/resources/ci/conf/attsdc.yaml +++ b/ui-ci/src/main/resources/ci/conf/attsdc.yaml @@ -45,13 +45,13 @@ localDataCenter: DC-Automate01 useBrowserMobProxy: false captureTraffic: false -titanPropertiesFile: src/main/resources/ci/conf/titan.properties +janusGraphPropertiesFile: src/main/resources/ci/conf/janusgraph.properties stopOnClassFailure: false #todo onboardingBeHost: 192.168.33.10 onboardingBePort: 8080 -#List of non-abstract resources to keep during titan cleanup between tests +#List of non-abstract resources to keep during JanusGraph cleanup between tests #Only 1.0 version will be kept resourcesNotToDelete: - tosca.nodes.Compute diff --git a/ui-ci/src/main/resources/ci/conf/log4j.properties b/ui-ci/src/main/resources/ci/conf/log4j.properties index 3e159ec8df..0bdf0fad8c 100644 --- a/ui-ci/src/main/resources/ci/conf/log4j.properties +++ b/ui-ci/src/main/resources/ci/conf/log4j.properties @@ -26,7 +26,7 @@ log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %10c:%L - %m%n log4j.logger.org.apache.cassandra.service.StorageProxy=DEBUG -log4j.logger.com.thinkaurelius.titan.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout +log4j.logger.org.janusgraph.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout log4j.logger.org.openecomp.sdc.ci.tests.utils=TRACE, FILE, stdout log4j.additivity.org.openecomp.sdc.ci.tests.utils=false -- cgit 1.2.3-korg